1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-08-09 10:22:46 +03:00

eslint ---fix for prefer-const

This commit is contained in:
David Baker
2017-01-19 17:42:10 +00:00
parent 9b354ba99e
commit 7bca05af64
60 changed files with 1732 additions and 1732 deletions

View File

@@ -22,8 +22,8 @@ limitations under the License.
* @module base-apis
*/
let httpApi = require("./http-api");
let utils = require("./utils");
const httpApi = require("./http-api");
const utils = require("./utils");
/**
* Low-level wrappers for the Matrix APIs
@@ -60,7 +60,7 @@ function MatrixBaseApis(opts) {
this.baseUrl = opts.baseUrl;
this.idBaseUrl = opts.idBaseUrl;
let httpOpts = {
const httpOpts = {
baseUrl: opts.baseUrl,
idBaseUrl: opts.idBaseUrl,
accessToken: opts.accessToken,
@@ -142,7 +142,7 @@ MatrixBaseApis.prototype.register = function(
auth.session = sessionId;
}
let params = {
const params = {
auth: auth,
};
if (username !== undefined && username !== null) {
@@ -183,7 +183,7 @@ MatrixBaseApis.prototype.registerGuest = function(opts, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.registerRequest = function(data, kind, callback) {
let params = {};
const params = {};
if (kind) {
params.kind = kind;
}
@@ -210,7 +210,7 @@ MatrixBaseApis.prototype.loginFlows = function(callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.login = function(loginType, data, callback) {
let login_data = {
const login_data = {
type: loginType,
};
@@ -318,7 +318,7 @@ MatrixBaseApis.prototype.deactivateAccount = function(auth, callback) {
* @return {string} HS URL to hit to for the fallback interface
*/
MatrixBaseApis.prototype.getFallbackAuthUrl = function(loginType, authSessionId) {
let path = utils.encodeUri("/auth/$loginType/fallback/web", {
const path = utils.encodeUri("/auth/$loginType/fallback/web", {
$loginType: loginType,
});
@@ -358,7 +358,7 @@ MatrixBaseApis.prototype.createRoom = function(options, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.roomState = function(roomId, callback) {
let path = utils.encodeUri("/rooms/$roomId/state", {$roomId: roomId});
const path = utils.encodeUri("/rooms/$roomId/state", {$roomId: roomId});
return this._http.authedRequest(callback, "GET", path);
};
@@ -372,7 +372,7 @@ MatrixBaseApis.prototype.roomState = function(roomId, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getStateEvent = function(roomId, eventType, stateKey, callback) {
let pathParams = {
const pathParams = {
$roomId: roomId,
$eventType: eventType,
$stateKey: stateKey,
@@ -397,7 +397,7 @@ MatrixBaseApis.prototype.getStateEvent = function(roomId, eventType, stateKey, c
*/
MatrixBaseApis.prototype.sendStateEvent = function(roomId, eventType, content, stateKey,
callback) {
let pathParams = {
const pathParams = {
$roomId: roomId,
$eventType: eventType,
$stateKey: stateKey,
@@ -419,7 +419,7 @@ MatrixBaseApis.prototype.sendStateEvent = function(roomId, eventType, content, s
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.redactEvent = function(roomId, eventId, callback) {
let path = utils.encodeUri("/rooms/$roomId/redact/$eventId", {
const path = utils.encodeUri("/rooms/$roomId/redact/$eventId", {
$roomId: roomId,
$eventId: eventId,
});
@@ -437,7 +437,7 @@ MatrixBaseApis.prototype.roomInitialSync = function(roomId, limit, callback) {
if (utils.isFunction(limit)) {
callback = limit; limit = undefined;
}
let path = utils.encodeUri("/rooms/$roomId/initialSync",
const path = utils.encodeUri("/rooms/$roomId/initialSync",
{$roomId: roomId}
);
if (!limit) {
@@ -474,7 +474,7 @@ MatrixBaseApis.prototype.publicRooms = function(options, callback) {
options = {};
}
let query_params = {};
const query_params = {};
if (options.server) {
query_params.server = options.server;
delete options.server;
@@ -498,10 +498,10 @@ MatrixBaseApis.prototype.publicRooms = function(options, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.createAlias = function(alias, roomId, callback) {
let path = utils.encodeUri("/directory/room/$alias", {
const path = utils.encodeUri("/directory/room/$alias", {
$alias: alias,
});
let data = {
const data = {
room_id: roomId,
};
return this._http.authedRequest(
@@ -518,7 +518,7 @@ MatrixBaseApis.prototype.createAlias = function(alias, roomId, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.deleteAlias = function(alias, callback) {
let path = utils.encodeUri("/directory/room/$alias", {
const path = utils.encodeUri("/directory/room/$alias", {
$alias: alias,
});
return this._http.authedRequest(
@@ -535,7 +535,7 @@ MatrixBaseApis.prototype.deleteAlias = function(alias, callback) {
*/
MatrixBaseApis.prototype.getRoomIdForAlias = function(alias, callback) {
// TODO: deprecate this or resolveRoomAlias
let path = utils.encodeUri("/directory/room/$alias", {
const path = utils.encodeUri("/directory/room/$alias", {
$alias: alias,
});
return this._http.authedRequest(
@@ -551,7 +551,7 @@ MatrixBaseApis.prototype.getRoomIdForAlias = function(alias, callback) {
*/
MatrixBaseApis.prototype.resolveRoomAlias = function(roomAlias, callback) {
// TODO: deprecate this or getRoomIdForAlias
let path = utils.encodeUri("/directory/room/$alias", {$alias: roomAlias});
const path = utils.encodeUri("/directory/room/$alias", {$alias: roomAlias});
return this._http.request(callback, "GET", path);
};
@@ -564,7 +564,7 @@ MatrixBaseApis.prototype.resolveRoomAlias = function(roomAlias, callback) {
*/
MatrixBaseApis.prototype.getRoomDirectoryVisibility =
function(roomId, callback) {
let path = utils.encodeUri("/directory/list/room/$roomId", {
const path = utils.encodeUri("/directory/list/room/$roomId", {
$roomId: roomId,
});
return this._http.authedRequest(callback, "GET", path);
@@ -582,7 +582,7 @@ MatrixBaseApis.prototype.getRoomDirectoryVisibility =
*/
MatrixBaseApis.prototype.setRoomDirectoryVisibility =
function(roomId, visibility, callback) {
let path = utils.encodeUri("/directory/list/room/$roomId", {
const path = utils.encodeUri("/directory/list/room/$roomId", {
$roomId: roomId,
});
return this._http.authedRequest(
@@ -605,7 +605,7 @@ MatrixBaseApis.prototype.setRoomDirectoryVisibility =
*/
MatrixBaseApis.prototype.setRoomDirectoryVisibilityAppService =
function(networkId, roomId, visibility, callback) {
let path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", {
const path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", {
$networkId: networkId,
$roomId: roomId,
});
@@ -692,7 +692,7 @@ MatrixBaseApis.prototype.getProfileInfo = function(userId, info, callback) {
callback = info; info = undefined;
}
let path = info ?
const path = info ?
utils.encodeUri("/profile/$userId/$info",
{ $userId: userId, $info: info }) :
utils.encodeUri("/profile/$userId",
@@ -710,7 +710,7 @@ MatrixBaseApis.prototype.getProfileInfo = function(userId, info, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getThreePids = function(callback) {
let path = "/account/3pid";
const path = "/account/3pid";
return this._http.authedRequest(
callback, "GET", path, undefined, undefined
);
@@ -724,8 +724,8 @@ MatrixBaseApis.prototype.getThreePids = function(callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.addThreePid = function(creds, bind, callback) {
let path = "/account/3pid";
let data = {
const path = "/account/3pid";
const data = {
'threePidCreds': creds,
'bind': bind,
};
@@ -743,8 +743,8 @@ MatrixBaseApis.prototype.addThreePid = function(creds, bind, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.deleteThreePid = function(medium, address) {
let path = "/account/3pid/delete";
let data = {
const path = "/account/3pid/delete";
const data = {
'medium': medium,
'address': address,
};
@@ -762,8 +762,8 @@ MatrixBaseApis.prototype.deleteThreePid = function(medium, address) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.setPassword = function(authDict, newPassword, callback) {
let path = "/account/password";
let data = {
const path = "/account/password";
const data = {
'auth': authDict,
'new_password': newPassword,
};
@@ -783,7 +783,7 @@ MatrixBaseApis.prototype.setPassword = function(authDict, newPassword, callback)
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getDevices = function() {
let path = "/devices";
const path = "/devices";
return this._http.authedRequestWithPrefix(
undefined, "GET", path, undefined, undefined,
httpApi.PREFIX_UNSTABLE
@@ -799,7 +799,7 @@ MatrixBaseApis.prototype.getDevices = function() {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.setDeviceDetails = function(device_id, body) {
let path = utils.encodeUri("/devices/$device_id", {
const path = utils.encodeUri("/devices/$device_id", {
$device_id: device_id,
});
@@ -819,11 +819,11 @@ MatrixBaseApis.prototype.setDeviceDetails = function(device_id, body) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.deleteDevice = function(device_id, auth) {
let path = utils.encodeUri("/devices/$device_id", {
const path = utils.encodeUri("/devices/$device_id", {
$device_id: device_id,
});
let body = {};
const body = {};
if (auth) {
body.auth = auth;
@@ -847,7 +847,7 @@ MatrixBaseApis.prototype.deleteDevice = function(device_id, auth) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.getPushers = function(callback) {
let path = "/pushers";
const path = "/pushers";
return this._http.authedRequest(
callback, "GET", path, undefined, undefined
);
@@ -862,7 +862,7 @@ MatrixBaseApis.prototype.getPushers = function(callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.setPusher = function(pusher, callback) {
let path = "/pushers/set";
const path = "/pushers/set";
return this._http.authedRequest(
callback, "POST", path, null, pusher
);
@@ -888,7 +888,7 @@ MatrixBaseApis.prototype.getPushRules = function(callback) {
*/
MatrixBaseApis.prototype.addPushRule = function(scope, kind, ruleId, body, callback) {
// NB. Scope not uri encoded because devices need the '/'
let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
$kind: kind,
$ruleId: ruleId,
});
@@ -907,7 +907,7 @@ MatrixBaseApis.prototype.addPushRule = function(scope, kind, ruleId, body, callb
*/
MatrixBaseApis.prototype.deletePushRule = function(scope, kind, ruleId, callback) {
// NB. Scope not uri encoded because devices need the '/'
let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", {
$kind: kind,
$ruleId: ruleId,
});
@@ -926,7 +926,7 @@ MatrixBaseApis.prototype.deletePushRule = function(scope, kind, ruleId, callback
*/
MatrixBaseApis.prototype.setPushRuleEnabled = function(scope, kind,
ruleId, enabled, callback) {
let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", {
const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", {
$kind: kind,
$ruleId: ruleId,
});
@@ -947,7 +947,7 @@ MatrixBaseApis.prototype.setPushRuleEnabled = function(scope, kind,
*/
MatrixBaseApis.prototype.setPushRuleActions = function(scope, kind,
ruleId, actions, callback) {
let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", {
const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", {
$kind: kind,
$ruleId: ruleId,
});
@@ -970,7 +970,7 @@ MatrixBaseApis.prototype.setPushRuleActions = function(scope, kind,
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.search = function(opts, callback) {
let queryparams = {};
const queryparams = {};
if (opts.next_batch) {
queryparams.next_batch = opts.next_batch;
}
@@ -999,7 +999,7 @@ MatrixBaseApis.prototype.search = function(opts, callback) {
*/
MatrixBaseApis.prototype.uploadKeysRequest = function(content, opts, callback) {
opts = opts || {};
let deviceId = opts.device_id;
const deviceId = opts.device_id;
let path;
if (deviceId) {
path = utils.encodeUri("/keys/upload/$deviceId", {
@@ -1024,12 +1024,12 @@ MatrixBaseApis.prototype.uploadKeysRequest = function(content, opts, callback) {
* an error response ({@link module:http-api.MatrixError}).
*/
MatrixBaseApis.prototype.downloadKeysForUsers = function(userIds, callback) {
let downloadQuery = {};
const downloadQuery = {};
for (let i = 0; i < userIds.length; ++i) {
downloadQuery[userIds[i]] = {};
}
let content = {device_keys: downloadQuery};
const content = {device_keys: downloadQuery};
return this._http.authedRequestWithPrefix(
callback, "POST", "/keys/query", undefined, content,
httpApi.PREFIX_UNSTABLE
@@ -1047,20 +1047,20 @@ MatrixBaseApis.prototype.downloadKeysForUsers = function(userIds, callback) {
* an error response ({@link module:http-api.MatrixError}).
*/
MatrixBaseApis.prototype.claimOneTimeKeys = function(devices, key_algorithm) {
let queries = {};
const queries = {};
if (key_algorithm === undefined) {
key_algorithm = "signed_curve25519";
}
for (let i = 0; i < devices.length; ++i) {
let userId = devices[i][0];
let deviceId = devices[i][1];
let query = queries[userId] || {};
const userId = devices[i][0];
const deviceId = devices[i][1];
const query = queries[userId] || {};
queries[userId] = query;
query[deviceId] = key_algorithm;
}
let content = {one_time_keys: queries};
const content = {one_time_keys: queries};
return this._http.authedRequestWithPrefix(
undefined, "POST", "/keys/claim", undefined, content,
httpApi.PREFIX_UNSTABLE
@@ -1093,7 +1093,7 @@ MatrixBaseApis.prototype.claimOneTimeKeys = function(devices, key_algorithm) {
*/
MatrixBaseApis.prototype.requestEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) {
let params = {
const params = {
client_secret: clientSecret,
email: email,
send_attempt: sendAttempt,
@@ -1117,7 +1117,7 @@ MatrixBaseApis.prototype.requestEmailToken = function(email, clientSecret,
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixBaseApis.prototype.lookupThreePid = function(medium, address, callback) {
let params = {
const params = {
medium: medium,
address: address,
};
@@ -1144,12 +1144,12 @@ MatrixBaseApis.prototype.lookupThreePid = function(medium, address, callback) {
MatrixBaseApis.prototype.sendToDevice = function(
eventType, contentMap, txnId
) {
let path = utils.encodeUri("/sendToDevice/$eventType/$txnId", {
const path = utils.encodeUri("/sendToDevice/$eventType/$txnId", {
$eventType: eventType,
$txnId: txnId ? txnId : this.makeTxnId(),
});
let body = {
const body = {
messages: contentMap,
};
@@ -1183,7 +1183,7 @@ MatrixBaseApis.prototype.getThirdpartyProtocols = function() {
* @return {module:client.Promise} Resolves to the result object
*/
MatrixBaseApis.prototype.getThirdpartyLocation = function(protocol, params) {
let path = utils.encodeUri("/thirdparty/location/$protocol", {
const path = utils.encodeUri("/thirdparty/location/$protocol", {
$protocol: protocol,
});

View File

@@ -15,31 +15,31 @@ limitations under the License.
*/
"use strict";
let PushProcessor = require('./pushprocessor');
const PushProcessor = require('./pushprocessor');
/**
* This is an internal module. See {@link MatrixClient} for the public class.
* @module client
*/
let EventEmitter = require("events").EventEmitter;
let q = require("q");
let url = require('url');
const EventEmitter = require("events").EventEmitter;
const q = require("q");
const url = require('url');
let httpApi = require("./http-api");
let MatrixEvent = require("./models/event").MatrixEvent;
let EventStatus = require("./models/event").EventStatus;
let EventTimeline = require("./models/event-timeline");
let SearchResult = require("./models/search-result");
let StubStore = require("./store/stub");
let webRtcCall = require("./webrtc/call");
let utils = require("./utils");
let contentRepo = require("./content-repo");
let Filter = require("./filter");
let SyncApi = require("./sync");
let MatrixBaseApis = require("./base-apis");
let MatrixError = httpApi.MatrixError;
const httpApi = require("./http-api");
const MatrixEvent = require("./models/event").MatrixEvent;
const EventStatus = require("./models/event").EventStatus;
const EventTimeline = require("./models/event-timeline");
const SearchResult = require("./models/search-result");
const StubStore = require("./store/stub");
const webRtcCall = require("./webrtc/call");
const utils = require("./utils");
const contentRepo = require("./content-repo");
const Filter = require("./filter");
const SyncApi = require("./sync");
const MatrixBaseApis = require("./base-apis");
const MatrixError = httpApi.MatrixError;
let SCROLLBACK_DELAY_MS = 3000;
const SCROLLBACK_DELAY_MS = 3000;
let CRYPTO_ENABLED = false;
try {
@@ -111,16 +111,16 @@ function MatrixClient(opts) {
this.deviceId = opts.deviceId || null;
let userId = (opts.userId || null);
const userId = (opts.userId || null);
this.credentials = {
userId: userId,
};
this.scheduler = opts.scheduler;
if (this.scheduler) {
let self = this;
const self = this;
this.scheduler.setProcessFunction(function(eventToSend) {
let room = self.getRoom(eventToSend.getRoomId());
const room = self.getRoom(eventToSend.getRoomId());
if (eventToSend.status !== EventStatus.SENDING) {
_updatePendingEventStatus(room, eventToSend,
EventStatus.SENDING);
@@ -136,7 +136,7 @@ function MatrixClient(opts) {
// try constructing a MatrixCall to see if we are running in an environment
// which has WebRTC. If we are, listen for and handle m.call.* events.
let call = webRtcCall.createNewMatrixCall(this);
const call = webRtcCall.createNewMatrixCall(this);
this._supportsVoip = false;
if (call) {
setupCallEventHandler(this);
@@ -427,7 +427,7 @@ MatrixClient.prototype.getEventSenderDeviceInfo = function(event) {
* {@link module:client~MatrixClient#setDeviceVerified|setDeviceVerified}.
*/
MatrixClient.prototype.isEventSenderVerified = function(event) {
let device = this.getEventSenderDeviceInfo(event);
const device = this.getEventSenderDeviceInfo(event);
if (!device) {
return false;
}
@@ -574,7 +574,7 @@ MatrixClient.prototype.getUsers = function() {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setAccountData = function(eventType, contents, callback) {
let path = utils.encodeUri("/user/$userId/account_data/$type", {
const path = utils.encodeUri("/user/$userId/account_data/$type", {
$userId: this.credentials.userId,
$type: eventType,
});
@@ -619,7 +619,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
opts.syncRoom = true;
}
let room = this.getRoom(roomIdOrAlias);
const room = this.getRoom(roomIdOrAlias);
if (room && room.hasMembershipState(this.credentials.userId, "join")) {
return q(room);
}
@@ -633,21 +633,21 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
);
}
let defer = q.defer();
const defer = q.defer();
let self = this;
const self = this;
sign_promise.then(function(signed_invite_object) {
let data = {};
const data = {};
if (signed_invite_object) {
data.third_party_signed = signed_invite_object;
}
let path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias});
const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias});
return self._http.authedRequest(undefined, "POST", path, undefined, data);
}).then(function(res) {
let roomId = res.room_id;
let syncApi = new SyncApi(self, self._clientOpts);
let room = syncApi.createRoom(roomId);
const roomId = res.room_id;
const syncApi = new SyncApi(self, self._clientOpts);
const room = syncApi.createRoom(roomId);
if (opts.syncRoom) {
// v2 will do this for us
// return syncApi.syncRoom(room);
@@ -692,7 +692,7 @@ MatrixClient.prototype.cancelPendingEvent = function(event) {
// then tell the room about the change of state, which will remove it
// from the room's list of pending events.
let room = this.getRoom(event.getRoomId());
const room = this.getRoom(event.getRoomId());
_updatePendingEventStatus(room, event, EventStatus.CANCELLED);
};
@@ -727,7 +727,7 @@ MatrixClient.prototype.setRoomTopic = function(roomId, topic, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.getRoomTags = function(roomId, callback) {
let path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/", {
const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/", {
$userId: this.credentials.userId,
$roomId: roomId,
});
@@ -745,7 +745,7 @@ MatrixClient.prototype.getRoomTags = function(roomId, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setRoomTag = function(roomId, tagName, metadata, callback) {
let path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
$userId: this.credentials.userId,
$roomId: roomId,
$tag: tagName,
@@ -763,7 +763,7 @@ MatrixClient.prototype.setRoomTag = function(roomId, tagName, metadata, callback
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.deleteRoomTag = function(roomId, tagName, callback) {
let path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", {
$userId: this.credentials.userId,
$roomId: roomId,
$tag: tagName,
@@ -783,7 +783,7 @@ MatrixClient.prototype.deleteRoomTag = function(roomId, tagName, callback) {
*/
MatrixClient.prototype.setRoomAccountData = function(roomId, eventType,
content, callback) {
let path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", {
const path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", {
$userId: this.credentials.userId,
$roomId: roomId,
$type: eventType,
@@ -814,7 +814,7 @@ MatrixClient.prototype.setPowerLevel = function(roomId, userId, powerLevel,
content = utils.deepCopy(event.getContent());
}
content.users[userId] = powerLevel;
let path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", {
const path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", {
$roomId: roomId,
});
return this._http.authedRequest(
@@ -844,8 +844,8 @@ MatrixClient.prototype.sendEvent = function(roomId, eventType, content, txnId,
// we always construct a MatrixEvent when sending because the store and
// scheduler use them. We'll extract the params back out if it turns out
// the client has no scheduler or store.
let room = this.getRoom(roomId);
let localEvent = new MatrixEvent({
const room = this.getRoom(roomId);
const localEvent = new MatrixEvent({
event_id: "~" + roomId + ":" + txnId,
user_id: this.credentials.userId,
room_id: roomId,
@@ -939,9 +939,9 @@ function _updatePendingEventStatus(room, event, newStatus) {
}
function _sendEventHttpRequest(client, event) {
let txnId = event._txnId ? event._txnId : client.makeTxnId();
const txnId = event._txnId ? event._txnId : client.makeTxnId();
let pathParams = {
const pathParams = {
$roomId: event.getRoomId(),
$eventType: event.getWireType(),
$stateKey: event.getStateKey(),
@@ -993,7 +993,7 @@ MatrixClient.prototype.sendMessage = function(roomId, content, txnId, callback)
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.sendTextMessage = function(roomId, body, txnId, callback) {
let content = {
const content = {
msgtype: "m.text",
body: body,
};
@@ -1009,7 +1009,7 @@ MatrixClient.prototype.sendTextMessage = function(roomId, body, txnId, callback)
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.sendNotice = function(roomId, body, txnId, callback) {
let content = {
const content = {
msgtype: "m.notice",
body: body,
};
@@ -1025,7 +1025,7 @@ MatrixClient.prototype.sendNotice = function(roomId, body, txnId, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.sendEmoteMessage = function(roomId, body, txnId, callback) {
let content = {
const content = {
msgtype: "m.emote",
body: body,
};
@@ -1048,7 +1048,7 @@ MatrixClient.prototype.sendImageMessage = function(roomId, url, info, text, call
if (!text) {
text = "Image";
}
let content = {
const content = {
msgtype: "m.image",
url: url,
info: info,
@@ -1066,7 +1066,7 @@ MatrixClient.prototype.sendImageMessage = function(roomId, url, info, text, call
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.sendHtmlMessage = function(roomId, body, htmlBody, callback) {
let content = {
const content = {
msgtype: "m.text",
format: "org.matrix.custom.html",
body: body,
@@ -1084,7 +1084,7 @@ MatrixClient.prototype.sendHtmlMessage = function(roomId, body, htmlBody, callba
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.sendHtmlNotice = function(roomId, body, htmlBody, callback) {
let content = {
const content = {
msgtype: "m.notice",
format: "org.matrix.custom.html",
body: body,
@@ -1102,7 +1102,7 @@ MatrixClient.prototype.sendHtmlNotice = function(roomId, body, htmlBody, callbac
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.sendHtmlEmote = function(roomId, body, htmlBody, callback) {
let content = {
const content = {
msgtype: "m.emote",
format: "org.matrix.custom.html",
body: body,
@@ -1124,16 +1124,16 @@ MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) {
return q({}); // guests cannot send receipts so don't bother.
}
let path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", {
const path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", {
$roomId: event.getRoomId(),
$receiptType: receiptType,
$eventId: event.getId(),
});
let promise = this._http.authedRequest(
const promise = this._http.authedRequest(
callback, "POST", path, undefined, {}
);
let room = this.getRoom(event.getRoomId());
const room = this.getRoom(event.getRoomId());
if (room) {
room._addLocalEchoReceipt(this.credentials.userId, event, receiptType);
}
@@ -1168,13 +1168,13 @@ MatrixClient.prototype.sendReadReceipt = function(event, callback) {
* May return synthesized attributes if the URL lacked OG meta.
*/
MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
let key = ts + "_" + url;
let og = this.urlPreviewCache[key];
const key = ts + "_" + url;
const og = this.urlPreviewCache[key];
if (og) {
return q(og);
}
let self = this;
const self = this;
return this._http.authedRequestWithPrefix(
callback, "GET", "/preview_url", {
url: url,
@@ -1200,11 +1200,11 @@ MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callba
return q({}); // guests cannot send typing notifications so don't bother.
}
let path = utils.encodeUri("/rooms/$roomId/typing/$userId", {
const path = utils.encodeUri("/rooms/$roomId/typing/$userId", {
$roomId: roomId,
$userId: this.credentials.userId,
});
let data = {
const data = {
typing: isTyping,
};
if (isTyping) {
@@ -1251,7 +1251,7 @@ MatrixClient.prototype.inviteByEmail = function(roomId, email, callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, callback) {
let path = utils.encodeUri(
const path = utils.encodeUri(
"/rooms/$roomId/invite",
{ $roomId: roomId }
);
@@ -1312,12 +1312,12 @@ MatrixClient.prototype.forget = function(roomId, deleteRoom, callback) {
if (deleteRoom === undefined) {
deleteRoom = true;
}
let promise = _membershipChange(this, roomId, undefined, "forget", undefined,
const promise = _membershipChange(this, roomId, undefined, "forget", undefined,
callback);
if (!deleteRoom) {
return promise;
}
let self = this;
const self = this;
return promise.then(function(response) {
self.store.removeRoom(roomId);
self.emit("deleteRoom", roomId);
@@ -1370,7 +1370,7 @@ function _setMembershipState(client, roomId, userId, membershipValue, reason,
callback = reason; reason = undefined;
}
let path = utils.encodeUri(
const path = utils.encodeUri(
"/rooms/$roomId/state/m.room.member/$userId",
{ $roomId: roomId, $userId: userId}
);
@@ -1397,7 +1397,7 @@ function _membershipChange(client, roomId, userId, membership, reason, callback)
callback = reason; reason = undefined;
}
let path = utils.encodeUri("/rooms/$room_id/$membership", {
const path = utils.encodeUri("/rooms/$room_id/$membership", {
$room_id: roomId,
$membership: membership,
});
@@ -1417,7 +1417,7 @@ function _membershipChange(client, roomId, userId, membership, reason, callback)
*/
MatrixClient.prototype.getPushActionsForEvent = function(event) {
if (!event.getPushActions()) {
let pushProcessor = new PushProcessor(this);
const pushProcessor = new PushProcessor(this);
event.setPushActions(pushProcessor.actionsForEvent(event));
}
return event.getPushActions();
@@ -1434,7 +1434,7 @@ MatrixClient.prototype.getPushActionsForEvent = function(event) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setProfileInfo = function(info, data, callback) {
let path = utils.encodeUri("/profile/$userId/$info", {
const path = utils.encodeUri("/profile/$userId/$info", {
$userId: this.credentials.userId,
$info: info,
});
@@ -1497,7 +1497,7 @@ MatrixClient.prototype.mxcUrlToHttp =
* @throws If 'presence' isn't a valid presence enum value.
*/
MatrixClient.prototype.setPresence = function(opts, callback) {
let path = utils.encodeUri("/presence/$userId/status", {
const path = utils.encodeUri("/presence/$userId/status", {
$userId: this.credentials.userId,
});
@@ -1505,7 +1505,7 @@ MatrixClient.prototype.setPresence = function(opts, callback) {
opts = { presence: opts };
}
let validStates = ["offline", "online", "unavailable"];
const validStates = ["offline", "online", "unavailable"];
if (validStates.indexOf(opts.presence) == -1) {
throw new Error("Bad presence value: " + opts.presence);
}
@@ -1515,7 +1515,7 @@ MatrixClient.prototype.setPresence = function(opts, callback) {
};
function _presenceList(callback, client, opts, method) {
let path = utils.encodeUri("/presence/list/$userId", {
const path = utils.encodeUri("/presence/list/$userId", {
$userId: client.credentials.userId,
});
return client._http.authedRequest(callback, method, path, undefined, opts);
@@ -1539,7 +1539,7 @@ MatrixClient.prototype.getPresenceList = function(callback) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.inviteToPresenceList = function(callback, userIds) {
let opts = {"invite": userIds};
const opts = {"invite": userIds};
return _presenceList(callback, this, opts, "POST");
};
@@ -1551,7 +1551,7 @@ MatrixClient.prototype.inviteToPresenceList = function(callback, userIds) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
**/
MatrixClient.prototype.dropFromPresenceList = function(callback, userIds) {
let opts = {"drop": userIds};
const opts = {"drop": userIds};
return _presenceList(callback, this, opts, "POST");
};
@@ -1583,7 +1583,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
if (info.promise) {
return info.promise;
} else if (info.errorTs) {
let timeWaitedMs = Date.now() - info.errorTs;
const timeWaitedMs = Date.now() - info.errorTs;
timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);
}
@@ -1591,7 +1591,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
return q(room); // already at the start.
}
// attempt to grab more events from the store first
let numAdded = this.store.scrollback(room, limit).length;
const numAdded = this.store.scrollback(room, limit).length;
if (numAdded === limit) {
// store contained everything we needed.
return q(room);
@@ -1599,26 +1599,26 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
// reduce the required number of events appropriately
limit = limit - numAdded;
let path = utils.encodeUri(
const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: room.roomId}
);
let params = {
const params = {
from: room.oldState.paginationToken,
limit: limit,
dir: 'b',
};
let defer = q.defer();
const defer = q.defer();
info = {
promise: defer.promise,
errorTs: null,
};
let self = this;
const self = this;
// wait for a time before doing this request
// (which may be 0 in order not to special case the code paths)
q.delay(timeToWaitMs).then(function() {
return self._http.authedRequest(callback, "GET", path, params);
}).done(function(res) {
let matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self));
const matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self));
room.addEventsToTimeline(matrixEvents, true, room.getLiveTimeline());
room.oldState.paginationToken = res.end;
if (res.chunk.length === 0) {
@@ -1653,40 +1653,40 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
// TODO: we should implement a backoff (as per scrollback()) to deal more
// nicely with HTTP errors.
opts = opts || {};
let backwards = opts.backwards || false;
const backwards = opts.backwards || false;
let token = eventContext.getPaginateToken(backwards);
const token = eventContext.getPaginateToken(backwards);
if (!token) {
// no more results.
return q.reject(new Error("No paginate token"));
}
let dir = backwards ? 'b' : 'f';
let pendingRequest = eventContext._paginateRequests[dir];
const dir = backwards ? 'b' : 'f';
const pendingRequest = eventContext._paginateRequests[dir];
if (pendingRequest) {
// already a request in progress - return the existing promise
return pendingRequest;
}
let path = utils.encodeUri(
const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: eventContext.getEvent().getRoomId()}
);
let params = {
const params = {
from: token,
limit: ('limit' in opts) ? opts.limit : 30,
dir: dir,
};
let self = this;
let promise =
const self = this;
const promise =
self._http.authedRequest(undefined, "GET", path, params
).then(function(res) {
let token = res.end;
if (res.chunk.length === 0) {
token = null;
} else {
let matrixEvents = utils.map(res.chunk, self.getEventMapper());
const matrixEvents = utils.map(res.chunk, self.getEventMapper());
if (backwards) {
// eventContext expects the events in timeline order, but
// back-pagination returns them in reverse order.
@@ -1730,7 +1730,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
return q(timelineSet.getTimelineForEvent(eventId));
}
let path = utils.encodeUri(
const path = utils.encodeUri(
"/rooms/$roomId/context/$eventId", {
$roomId: timelineSet.room.roomId,
$eventId: eventId,
@@ -1739,8 +1739,8 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
// TODO: we should implement a backoff (as per scrollback()) to deal more
// nicely with HTTP errors.
let self = this;
let promise =
const self = this;
const promise =
self._http.authedRequest(undefined, "GET", path
).then(function(res) {
if (!res.event) {
@@ -1757,10 +1757,10 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
// have known state.
// events_after is already backwards; events_before is forwards.
res.events_after.reverse();
let events = res.events_after
const events = res.events_after
.concat([res.event])
.concat(res.events_before);
let matrixEvents = utils.map(events, self.getEventMapper());
const matrixEvents = utils.map(events, self.getEventMapper());
let timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId());
if (!timeline) {
@@ -1776,7 +1776,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
// room's index again. On the other hand, there's no guarantee the
// event ended up anywhere, if it was later redacted, so we just
// return the timeline we first thought of.
let tl = timelineSet.getTimelineForEvent(eventId) || timeline;
const tl = timelineSet.getTimelineForEvent(eventId) || timeline;
return tl;
});
return promise;
@@ -1797,12 +1797,12 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
* events and we reached either end of the timeline; else true.
*/
MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
let isNotifTimeline = (eventTimeline.getTimelineSet() === this._notifTimelineSet);
const isNotifTimeline = (eventTimeline.getTimelineSet() === this._notifTimelineSet);
// TODO: we should implement a backoff (as per scrollback()) to deal more
// nicely with HTTP errors.
opts = opts || {};
let backwards = opts.backwards || false;
const backwards = opts.backwards || false;
if (isNotifTimeline) {
if (!backwards) {
@@ -1810,15 +1810,15 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
}
}
let dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;
const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;
let token = eventTimeline.getPaginationToken(dir);
const token = eventTimeline.getPaginationToken(dir);
if (!token) {
// no token - no results.
return q(false);
}
let pendingRequest = eventTimeline._paginationRequests[dir];
const pendingRequest = eventTimeline._paginationRequests[dir];
if (pendingRequest) {
// already a request in progress - return the existing promise
@@ -1826,7 +1826,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
}
let path, params, promise;
let self = this;
const self = this;
if (isNotifTimeline) {
path = "/notifications";
@@ -1843,12 +1843,12 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
this._http.authedRequestWithPrefix(undefined, "GET", path, params,
undefined, httpApi.PREFIX_UNSTABLE
).then(function(res) {
let token = res.next_token;
let matrixEvents = [];
const token = res.next_token;
const matrixEvents = [];
for (let i = 0; i < res.notifications.length; i++) {
let notification = res.notifications[i];
let event = self.getEventMapper()(notification.event);
const notification = res.notifications[i];
const event = self.getEventMapper()(notification.event);
event.setPushActions(
PushProcessor.actionListToActionsObject(notification.actions)
);
@@ -1871,7 +1871,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
});
eventTimeline._paginationRequests[dir] = promise;
} else {
let room = this.getRoom(eventTimeline.getRoomId());
const room = this.getRoom(eventTimeline.getRoomId());
if (!room) {
throw new Error("Unknown room " + eventTimeline.getRoomId());
}
@@ -1885,7 +1885,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
dir: dir,
};
let filter = eventTimeline.getFilter();
const filter = eventTimeline.getFilter();
if (filter) {
// XXX: it's horrific that /messages' filter parameter doesn't match
// /sync's one - see https://matrix.org/jira/browse/SPEC-451
@@ -1895,8 +1895,8 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
promise =
this._http.authedRequest(undefined, "GET", path, params
).then(function(res) {
let token = res.end;
let matrixEvents = utils.map(res.chunk, self.getEventMapper());
const token = res.end;
const matrixEvents = utils.map(res.chunk, self.getEventMapper());
eventTimeline.getTimelineSet()
.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);
@@ -1988,7 +1988,7 @@ MatrixClient.prototype.stopPeeking = function() {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setGuestAccess = function(roomId, opts) {
let writePromise = this.sendStateEvent(roomId, "m.room.guest_access", {
const writePromise = this.sendStateEvent(roomId, "m.room.guest_access", {
guest_access: opts.allowJoin ? "can_join" : "forbidden",
});
@@ -2103,12 +2103,12 @@ MatrixClient.prototype.requestPasswordEmailToken = function(email, clientSecret,
MatrixClient.prototype._requestTokenFromEndpoint = function(endpoint,
email, clientSecret,
sendAttempt, nextLink, callback) {
let id_server_url = url.parse(this.idBaseUrl);
const id_server_url = url.parse(this.idBaseUrl);
if (id_server_url.host === null) {
throw new Error("Invalid ID server URL: " + this.idBaseUrl);
}
let params = {
const params = {
client_secret: clientSecret,
email: email,
send_attempt: sendAttempt,
@@ -2136,7 +2136,7 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) {
// and its id is the room id.
if (this.pushRules) {
for (let i = 0; i < this.pushRules[scope].room.length; i++) {
let rule = this.pushRules[scope].room[i];
const rule = this.pushRules[scope].room[i];
if (rule.rule_id === roomId) {
return rule;
}
@@ -2158,11 +2158,11 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
let self = this;
const self = this;
let deferred, hasDontNotifyRule;
// Get the existing room-kind push rule if any
let roomPushRule = this.getRoomPushRule(scope, roomId);
const roomPushRule = this.getRoomPushRule(scope, roomId);
if (roomPushRule) {
if (0 <= roomPushRule.actions.indexOf("dont_notify")) {
hasDontNotifyRule = true;
@@ -2202,7 +2202,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
if (deferred) {
// Update this.pushRules when the operation completes
let ruleRefreshDeferred = q.defer();
const ruleRefreshDeferred = q.defer();
deferred.done(function() {
self.getPushRules().done(function(result) {
self.pushRules = result;
@@ -2273,7 +2273,7 @@ MatrixClient.prototype.searchMessageText = function(opts, callback) {
MatrixClient.prototype.searchRoomEvents = function(opts) {
// TODO: support groups
let body = {
const body = {
search_categories: {
room_events: {
search_term: opts.term,
@@ -2288,7 +2288,7 @@ MatrixClient.prototype.searchRoomEvents = function(opts) {
},
};
let searchResults = {
const searchResults = {
_query: body,
results: [],
highlights: [],
@@ -2319,12 +2319,12 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) {
return searchResults.pendingRequest;
}
let searchOpts = {
const searchOpts = {
body: searchResults._query,
next_batch: searchResults.next_batch,
};
let promise = this.search(searchOpts).then(
const promise = this.search(searchOpts).then(
this._processRoomEventsSearch.bind(this, searchResults)
).finally(function() {
searchResults.pendingRequest = null;
@@ -2344,14 +2344,14 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) {
* @private
*/
MatrixClient.prototype._processRoomEventsSearch = function(searchResults, response) {
let room_events = response.search_categories.room_events;
const room_events = response.search_categories.room_events;
searchResults.count = room_events.count;
searchResults.next_batch = room_events.next_batch;
// combine the highlight list with our existing list; build an object
// to avoid O(N^2) fail
let highlights = {};
const highlights = {};
room_events.highlights.forEach(function(hl) {
highlights[hl] = 1;
});
@@ -2364,7 +2364,7 @@ MatrixClient.prototype._processRoomEventsSearch = function(searchResults, respon
// append the new results to our existing results
for (let i = 0; i < room_events.results.length; i++) {
let sr = SearchResult.fromJson(room_events.results[i], this.getEventMapper());
const sr = SearchResult.fromJson(room_events.results[i], this.getEventMapper());
searchResults.results.push(sr);
}
return searchResults;
@@ -2385,8 +2385,8 @@ MatrixClient.prototype.syncLeftRooms = function() {
if (this._syncLeftRoomsPromise) {
return this._syncLeftRoomsPromise; // return the ongoing request
}
let self = this;
let syncApi = new SyncApi(this, this._clientOpts);
const self = this;
const syncApi = new SyncApi(this, this._clientOpts);
this._syncLeftRoomsPromise = syncApi.syncLeftRooms();
// cleanup locks
@@ -2410,15 +2410,15 @@ MatrixClient.prototype.syncLeftRooms = function() {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.createFilter = function(content) {
let self = this;
let path = utils.encodeUri("/user/$userId/filter", {
const self = this;
const path = utils.encodeUri("/user/$userId/filter", {
$userId: this.credentials.userId,
});
return this._http.authedRequest(
undefined, "POST", path, undefined, content
).then(function(response) {
// persist the filter
let filter = Filter.fromJson(
const filter = Filter.fromJson(
self.credentials.userId, response.filter_id, content
);
self.store.storeFilter(filter);
@@ -2437,14 +2437,14 @@ MatrixClient.prototype.createFilter = function(content) {
*/
MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
if (allowCached) {
let filter = this.store.getFilter(userId, filterId);
const filter = this.store.getFilter(userId, filterId);
if (filter) {
return q(filter);
}
}
let self = this;
let path = utils.encodeUri("/user/$userId/filter/$filterId", {
const self = this;
const path = utils.encodeUri("/user/$userId/filter/$filterId", {
$userId: userId,
$filterId: filterId,
});
@@ -2453,7 +2453,7 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
undefined, "GET", path, undefined, undefined
).then(function(response) {
// persist the filter
let filter = Filter.fromJson(
const filter = Filter.fromJson(
userId, filterId, response
);
self.store.storeFilter(filter);
@@ -2467,17 +2467,17 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
* @return {Promise<String>} Filter ID
*/
MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
let filterId = this.store.getFilterIdByName(filterName);
const filterId = this.store.getFilterIdByName(filterName);
let promise = q();
let self = this;
const self = this;
if (filterId) {
// check that the existing filter matches our expectations
promise = self.getFilter(self.credentials.userId,
filterId, true
).then(function(existingFilter) {
let oldDef = existingFilter.getDefinition();
let newDef = filter.getDefinition();
const oldDef = existingFilter.getDefinition();
const newDef = filter.getDefinition();
if (utils.deepCompare(oldDef, newDef)) {
// super, just use that.
@@ -2535,7 +2535,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
* @return {module:http-api.MatrixError} Rejects: with an error response.
*/
MatrixClient.prototype.getOpenIdToken = function() {
let path = utils.encodeUri("/user/$userId/openid/request_token", {
const path = utils.encodeUri("/user/$userId/openid/request_token", {
$userId: this.credentials.userId,
});
@@ -2624,8 +2624,8 @@ MatrixClient.prototype.startClient = function(opts) {
if (this._crypto) {
this._crypto.uploadKeys(5).done();
let tenMinutes = 1000 * 60 * 10;
let self = this;
const tenMinutes = 1000 * 60 * 10;
const self = this;
this._uploadIntervalID = global.setInterval(function() {
self._crypto.uploadKeys(5).done();
}, tenMinutes);
@@ -2661,7 +2661,7 @@ MatrixClient.prototype.stopClient = function() {
};
function setupCallEventHandler(client) {
let candidatesByCall = {
const candidatesByCall = {
// callId: [Candidate]
};
@@ -2674,11 +2674,11 @@ function setupCallEventHandler(client) {
client.on("sync", function(state) {
if (state === "PREPARED") {
isClientPrepared = true;
let ignoreCallIds = {}; // Set<String>
const ignoreCallIds = {}; // Set<String>
// inspect the buffer and mark all calls which have been answered
// or hung up before passing them to the call event handler.
for (let i = callEventBuffer.length - 1; i >= 0; i--) {
let ev = callEventBuffer[i];
const ev = callEventBuffer[i];
if (ev.getType() === "m.call.answer" ||
ev.getType() === "m.call.hangup") {
ignoreCallIds[ev.getContent().call_id] = "yep";
@@ -2709,7 +2709,7 @@ function setupCallEventHandler(client) {
if (event.getType().indexOf("m.call.") !== 0) {
return; // not a call event
}
let content = event.getContent();
const content = event.getContent();
let call = content.call_id ? client.callList[content.call_id] : undefined;
let i;
//console.log("RECV %s content=%s", event.getType(), JSON.stringify(content));
@@ -2761,9 +2761,9 @@ function setupCallEventHandler(client) {
// Were we trying to call that user (room)?
let existingCall;
let existingCalls = utils.values(client.callList);
const existingCalls = utils.values(client.callList);
for (i = 0; i < existingCalls.length; ++i) {
let thisCall = existingCalls[i];
const thisCall = existingCalls[i];
if (call.room_id === thisCall.room_id &&
thisCall.direction === 'outbound' &&
(["wait_local_media", "create_offer", "invite_sent"].indexOf(
@@ -2862,7 +2862,7 @@ function checkTurnServers(client) {
res.ttl + " secs");
// map the response to a format that can be fed to
// RTCPeerConnection
let servers = {
const servers = {
urls: res.uris,
username: res.username,
credential: res.password,
@@ -2898,7 +2898,7 @@ function _resolve(callback, defer, res) {
function _PojoToMatrixEventMapper(client) {
function mapper(plainOldJsObject) {
let event = new MatrixEvent(plainOldJsObject);
const event = new MatrixEvent(plainOldJsObject);
if (event.isEncrypted()) {
_decryptEvent(client, event);
}
@@ -2924,7 +2924,7 @@ MatrixClient.prototype.getEventMapper = function() {
*/
MatrixClient.prototype.generateClientSecret = function() {
let ret = "";
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
ret += chars.charAt(Math.floor(Math.random() * chars.length));

View File

@@ -16,7 +16,7 @@ limitations under the License.
/**
* @module content-repo
*/
let utils = require("./utils");
const utils = require("./utils");
/** Content Repo utility functions */
module.exports = {
@@ -48,7 +48,7 @@ module.exports = {
}
let serverAndMediaId = mxc.slice(6); // strips mxc://
let prefix = "/_matrix/media/v1/download/";
let params = {};
const params = {};
if (width) {
params.width = width;
@@ -94,12 +94,12 @@ module.exports = {
if (!height) {
height = 96;
}
let params = {
const params = {
width: width,
height: height,
};
let path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", {
const path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", {
$ident: identiconString,
});
return baseUrl + path +

View File

@@ -20,13 +20,13 @@ limitations under the License.
*
* @module crypto/OlmDevice
*/
let Olm = require("olm");
let utils = require("../utils");
const Olm = require("olm");
const utils = require("../utils");
// The maximum size of an event is 65K, and we base64 the content, so this is a
// reasonable approximation to the biggest plaintext we can encrypt.
let MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4;
const MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4;
function checkPayloadLength(payloadString) {
if (payloadString === undefined) {
@@ -79,7 +79,7 @@ function OlmDevice(sessionStore) {
this._pickleKey = "DEFAULT_KEY";
let e2eKeys;
let account = new Olm.Account();
const account = new Olm.Account();
try {
_initialise_account(this._sessionStore, this._pickleKey, account);
e2eKeys = JSON.parse(account.identity_keys());
@@ -108,14 +108,14 @@ function OlmDevice(sessionStore) {
}
function _initialise_account(sessionStore, pickleKey, account) {
let e2eAccount = sessionStore.getEndToEndAccount();
const e2eAccount = sessionStore.getEndToEndAccount();
if (e2eAccount !== null) {
account.unpickle(pickleKey, e2eAccount);
return;
}
account.create();
let pickled = account.pickle(pickleKey);
const pickled = account.pickle(pickleKey);
sessionStore.storeEndToEndAccount(pickled);
}
@@ -135,9 +135,9 @@ OlmDevice.getOlmVersion = function() {
* @private
*/
OlmDevice.prototype._getAccount = function(func) {
let account = new Olm.Account();
const account = new Olm.Account();
try {
let pickledAccount = this._sessionStore.getEndToEndAccount();
const pickledAccount = this._sessionStore.getEndToEndAccount();
account.unpickle(this._pickleKey, pickledAccount);
return func(account);
} finally {
@@ -153,7 +153,7 @@ OlmDevice.prototype._getAccount = function(func) {
* @private
*/
OlmDevice.prototype._saveAccount = function(account) {
let pickledAccount = account.pickle(this._pickleKey);
const pickledAccount = account.pickle(this._pickleKey);
this._sessionStore.storeEndToEndAccount(pickledAccount);
};
@@ -168,10 +168,10 @@ OlmDevice.prototype._saveAccount = function(account) {
* @private
*/
OlmDevice.prototype._getSession = function(deviceKey, sessionId, func) {
let sessions = this._sessionStore.getEndToEndSessions(deviceKey);
let pickledSession = sessions[sessionId];
const sessions = this._sessionStore.getEndToEndSessions(deviceKey);
const pickledSession = sessions[sessionId];
let session = new Olm.Session();
const session = new Olm.Session();
try {
session.unpickle(this._pickleKey, pickledSession);
return func(session);
@@ -189,7 +189,7 @@ OlmDevice.prototype._getSession = function(deviceKey, sessionId, func) {
* @private
*/
OlmDevice.prototype._saveSession = function(deviceKey, session) {
let pickledSession = session.pickle(this._pickleKey);
const pickledSession = session.pickle(this._pickleKey);
this._sessionStore.storeEndToEndSession(
deviceKey, session.session_id(), pickledSession
);
@@ -204,7 +204,7 @@ OlmDevice.prototype._saveSession = function(deviceKey, session) {
* @private
*/
OlmDevice.prototype._getUtility = function(func) {
let utility = new Olm.Utility();
const utility = new Olm.Utility();
try {
return func(utility);
} finally {
@@ -254,7 +254,7 @@ OlmDevice.prototype.maxNumberOfOneTimeKeys = function() {
* Marks all of the one-time keys as published.
*/
OlmDevice.prototype.markKeysAsPublished = function() {
let self = this;
const self = this;
this._getAccount(function(account) {
account.mark_keys_as_published();
self._saveAccount(account);
@@ -267,7 +267,7 @@ OlmDevice.prototype.markKeysAsPublished = function() {
* @param {number} numKeys number of keys to generate
*/
OlmDevice.prototype.generateOneTimeKeys = function(numKeys) {
let self = this;
const self = this;
this._getAccount(function(account) {
account.generate_one_time_keys(numKeys);
self._saveAccount(account);
@@ -286,9 +286,9 @@ OlmDevice.prototype.generateOneTimeKeys = function(numKeys) {
OlmDevice.prototype.createOutboundSession = function(
theirIdentityKey, theirOneTimeKey
) {
let self = this;
const self = this;
return this._getAccount(function(account) {
let session = new Olm.Session();
const session = new Olm.Session();
try {
session.create_outbound(account, theirIdentityKey, theirOneTimeKey);
self._saveSession(theirIdentityKey, session);
@@ -320,15 +320,15 @@ OlmDevice.prototype.createInboundSession = function(
throw new Error("Need message_type == 0 to create inbound session");
}
let self = this;
const self = this;
return this._getAccount(function(account) {
let session = new Olm.Session();
const session = new Olm.Session();
try {
session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext);
account.remove_one_time_keys(session);
self._saveAccount(account);
let payloadString = session.decrypt(message_type, ciphertext);
const payloadString = session.decrypt(message_type, ciphertext);
self._saveSession(theirDeviceIdentityKey, session);
@@ -351,7 +351,7 @@ OlmDevice.prototype.createInboundSession = function(
* @return {string[]} a list of known session ids for the device
*/
OlmDevice.prototype.getSessionIdsForDevice = function(theirDeviceIdentityKey) {
let sessions = this._sessionStore.getEndToEndSessions(
const sessions = this._sessionStore.getEndToEndSessions(
theirDeviceIdentityKey
);
return utils.keys(sessions);
@@ -365,7 +365,7 @@ OlmDevice.prototype.getSessionIdsForDevice = function(theirDeviceIdentityKey) {
* @return {string?} session id, or null if no established session
*/
OlmDevice.prototype.getSessionIdForDevice = function(theirDeviceIdentityKey) {
let sessionIds = this.getSessionIdsForDevice(theirDeviceIdentityKey);
const sessionIds = this.getSessionIdsForDevice(theirDeviceIdentityKey);
if (sessionIds.length === 0) {
return null;
}
@@ -386,10 +386,10 @@ OlmDevice.prototype.getSessionIdForDevice = function(theirDeviceIdentityKey) {
* @return {Array.<{sessionId: string, hasReceivedMessage: Boolean}>}
*/
OlmDevice.prototype.getSessionInfoForDevice = function(deviceIdentityKey) {
let sessionIds = this.getSessionIdsForDevice(deviceIdentityKey);
const sessionIds = this.getSessionIdsForDevice(deviceIdentityKey);
sessionIds.sort();
let info = [];
const info = [];
function getSessionInfo(session) {
return {
@@ -398,8 +398,8 @@ OlmDevice.prototype.getSessionInfoForDevice = function(deviceIdentityKey) {
}
for (let i = 0; i < sessionIds.length; i++) {
let sessionId = sessionIds[i];
let res = this._getSession(deviceIdentityKey, sessionId, getSessionInfo);
const sessionId = sessionIds[i];
const res = this._getSession(deviceIdentityKey, sessionId, getSessionInfo);
res.sessionId = sessionId;
info.push(res);
}
@@ -419,12 +419,12 @@ OlmDevice.prototype.getSessionInfoForDevice = function(deviceIdentityKey) {
OlmDevice.prototype.encryptMessage = function(
theirDeviceIdentityKey, sessionId, payloadString
) {
let self = this;
const self = this;
checkPayloadLength(payloadString);
return this._getSession(theirDeviceIdentityKey, sessionId, function(session) {
let res = session.encrypt(payloadString);
const res = session.encrypt(payloadString);
self._saveSession(theirDeviceIdentityKey, session);
return res;
});
@@ -444,10 +444,10 @@ OlmDevice.prototype.encryptMessage = function(
OlmDevice.prototype.decryptMessage = function(
theirDeviceIdentityKey, sessionId, message_type, ciphertext
) {
let self = this;
const self = this;
return this._getSession(theirDeviceIdentityKey, sessionId, function(session) {
let payloadString = session.decrypt(message_type, ciphertext);
const payloadString = session.decrypt(message_type, ciphertext);
self._saveSession(theirDeviceIdentityKey, session);
return payloadString;
@@ -489,7 +489,7 @@ OlmDevice.prototype.matchesSession = function(
* @private
*/
OlmDevice.prototype._saveOutboundGroupSession = function(session) {
let pickledSession = session.pickle(this._pickleKey);
const pickledSession = session.pickle(this._pickleKey);
this._outboundGroupSessionStore[session.session_id()] = pickledSession;
};
@@ -504,12 +504,12 @@ OlmDevice.prototype._saveOutboundGroupSession = function(session) {
* @private
*/
OlmDevice.prototype._getOutboundGroupSession = function(sessionId, func) {
let pickled = this._outboundGroupSessionStore[sessionId];
const pickled = this._outboundGroupSessionStore[sessionId];
if (pickled === null) {
throw new Error("Unknown outbound group session " + sessionId);
}
let session = new Olm.OutboundGroupSession();
const session = new Olm.OutboundGroupSession();
try {
session.unpickle(this._pickleKey, pickled);
return func(session);
@@ -525,7 +525,7 @@ OlmDevice.prototype._getOutboundGroupSession = function(sessionId, func) {
* @return {string} sessionId for the outbound session.
*/
OlmDevice.prototype.createOutboundGroupSession = function() {
let session = new Olm.OutboundGroupSession();
const session = new Olm.OutboundGroupSession();
try {
session.create();
this._saveOutboundGroupSession(session);
@@ -545,12 +545,12 @@ OlmDevice.prototype.createOutboundGroupSession = function() {
* @return {string} ciphertext
*/
OlmDevice.prototype.encryptGroupMessage = function(sessionId, payloadString) {
let self = this;
const self = this;
checkPayloadLength(payloadString);
return this._getOutboundGroupSession(sessionId, function(session) {
let res = session.encrypt(payloadString);
const res = session.encrypt(payloadString);
self._saveOutboundGroupSession(session);
return res;
});
@@ -590,7 +590,7 @@ OlmDevice.prototype.getOutboundGroupSessionKey = function(sessionId) {
OlmDevice.prototype._saveInboundGroupSession = function(
roomId, senderCurve25519Key, sessionId, session, keysClaimed
) {
let r = {
const r = {
room_id: roomId,
session: session.pickle(this._pickleKey),
keysClaimed: keysClaimed,
@@ -639,7 +639,7 @@ OlmDevice.prototype._getInboundGroupSession = function(
);
}
let session = new Olm.InboundGroupSession();
const session = new Olm.InboundGroupSession();
try {
session.unpickle(this._pickleKey, r.session);
return func(session, r.keysClaimed || {});
@@ -660,7 +660,7 @@ OlmDevice.prototype._getInboundGroupSession = function(
OlmDevice.prototype.addInboundGroupSession = function(
roomId, senderKey, sessionId, sessionKey, keysClaimed
) {
let self = this;
const self = this;
/* if we already have this session, consider updating it */
function updateSession(session) {
@@ -670,7 +670,7 @@ OlmDevice.prototype.addInboundGroupSession = function(
return true;
}
let r = this._getInboundGroupSession(
const r = this._getInboundGroupSession(
roomId, senderKey, sessionId, updateSession
);
@@ -679,7 +679,7 @@ OlmDevice.prototype.addInboundGroupSession = function(
}
// new session.
let session = new Olm.InboundGroupSession();
const session = new Olm.InboundGroupSession();
try {
session.create(sessionKey);
if (sessionId != session.session_id()) {
@@ -753,10 +753,10 @@ OlmDevice.prototype.importInboundGroupSession = function(data) {
OlmDevice.prototype.decryptGroupMessage = function(
roomId, senderKey, sessionId, body
) {
let self = this;
const self = this;
function decrypt(session, keysClaimed) {
let res = session.decrypt(body);
const res = session.decrypt(body);
let plaintext = res.plaintext;
if (plaintext === undefined) {
@@ -764,7 +764,7 @@ OlmDevice.prototype.decryptGroupMessage = function(
plaintext = res;
} else {
// Check if we have seen this message index before to detect replay attacks.
let messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index;
const messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index;
if (messageIndexKey in self._inboundGroupSessionMessageIndexes) {
throw new Error(
"Duplicate message index, possible replay attack: " +
@@ -776,7 +776,7 @@ OlmDevice.prototype.decryptGroupMessage = function(
// the sender must have had the senderKey to persuade us to save the
// session.
let keysProved = {curve25519: senderKey};
const keysProved = {curve25519: senderKey};
self._saveInboundGroupSession(
roomId, senderKey, sessionId, session, keysClaimed

View File

@@ -20,7 +20,7 @@ limitations under the License.
*
* @module crypto/algorithms/base
*/
let utils = require("../../utils");
const utils = require("../../utils");
/**
* map of registered encryption algorithm classes. A map from string to {@link
@@ -53,7 +53,7 @@ module.exports.DECRYPTION_CLASSES = {};
* @param {string} params.roomId The ID of the room we will be sending to
* @param {object} params.config The body of the m.room.encryption event
*/
let EncryptionAlgorithm = function(params) {
const EncryptionAlgorithm = function(params) {
this._userId = params.userId;
this._deviceId = params.deviceId;
this._crypto = params.crypto;
@@ -101,7 +101,7 @@ EncryptionAlgorithm.prototype.onRoomMembership = function(
* @param {string=} params.roomId The ID of the room we will be receiving
* from. Null for to-device events.
*/
let DecryptionAlgorithm = function(params) {
const DecryptionAlgorithm = function(params) {
this._userId = params.userId;
this._crypto = params.crypto;
this._olmDevice = params.olmDevice;

View File

@@ -19,7 +19,7 @@ limitations under the License.
* @module crypto/algorithms
*/
let base = require("./base");
const base = require("./base");
require("./olm");
require("./megolm");

View File

@@ -21,11 +21,11 @@ limitations under the License.
* @module crypto/algorithms/megolm
*/
let q = require("q");
const q = require("q");
let utils = require("../../utils");
let olmlib = require("../olmlib");
let base = require("./base");
const utils = require("../../utils");
const olmlib = require("../olmlib");
const base = require("./base");
/**
* @private
@@ -59,7 +59,7 @@ function OutboundSessionInfo(sessionId) {
OutboundSessionInfo.prototype.needsRotation = function(
rotationPeriodMsgs, rotationPeriodMs
) {
let sessionLifetime = new Date().getTime() - this.creationTime;
const sessionLifetime = new Date().getTime() - this.creationTime;
if (this.useCount >= rotationPeriodMsgs ||
sessionLifetime >= rotationPeriodMs
@@ -88,7 +88,7 @@ OutboundSessionInfo.prototype.needsRotation = function(
OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
devicesInRoom
) {
for (let userId in this.sharedWithDevices) {
for (const userId in this.sharedWithDevices) {
if (!this.sharedWithDevices.hasOwnProperty(userId)) {
continue;
}
@@ -98,7 +98,7 @@ OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
return true;
}
for (let deviceId in this.sharedWithDevices[userId]) {
for (const deviceId in this.sharedWithDevices[userId]) {
if (!this.sharedWithDevices[userId].hasOwnProperty(deviceId)) {
continue;
}
@@ -157,7 +157,7 @@ utils.inherits(MegolmEncryption, base.EncryptionAlgorithm);
* OutboundSessionInfo when setup is complete.
*/
MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) {
let self = this;
const self = this;
let session;
@@ -187,23 +187,23 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) {
}
// now check if we need to share with any devices
let shareMap = {};
const shareMap = {};
for (let userId in devicesInRoom) {
for (const userId in devicesInRoom) {
if (!devicesInRoom.hasOwnProperty(userId)) {
continue;
}
let userDevices = devicesInRoom[userId];
const userDevices = devicesInRoom[userId];
for (let deviceId in userDevices) {
for (const deviceId in userDevices) {
if (!userDevices.hasOwnProperty(deviceId)) {
continue;
}
let deviceInfo = userDevices[deviceId];
const deviceInfo = userDevices[deviceId];
let key = deviceInfo.getIdentityKey();
const key = deviceInfo.getIdentityKey();
if (key == self._olmDevice.deviceCurve25519Key) {
// don't bother sending to ourself
continue;
@@ -230,7 +230,7 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) {
}
// first wait for the previous share to complete
let prom = this._setupPromise.then(prepareSession);
const prom = this._setupPromise.then(prepareSession);
// _setupPromise resolves to `session` whether or not the share succeeds
this._setupPromise = prom.then(returnSession, returnSession);
@@ -245,8 +245,8 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) {
* @return {module:crypto/algorithms/megolm.OutboundSessionInfo} session
*/
MegolmEncryption.prototype._prepareNewSession = function() {
let session_id = this._olmDevice.createOutboundGroupSession();
let key = this._olmDevice.getOutboundGroupSessionKey(session_id);
const session_id = this._olmDevice.createOutboundGroupSession();
const key = this._olmDevice.getOutboundGroupSessionKey(session_id);
this._olmDevice.addInboundGroupSession(
this._roomId, this._olmDevice.deviceCurve25519Key, session_id,
@@ -268,10 +268,10 @@ MegolmEncryption.prototype._prepareNewSession = function() {
* message has been sent.
*/
MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUser) {
let self = this;
const self = this;
let key = this._olmDevice.getOutboundGroupSessionKey(session.sessionId);
let payload = {
const key = this._olmDevice.getOutboundGroupSessionKey(session.sessionId);
const payload = {
type: "m.room_key",
content: {
algorithm: olmlib.MEGOLM_ALGORITHM,
@@ -282,26 +282,26 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
},
};
let contentMap = {};
const contentMap = {};
return olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, devicesByUser
).then(function(devicemap) {
let haveTargets = false;
for (let userId in devicesByUser) {
for (const userId in devicesByUser) {
if (!devicesByUser.hasOwnProperty(userId)) {
continue;
}
let devicesToShareWith = devicesByUser[userId];
let sessionResults = devicemap[userId];
const devicesToShareWith = devicesByUser[userId];
const sessionResults = devicemap[userId];
for (let i = 0; i < devicesToShareWith.length; i++) {
let deviceInfo = devicesToShareWith[i];
let deviceId = deviceInfo.deviceId;
const deviceInfo = devicesToShareWith[i];
const deviceId = deviceInfo.deviceId;
let sessionResult = sessionResults[deviceId];
const sessionResult = sessionResults[deviceId];
if (!sessionResult.sessionId) {
// no session with this device, probably because there
// were no one-time keys.
@@ -321,7 +321,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
"sharing keys with device " + userId + ":" + deviceId
);
let encryptedContent = {
const encryptedContent = {
algorithm: olmlib.OLM_ALGORITHM,
sender_key: self._olmDevice.deviceCurve25519Key,
ciphertext: {},
@@ -359,16 +359,16 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
// attempted to share with) rather than the contentMap (those we did
// share with), because we don't want to try to claim a one-time-key
// for dead devices on every message.
for (let userId in devicesByUser) {
for (const userId in devicesByUser) {
if (!devicesByUser.hasOwnProperty(userId)) {
continue;
}
if (!session.sharedWithDevices[userId]) {
session.sharedWithDevices[userId] = {};
}
let devicesToShareWith = devicesByUser[userId];
const devicesToShareWith = devicesByUser[userId];
for (let i = 0; i < devicesToShareWith.length; i++) {
let deviceInfo = devicesToShareWith[i];
const deviceInfo = devicesToShareWith[i];
session.sharedWithDevices[userId][deviceInfo.deviceId] =
key.chain_index;
}
@@ -386,21 +386,21 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
* @return {module:client.Promise} Promise which resolves to the new event body
*/
MegolmEncryption.prototype.encryptMessage = function(room, eventType, content) {
let self = this;
const self = this;
return this._getDevicesInRoom(room).then(function(devicesInRoom) {
return self._ensureOutboundSession(devicesInRoom);
}).then(function(session) {
let payloadJson = {
const payloadJson = {
room_id: self._roomId,
type: eventType,
content: content,
};
let ciphertext = self._olmDevice.encryptGroupMessage(
const ciphertext = self._olmDevice.encryptGroupMessage(
session.sessionId, JSON.stringify(payloadJson)
);
let encryptedContent = {
const encryptedContent = {
algorithm: olmlib.MEGOLM_ALGORITHM,
sender_key: self._olmDevice.deviceCurve25519Key,
ciphertext: ciphertext,
@@ -425,7 +425,7 @@ MegolmEncryption.prototype.encryptMessage = function(room, eventType, content) {
*/
MegolmEncryption.prototype._getDevicesInRoom = function(room) {
// XXX what about rooms where invitees can see the content?
let roomMembers = utils.map(room.getJoinedMembers(), function(u) {
const roomMembers = utils.map(room.getJoinedMembers(), function(u) {
return u.userId;
});
@@ -435,13 +435,13 @@ MegolmEncryption.prototype._getDevicesInRoom = function(room) {
// an m.new_device.
return this._crypto.downloadKeys(roomMembers, false).then(function(devices) {
// remove any blocked devices
for (let userId in devices) {
for (const userId in devices) {
if (!devices.hasOwnProperty(userId)) {
continue;
}
let userDevices = devices[userId];
for (let deviceId in userDevices) {
const userDevices = devices[userId];
for (const deviceId in userDevices) {
if (!userDevices.hasOwnProperty(deviceId)) {
continue;
}
@@ -482,7 +482,7 @@ utils.inherits(MegolmDecryption, base.DecryptionAlgorithm);
* problem decrypting the event
*/
MegolmDecryption.prototype.decryptEvent = function(event) {
let content = event.getWireContent();
const content = event.getWireContent();
if (!content.sender_key || !content.session_id ||
!content.ciphertext
@@ -510,7 +510,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
);
}
let payload = JSON.parse(res.result);
const payload = JSON.parse(res.result);
// belt-and-braces check that the room id matches that indicated by the HS
// (this is somewhat redundant, since the megolm session is scoped to the
@@ -534,8 +534,8 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
* @param {module:models/event.MatrixEvent} event
*/
MegolmDecryption.prototype._addEventToPendingList = function(event) {
let content = event.getWireContent();
let k = content.sender_key + "|" + content.session_id;
const content = event.getWireContent();
const k = content.sender_key + "|" + content.session_id;
if (!this._pendingEvents[k]) {
this._pendingEvents[k] = [];
}
@@ -549,7 +549,7 @@ MegolmDecryption.prototype._addEventToPendingList = function(event) {
*/
MegolmDecryption.prototype.onRoomKeyEvent = function(event) {
console.log("Adding key from ", event);
let content = event.getContent();
const content = event.getContent();
if (!content.room_id ||
!content.session_id ||

View File

@@ -20,15 +20,15 @@ limitations under the License.
*
* @module crypto/algorithms/olm
*/
let q = require('q');
const q = require('q');
let utils = require("../../utils");
let olmlib = require("../olmlib");
let DeviceInfo = require("../deviceinfo");
let DeviceVerification = DeviceInfo.DeviceVerification;
const utils = require("../../utils");
const olmlib = require("../olmlib");
const DeviceInfo = require("../deviceinfo");
const DeviceVerification = DeviceInfo.DeviceVerification;
let base = require("./base");
const base = require("./base");
/**
* Olm encryption implementation
@@ -63,7 +63,7 @@ OlmEncryption.prototype._ensureSession = function(roomMembers) {
return q();
}
let self = this;
const self = this;
this._prepPromise = self._crypto.downloadKeys(roomMembers, true).then(function(res) {
return self._crypto.ensureOlmSessionsForUsers(roomMembers);
}).then(function() {
@@ -89,31 +89,31 @@ OlmEncryption.prototype.encryptMessage = function(room, eventType, content) {
// TODO: there is a race condition here! What if a new user turns up
// just as you are sending a secret message?
let users = utils.map(room.getJoinedMembers(), function(u) {
const users = utils.map(room.getJoinedMembers(), function(u) {
return u.userId;
});
let self = this;
const self = this;
return this._ensureSession(users).then(function() {
let payloadFields = {
const payloadFields = {
room_id: room.roomId,
type: eventType,
content: content,
};
let encryptedContent = {
const encryptedContent = {
algorithm: olmlib.OLM_ALGORITHM,
sender_key: self._olmDevice.deviceCurve25519Key,
ciphertext: {},
};
for (let i = 0; i < users.length; ++i) {
let userId = users[i];
let devices = self._crypto.getStoredDevicesForUser(userId);
const userId = users[i];
const devices = self._crypto.getStoredDevicesForUser(userId);
for (let j = 0; j < devices.length; ++j) {
let deviceInfo = devices[j];
let key = deviceInfo.getIdentityKey();
const deviceInfo = devices[j];
const key = deviceInfo.getIdentityKey();
if (key == self._olmDevice.deviceCurve25519Key) {
// don't bother sending to ourself
continue;
@@ -157,9 +157,9 @@ utils.inherits(OlmDecryption, base.DecryptionAlgorithm);
* problem decrypting the event
*/
OlmDecryption.prototype.decryptEvent = function(event) {
let content = event.getWireContent();
let deviceKey = content.sender_key;
let ciphertext = content.ciphertext;
const content = event.getWireContent();
const deviceKey = content.sender_key;
const ciphertext = content.ciphertext;
if (!ciphertext) {
throw new base.DecryptionError("Missing ciphertext");
@@ -168,7 +168,7 @@ OlmDecryption.prototype.decryptEvent = function(event) {
if (!(this._olmDevice.deviceCurve25519Key in ciphertext)) {
throw new base.DecryptionError("Not included in recipients");
}
let message = ciphertext[this._olmDevice.deviceCurve25519Key];
const message = ciphertext[this._olmDevice.deviceCurve25519Key];
let payloadString;
try {
@@ -182,7 +182,7 @@ OlmDecryption.prototype.decryptEvent = function(event) {
throw new base.DecryptionError("Bad Encrypted Message");
}
let payload = JSON.parse(payloadString);
const payload = JSON.parse(payloadString);
// check that we were the intended recipient, to avoid unknown-key attack
// https://github.com/vector-im/vector-web/issues/2483
@@ -243,14 +243,14 @@ OlmDecryption.prototype.decryptEvent = function(event) {
* @return {string} payload, if decrypted successfully.
*/
OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, message) {
let sessionIds = this._olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey);
const sessionIds = this._olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey);
// try each session in turn.
let decryptionErrors = {};
const decryptionErrors = {};
for (let i = 0; i < sessionIds.length; i++) {
let sessionId = sessionIds[i];
const sessionId = sessionIds[i];
try {
let payload = this._olmDevice.decryptMessage(
const payload = this._olmDevice.decryptMessage(
theirDeviceIdentityKey, sessionId, message.type, message.body
);
console.log(
@@ -259,7 +259,7 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa
);
return payload;
} catch (e) {
let foundSession = this._olmDevice.matchesSession(
const foundSession = this._olmDevice.matchesSession(
theirDeviceIdentityKey, sessionId, message.type, message.body
);

View File

@@ -62,8 +62,8 @@ function DeviceInfo(deviceId) {
* @return {module:crypto~DeviceInfo} new DeviceInfo
*/
DeviceInfo.fromStorage = function(obj, deviceId) {
let res = new DeviceInfo(deviceId);
for (let prop in obj) {
const res = new DeviceInfo(deviceId);
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
res[prop] = obj[prop];
}
@@ -139,7 +139,7 @@ DeviceInfo.DeviceVerification = {
BLOCKED: -1,
};
let DeviceVerification = DeviceInfo.DeviceVerification;
const DeviceVerification = DeviceInfo.DeviceVerification;
/** */
module.exports = DeviceInfo;

View File

@@ -20,15 +20,15 @@ limitations under the License.
* @module crypto
*/
let anotherjson = require('another-json');
let q = require("q");
const anotherjson = require('another-json');
const q = require("q");
let utils = require("../utils");
let OlmDevice = require("./OlmDevice");
let olmlib = require("./olmlib");
let algorithms = require("./algorithms");
let DeviceInfo = require("./deviceinfo");
let DeviceVerification = DeviceInfo.DeviceVerification;
const utils = require("../utils");
const OlmDevice = require("./OlmDevice");
const olmlib = require("./olmlib");
const algorithms = require("./algorithms");
const DeviceInfo = require("./deviceinfo");
const DeviceVerification = DeviceInfo.DeviceVerification;
/**
* Cryptography bits
@@ -92,7 +92,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
if (!myDevices[this._deviceId]) {
// add our own deviceinfo to the sessionstore
let deviceInfo = {
const deviceInfo = {
keys: this._deviceKeys,
algorithms: this._supportedAlgorithms,
verified: DeviceVerification.VERIFIED,
@@ -113,7 +113,7 @@ function _registerEventHandlers(crypto, eventEmitter) {
if (syncState == "PREPARED") {
// XXX ugh. we're assuming the eventEmitter is a MatrixClient.
// how can we avoid doing so?
let rooms = eventEmitter.getRooms();
const rooms = eventEmitter.getRooms();
crypto._onInitialSyncCompleted(rooms);
}
} catch (e) {
@@ -176,7 +176,7 @@ Crypto.prototype.getDeviceEd25519Key = function() {
* @return {object} A promise that will resolve when the keys are uploaded.
*/
Crypto.prototype.uploadKeys = function(maxKeys) {
let self = this;
const self = this;
return _uploadDeviceKeys(this).then(function(res) {
// We need to keep a pool of one time public keys on the server so that
// other devices can start conversations with us. But we can only store
@@ -191,16 +191,16 @@ Crypto.prototype.uploadKeys = function(maxKeys) {
// these factors.
// We first find how many keys the server has for us.
let keyCount = res.one_time_key_counts.signed_curve25519 || 0;
const keyCount = res.one_time_key_counts.signed_curve25519 || 0;
// We then check how many keys we can store in the Account object.
let maxOneTimeKeys = self._olmDevice.maxNumberOfOneTimeKeys();
const maxOneTimeKeys = self._olmDevice.maxNumberOfOneTimeKeys();
// Try to keep at most half that number on the server. This leaves the
// rest of the slots free to hold keys that have been claimed from the
// server but we haven't recevied a message for.
// If we run out of slots when generating new keys then olm will
// discard the oldest private keys first. This will eventually clean
// out stale private keys that won't receive a message.
let keyLimit = Math.floor(maxOneTimeKeys / 2);
const keyLimit = Math.floor(maxOneTimeKeys / 2);
// We work out how many new keys we need to create to top up the server
// If there are too many keys on the server then we don't need to
// create any more keys.
@@ -225,10 +225,10 @@ Crypto.prototype.uploadKeys = function(maxKeys) {
// returns a promise which resolves to the response
function _uploadDeviceKeys(crypto) {
let userId = crypto._userId;
let deviceId = crypto._deviceId;
const userId = crypto._userId;
const deviceId = crypto._deviceId;
let deviceKeys = {
const deviceKeys = {
algorithms: crypto._supportedAlgorithms,
device_id: deviceId,
keys: crypto._deviceKeys,
@@ -247,12 +247,12 @@ function _uploadDeviceKeys(crypto) {
// returns a promise which resolves to the response
function _uploadOneTimeKeys(crypto) {
let oneTimeKeys = crypto._olmDevice.getOneTimeKeys();
let oneTimeJson = {};
const oneTimeKeys = crypto._olmDevice.getOneTimeKeys();
const oneTimeJson = {};
for (let keyId in oneTimeKeys.curve25519) {
for (const keyId in oneTimeKeys.curve25519) {
if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) {
let k = {
const k = {
key: oneTimeKeys.curve25519[keyId],
};
crypto._signObject(k);
@@ -282,10 +282,10 @@ function _uploadOneTimeKeys(crypto) {
* module:crypto/deviceinfo|DeviceInfo}.
*/
Crypto.prototype.downloadKeys = function(userIds, forceDownload) {
let self = this;
const self = this;
// promises we need to wait for while the download happens
let promises = [];
const promises = [];
// list of userids we need to download keys for
let downloadUsers = [];
@@ -300,9 +300,9 @@ Crypto.prototype.downloadKeys = function(userIds, forceDownload) {
downloadUsers = userIds;
} else {
for (let i = 0; i < userIds.length; ++i) {
let u = userIds[i];
const u = userIds[i];
let inprogress = this._keyDownloadsInProgressByUser[u];
const inprogress = this._keyDownloadsInProgressByUser[u];
if (inprogress) {
// wait for the download to complete
promises.push(q.any(inprogress).catch(perUserCatch(u)));
@@ -313,7 +313,7 @@ Crypto.prototype.downloadKeys = function(userIds, forceDownload) {
}
if (downloadUsers.length > 0) {
let r = this._doKeyDownloadForUsers(downloadUsers);
const r = this._doKeyDownloadForUsers(downloadUsers);
downloadUsers.map(function(u) {
promises.push(r[u].catch(perUserCatch(u)));
});
@@ -333,11 +333,11 @@ Crypto.prototype.downloadKeys = function(userIds, forceDownload) {
* @return {Object} userId->deviceId->{@link module:crypto/deviceinfo|DeviceInfo}.
*/
Crypto.prototype._getDevicesFromStore = function(userIds) {
let stored = {};
let self = this;
const stored = {};
const self = this;
userIds.map(function(u) {
stored[u] = {};
let devices = self.getStoredDevicesForUser(u) || [];
const devices = self.getStoredDevicesForUser(u) || [];
devices.map(function(dev) {
stored[u][dev.deviceId] = dev;
});
@@ -351,17 +351,17 @@ Crypto.prototype._getDevicesFromStore = function(userIds) {
* @return {Object} a map from userId to a promise for a result for that user
*/
Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
let self = this;
const self = this;
console.log('Starting key download for ' + downloadUsers);
let deferMap = {};
let promiseMap = {};
const deferMap = {};
const promiseMap = {};
downloadUsers.map(function(u) {
let deferred = q.defer();
let promise = deferred.promise.finally(function() {
let inProgress = self._keyDownloadsInProgressByUser[u];
const deferred = q.defer();
const promise = deferred.promise.finally(function() {
const inProgress = self._keyDownloadsInProgressByUser[u];
utils.removeElement(inProgress, function(e) {
return e === promise;
});
@@ -383,29 +383,29 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
this._baseApis.downloadKeysForUsers(
downloadUsers
).done(function(res) {
let dk = res.device_keys || {};
const dk = res.device_keys || {};
for (let i = 0; i < downloadUsers.length; ++i) {
let userId = downloadUsers[i];
const userId = downloadUsers[i];
var deviceId;
console.log('got keys for ' + userId + ':', dk[userId]);
if (!dk[userId]) {
// no result for this user
let err = 'Unknown';
const err = 'Unknown';
// TODO: do something with res.failures
deferMap[userId].reject(err);
continue;
}
// map from deviceid -> deviceinfo for this user
let userStore = {};
let devs = self._sessionStore.getEndToEndDevicesForUser(userId);
const userStore = {};
const devs = self._sessionStore.getEndToEndDevicesForUser(userId);
if (devs) {
for (deviceId in devs) {
if (devs.hasOwnProperty(deviceId)) {
let d = DeviceInfo.fromStorage(devs[deviceId], deviceId);
const d = DeviceInfo.fromStorage(devs[deviceId], deviceId);
userStore[deviceId] = d;
}
}
@@ -416,7 +416,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
);
// update the session store
let storage = {};
const storage = {};
for (deviceId in userStore) {
if (!userStore.hasOwnProperty(deviceId)) {
continue;
@@ -462,7 +462,7 @@ function _updateStoredDeviceKeysForUser(_olmDevice, userId, userStore,
continue;
}
let deviceResult = userResult[deviceId];
const deviceResult = userResult[deviceId];
// check that the user_id and device_id in the response object are
// correct
@@ -496,18 +496,18 @@ function _storeDeviceKeys(_olmDevice, userStore, deviceResult) {
return false;
}
let deviceId = deviceResult.device_id;
let userId = deviceResult.user_id;
const deviceId = deviceResult.device_id;
const userId = deviceResult.user_id;
let signKeyId = "ed25519:" + deviceId;
let signKey = deviceResult.keys[signKeyId];
const signKeyId = "ed25519:" + deviceId;
const signKey = deviceResult.keys[signKeyId];
if (!signKey) {
console.log("Device " + userId + ":" + deviceId +
" has no ed25519 key");
return false;
}
let unsigned = deviceResult.unsigned || {};
const unsigned = deviceResult.unsigned || {};
try {
olmlib.verifySignature(_olmDevice, deviceResult, userId, deviceId, signKey);
@@ -552,12 +552,12 @@ function _storeDeviceKeys(_olmDevice, userStore, deviceResult) {
* managed to get a list of devices for this user yet.
*/
Crypto.prototype.getStoredDevicesForUser = function(userId) {
let devs = this._sessionStore.getEndToEndDevicesForUser(userId);
const devs = this._sessionStore.getEndToEndDevicesForUser(userId);
if (!devs) {
return null;
}
let res = [];
for (let deviceId in devs) {
const res = [];
for (const deviceId in devs) {
if (devs.hasOwnProperty(deviceId)) {
res.push(DeviceInfo.fromStorage(devs[deviceId], deviceId));
}
@@ -575,7 +575,7 @@ Crypto.prototype.getStoredDevicesForUser = function(userId) {
* if we don't know about this device
*/
Crypto.prototype.getStoredDevice = function(userId, deviceId) {
let devs = this._sessionStore.getEndToEndDevicesForUser(userId);
const devs = this._sessionStore.getEndToEndDevicesForUser(userId);
if (!devs || !devs[deviceId]) {
return undefined;
}
@@ -593,13 +593,13 @@ Crypto.prototype.getStoredDevice = function(userId, deviceId) {
* "key", and "display_name" parameters.
*/
Crypto.prototype.listDeviceKeys = function(userId) {
let devices = this.getStoredDevicesForUser(userId) || [];
const devices = this.getStoredDevicesForUser(userId) || [];
let result = [];
const result = [];
for (let i = 0; i < devices.length; ++i) {
let device = devices[i];
let ed25519Key = device.getFingerprint();
const device = devices[i];
const ed25519Key = device.getFingerprint();
if (ed25519Key) {
result.push({
id: device.deviceId,
@@ -643,25 +643,25 @@ Crypto.prototype.getDeviceByIdentityKey = function(userId, algorithm, sender_key
return null;
}
let devices = this._sessionStore.getEndToEndDevicesForUser(userId);
const devices = this._sessionStore.getEndToEndDevicesForUser(userId);
if (!devices) {
return null;
}
for (let deviceId in devices) {
for (const deviceId in devices) {
if (!devices.hasOwnProperty(deviceId)) {
continue;
}
let device = devices[deviceId];
for (let keyId in device.keys) {
const device = devices[deviceId];
for (const keyId in device.keys) {
if (!device.keys.hasOwnProperty(keyId)) {
continue;
}
if (keyId.indexOf("curve25519:") !== 0) {
continue;
}
let deviceKey = device.keys[keyId];
const deviceKey = device.keys[keyId];
if (deviceKey == sender_key) {
return DeviceInfo.fromStorage(device, deviceId);
}
@@ -686,12 +686,12 @@ Crypto.prototype.getDeviceByIdentityKey = function(userId, algorithm, sender_key
* leave unchanged.
*/
Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified, blocked) {
let devices = this._sessionStore.getEndToEndDevicesForUser(userId);
const devices = this._sessionStore.getEndToEndDevicesForUser(userId);
if (!devices || !devices[deviceId]) {
throw new Error("Unknown device " + userId + ":" + deviceId);
}
let dev = devices[deviceId];
const dev = devices[deviceId];
let verificationStatus = dev.verified;
if (verified) {
@@ -729,12 +729,12 @@ Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified, bl
* @return {Object.<string, {deviceIdKey: string, sessions: object[]}>}
*/
Crypto.prototype.getOlmSessionsForUser = function(userId) {
let devices = this.getStoredDevicesForUser(userId) || [];
let result = {};
const devices = this.getStoredDevicesForUser(userId) || [];
const result = {};
for (let j = 0; j < devices.length; ++j) {
let device = devices[j];
let deviceKey = device.getIdentityKey();
let sessions = this._olmDevice.getSessionInfoForDevice(deviceKey);
const device = devices[j];
const deviceKey = device.getIdentityKey();
const sessions = this._olmDevice.getSessionInfoForDevice(deviceKey);
result[device.deviceId] = {
deviceIdKey: deviceKey,
@@ -753,8 +753,8 @@ Crypto.prototype.getOlmSessionsForUser = function(userId) {
* @return {module:crypto/deviceinfo?}
*/
Crypto.prototype.getEventSenderDeviceInfo = function(event) {
let sender_key = event.getSenderKey();
let algorithm = event.getWireContent().algorithm;
const sender_key = event.getSenderKey();
const algorithm = event.getWireContent().algorithm;
if (!sender_key || !algorithm) {
return null;
@@ -764,7 +764,7 @@ Crypto.prototype.getEventSenderDeviceInfo = function(event) {
// was sent from. In the case of Megolm, it's actually the Curve25519
// identity key of the device which set up the Megolm session.
let device = this.getDeviceByIdentityKey(
const device = this.getDeviceByIdentityKey(
event.getSender(), algorithm, sender_key
);
@@ -781,7 +781,7 @@ Crypto.prototype.getEventSenderDeviceInfo = function(event) {
//
// (see https://github.com/vector-im/vector-web/issues/2215)
let claimedKey = event.getKeysClaimed().ed25519;
const claimedKey = event.getKeysClaimed().ed25519;
if (!claimedKey) {
console.warn("Event " + event.getId() + " claims no ed25519 key: " +
"cannot verify sending device");
@@ -808,7 +808,7 @@ Crypto.prototype.getEventSenderDeviceInfo = function(event) {
Crypto.prototype.setRoomEncryption = function(roomId, config) {
// if we already have encryption in this room, we should ignore this event
// (for now at least. maybe we should alert the user somehow?)
let existingConfig = this._sessionStore.getEndToEndRoom(roomId);
const existingConfig = this._sessionStore.getEndToEndRoom(roomId);
if (existingConfig) {
if (JSON.stringify(existingConfig) != JSON.stringify(config)) {
console.error("Ignoring m.room.encryption event which requests " +
@@ -817,7 +817,7 @@ Crypto.prototype.setRoomEncryption = function(roomId, config) {
}
}
let AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm];
const AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm];
if (!AlgClass) {
throw new Error("Unable to encrypt with " + config.algorithm);
}
@@ -828,7 +828,7 @@ Crypto.prototype.setRoomEncryption = function(roomId, config) {
};
this._sessionStore.storeEndToEndRoom(roomId, config);
let alg = new AlgClass({
const alg = new AlgClass({
userId: this._userId,
deviceId: this._deviceId,
crypto: this,
@@ -859,17 +859,17 @@ Crypto.prototype.setRoomEncryption = function(roomId, config) {
* {@link module:crypto~OlmSessionResult}
*/
Crypto.prototype.ensureOlmSessionsForUsers = function(users) {
let devicesByUser = {};
const devicesByUser = {};
for (let i = 0; i < users.length; ++i) {
let userId = users[i];
const userId = users[i];
devicesByUser[userId] = [];
let devices = this.getStoredDevicesForUser(userId) || [];
const devices = this.getStoredDevicesForUser(userId) || [];
for (let j = 0; j < devices.length; ++j) {
let deviceInfo = devices[j];
const deviceInfo = devices[j];
let key = deviceInfo.getIdentityKey();
const key = deviceInfo.getIdentityKey();
if (key == this._olmDevice.deviceCurve25519Key) {
// don't bother setting up session to ourself
continue;
@@ -959,9 +959,9 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
throw new Error("Cannot send encrypted messages in unknown rooms");
}
let roomId = event.getRoomId();
const roomId = event.getRoomId();
let alg = this._roomEncryptors[roomId];
const alg = this._roomEncryptors[roomId];
if (!alg) {
// not encrypting messages in this room
@@ -979,7 +979,7 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
// We can claim and prove ownership of all our device keys in the local
// echo of the event since we know that all the local echos come from
// this device.
let myKeys = {
const myKeys = {
curve25519: this._olmDevice.deviceCurve25519Key,
ed25519: this._olmDevice.deviceEd25519Key,
};
@@ -999,8 +999,8 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
* @raises {algorithms.DecryptionError} if there is a problem decrypting the event
*/
Crypto.prototype.decryptEvent = function(event) {
let content = event.getWireContent();
let alg = this._getRoomDecryptor(event.getRoomId(), content.algorithm);
const content = event.getWireContent();
const alg = this._getRoomDecryptor(event.getRoomId(), content.algorithm);
alg.decryptEvent(event);
};
@@ -1011,8 +1011,8 @@ Crypto.prototype.decryptEvent = function(event) {
* @param {module:models/event.MatrixEvent} event encryption event
*/
Crypto.prototype._onCryptoEvent = function(event) {
let roomId = event.getRoomId();
let content = event.getContent();
const roomId = event.getRoomId();
const content = event.getContent();
try {
this.setRoomEncryption(roomId, content);
@@ -1043,27 +1043,27 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) {
// we need to tell all the devices in all the rooms we are members of that
// we have arrived.
// build a list of rooms for each user.
let roomsByUser = {};
const roomsByUser = {};
for (let i = 0; i < rooms.length; i++) {
let room = rooms[i];
const room = rooms[i];
// check for rooms with encryption enabled
let alg = this._roomEncryptors[room.roomId];
const alg = this._roomEncryptors[room.roomId];
if (!alg) {
continue;
}
// ignore any rooms which we have left
let me = room.getMember(this._userId);
const me = room.getMember(this._userId);
if (!me || (
me.membership !== "join" && me.membership !== "invite"
)) {
continue;
}
let members = room.getJoinedMembers();
const members = room.getJoinedMembers();
for (let j = 0; j < members.length; j++) {
let m = members[j];
const m = members[j];
if (!roomsByUser[m.userId]) {
roomsByUser[m.userId] = [];
}
@@ -1072,8 +1072,8 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) {
}
// build a per-device message for each user
let content = {};
for (let userId in roomsByUser) {
const content = {};
for (const userId in roomsByUser) {
if (!roomsByUser.hasOwnProperty(userId)) {
continue;
}
@@ -1085,7 +1085,7 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) {
};
}
let self = this;
const self = this;
this._baseApis.sendToDevice(
"m.new_device", // OH HAI!
content
@@ -1101,14 +1101,14 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) {
* @param {module:models/event.MatrixEvent} event key event
*/
Crypto.prototype._onRoomKeyEvent = function(event) {
let content = event.getContent();
const content = event.getContent();
if (!content.room_id || !content.algorithm) {
console.error("key event is missing fields");
return;
}
let alg = this._getRoomDecryptor(content.room_id, content.algorithm);
const alg = this._getRoomDecryptor(content.room_id, content.algorithm);
alg.onRoomKeyEvent(event);
};
@@ -1129,9 +1129,9 @@ Crypto.prototype._onRoomMembership = function(event, member, oldMembership) {
// Further, it is automatically registered and called when new members
// arrive in the room.
let roomId = member.roomId;
const roomId = member.roomId;
let alg = this._roomEncryptors[roomId];
const alg = this._roomEncryptors[roomId];
if (!alg) {
// not encrypting in this room
return;
@@ -1148,10 +1148,10 @@ Crypto.prototype._onRoomMembership = function(event, member, oldMembership) {
* @param {module:models/event.MatrixEvent} event announcement event
*/
Crypto.prototype._onNewDeviceEvent = function(event) {
let content = event.getContent();
let userId = event.getSender();
let deviceId = content.device_id;
let rooms = content.rooms;
const content = event.getContent();
const userId = event.getSender();
const deviceId = content.device_id;
const rooms = content.rooms;
if (!rooms || !deviceId) {
console.warn("new_device event missing keys");
@@ -1179,15 +1179,15 @@ Crypto.prototype._onNewDeviceEvent = function(event) {
* Start device queries for any users who sent us an m.new_device recently
*/
Crypto.prototype._flushNewDeviceRequests = function() {
let self = this;
const self = this;
let users = utils.keys(this._pendingUsersWithNewDevices);
const users = utils.keys(this._pendingUsersWithNewDevices);
if (users.length === 0) {
return;
}
let r = this._doKeyDownloadForUsers(users);
const r = this._doKeyDownloadForUsers(users);
// we've kicked off requests to these users: remove their
// pending flag for now.
@@ -1245,7 +1245,7 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) {
}
}
let AlgClass = algorithms.DECRYPTION_CLASSES[algorithm];
const AlgClass = algorithms.DECRYPTION_CLASSES[algorithm];
if (!AlgClass) {
throw new algorithms.DecryptionError(
'Unknown encryption algorithm "' + algorithm + '".'
@@ -1271,7 +1271,7 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) {
* @param {Object} obj Object to which we will add a 'signatures' property
*/
Crypto.prototype._signObject = function(obj) {
let sigs = {};
const sigs = {};
sigs[this._userId] = {};
sigs[this._userId]["ed25519:" + this._deviceId] =
this._olmDevice.sign(anotherjson.stringify(obj));

View File

@@ -20,10 +20,10 @@ limitations under the License.
* Utilities common to olm encryption algorithms
*/
let q = require('q');
let anotherjson = require('another-json');
const q = require('q');
const anotherjson = require('another-json');
let utils = require("../utils");
const utils = require("../utils");
/**
* matrix algorithm tag for olm
@@ -54,8 +54,8 @@ module.exports.encryptMessageForDevice = function(
ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice,
payloadFields
) {
let deviceKey = recipientDevice.getIdentityKey();
let sessionId = olmDevice.getSessionIdForDevice(deviceKey);
const deviceKey = recipientDevice.getIdentityKey();
const sessionId = olmDevice.getSessionIdForDevice(deviceKey);
if (sessionId === null) {
// If we don't have a session for a device then
// we can't encrypt a message for it.
@@ -67,7 +67,7 @@ module.exports.encryptMessageForDevice = function(
recipientUserId + ":" + recipientDevice.deviceId
);
let payload = {
const payload = {
sender: ourUserId,
sender_device: ourDeviceId,
@@ -121,22 +121,22 @@ module.exports.encryptMessageForDevice = function(
module.exports.ensureOlmSessionsForDevices = function(
olmDevice, baseApis, devicesByUser
) {
let devicesWithoutSession = [
const devicesWithoutSession = [
// [userId, deviceId], ...
];
let result = {};
const result = {};
for (let userId in devicesByUser) {
for (const userId in devicesByUser) {
if (!devicesByUser.hasOwnProperty(userId)) {
continue;
}
result[userId] = {};
let devices = devicesByUser[userId];
const devices = devicesByUser[userId];
for (let j = 0; j < devices.length; j++) {
let deviceInfo = devices[j];
let deviceId = deviceInfo.deviceId;
let key = deviceInfo.getIdentityKey();
let sessionId = olmDevice.getSessionIdForDevice(key);
const deviceInfo = devices[j];
const deviceId = deviceInfo.deviceId;
const key = deviceInfo.getIdentityKey();
const sessionId = olmDevice.getSessionIdForDevice(key);
if (sessionId === null) {
devicesWithoutSession.push([userId, deviceId]);
}
@@ -157,28 +157,28 @@ module.exports.ensureOlmSessionsForDevices = function(
//
// That should eventually resolve itself, but it's poor form.
let oneTimeKeyAlgorithm = "signed_curve25519";
const oneTimeKeyAlgorithm = "signed_curve25519";
return baseApis.claimOneTimeKeys(
devicesWithoutSession, oneTimeKeyAlgorithm
).then(function(res) {
let otk_res = res.one_time_keys || {};
for (let userId in devicesByUser) {
const otk_res = res.one_time_keys || {};
for (const userId in devicesByUser) {
if (!devicesByUser.hasOwnProperty(userId)) {
continue;
}
let userRes = otk_res[userId] || {};
let devices = devicesByUser[userId];
const userRes = otk_res[userId] || {};
const devices = devicesByUser[userId];
for (let j = 0; j < devices.length; j++) {
let deviceInfo = devices[j];
let deviceId = deviceInfo.deviceId;
const deviceInfo = devices[j];
const deviceId = deviceInfo.deviceId;
if (result[userId][deviceId].sessionId) {
// we already have a result for this device
continue;
}
let deviceRes = userRes[deviceId] || {};
const deviceRes = userRes[deviceId] || {};
let oneTimeKey = null;
for (let keyId in deviceRes) {
for (const keyId in deviceRes) {
if (keyId.indexOf(oneTimeKeyAlgorithm + ":") === 0) {
oneTimeKey = deviceRes[keyId];
}
@@ -192,7 +192,7 @@ module.exports.ensureOlmSessionsForDevices = function(
continue;
}
let sid = _verifyKeyAndStartSession(
const sid = _verifyKeyAndStartSession(
olmDevice, oneTimeKey, userId, deviceInfo
);
result[userId][deviceId].sessionId = sid;
@@ -204,7 +204,7 @@ module.exports.ensureOlmSessionsForDevices = function(
function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) {
let deviceId = deviceInfo.deviceId;
const deviceId = deviceInfo.deviceId;
try {
_verifySignature(
olmDevice, oneTimeKey, userId, deviceId,
@@ -250,13 +250,13 @@ function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) {
*
* @param {string} signingKey base64-ed ed25519 public key
*/
let _verifySignature = module.exports.verifySignature = function(
const _verifySignature = module.exports.verifySignature = function(
olmDevice, obj, signingUserId, signingDeviceId, signingKey
) {
let signKeyId = "ed25519:" + signingDeviceId;
let signatures = obj.signatures || {};
let userSigs = signatures[signingUserId] || {};
let signature = userSigs[signKeyId];
const signKeyId = "ed25519:" + signingDeviceId;
const signatures = obj.signatures || {};
const userSigs = signatures[signingUserId] || {};
const signature = userSigs[signKeyId];
if (!signature) {
throw Error("No signature");
}
@@ -265,7 +265,7 @@ let _verifySignature = module.exports.verifySignature = function(
// anotherjson
delete obj.unsigned;
delete obj.signatures;
let json = anotherjson.stringify(obj);
const json = anotherjson.stringify(obj);
olmDevice.verifySignature(
signingKey, json, signature

View File

@@ -27,7 +27,7 @@ limitations under the License.
*/
function _matches_wildcard(actual_value, filter_value) {
if (filter_value.endsWith("*")) {
let type_prefix = filter_value.slice(0, -1);
const type_prefix = filter_value.slice(0, -1);
return actual_value.substr(0, type_prefix.length) === type_prefix;
} else {
return actual_value === filter_value;
@@ -84,7 +84,7 @@ FilterComponent.prototype.check = function(event) {
*/
FilterComponent.prototype._checkFields =
function(room_id, sender, event_type, contains_url) {
let literal_keys = {
const literal_keys = {
"rooms": function(v) {
return room_id === v;
},
@@ -96,16 +96,16 @@ FilterComponent.prototype._checkFields =
},
};
let self = this;
const self = this;
Object.keys(literal_keys).forEach(function(name) {
let match_func = literal_keys[name];
let not_name = "not_" + name;
let disallowed_values = self[not_name];
const match_func = literal_keys[name];
const not_name = "not_" + name;
const disallowed_values = self[not_name];
if (disallowed_values.map(match_func)) {
return false;
}
let allowed_values = self[name];
const allowed_values = self[name];
if (allowed_values) {
if (!allowed_values.map(match_func)) {
return false;
@@ -113,7 +113,7 @@ FilterComponent.prototype._checkFields =
}
});
let contains_url_filter = this.filter_json.contains_url;
const contains_url_filter = this.filter_json.contains_url;
if (contains_url_filter !== undefined) {
if (contains_url_filter !== contains_url) {
return false;

View File

@@ -18,7 +18,7 @@ limitations under the License.
* @module filter
*/
let FilterComponent = require("./filter-component");
const FilterComponent = require("./filter-component");
/**
* @param {Object} obj
@@ -26,7 +26,7 @@ let FilterComponent = require("./filter-component");
* @param {*} val
*/
function setProp(obj, keyNesting, val) {
let nestedKeys = keyNesting.split(".");
const nestedKeys = keyNesting.split(".");
let currentObj = obj;
for (let i = 0; i < (nestedKeys.length - 1); i++) {
if (!currentObj[nestedKeys[i]]) {
@@ -106,10 +106,10 @@ Filter.prototype.setDefinition = function(definition) {
// "event_fields": ["type", "content", "sender"]
// }
let room_filter_json = definition.room;
const room_filter_json = definition.room;
// consider the top level rooms/not_rooms filter
let room_filter_fields = {};
const room_filter_fields = {};
if (room_filter_json) {
if (room_filter_json.rooms) {
room_filter_fields.rooms = room_filter_json.rooms;
@@ -183,7 +183,7 @@ Filter.prototype.setIncludeLeaveRooms = function(includeLeave) {
* @return {Filter}
*/
Filter.fromJson = function(userId, filterId, jsonObj) {
let filter = new Filter(userId, filterId);
const filter = new Filter(userId, filterId);
filter.setDefinition(jsonObj);
return filter;
};

View File

@@ -18,13 +18,13 @@ limitations under the License.
* This is an internal module. See {@link MatrixHttpApi} for the public class.
* @module http-api
*/
let q = require("q");
let utils = require("./utils");
const q = require("q");
const utils = require("./utils");
// we use our own implementation of setTimeout, so that if we get suspended in
// the middle of a /sync, we cancel the sync as soon as we awake, rather than
// waiting for the delay to elapse.
let callbacks = require("./realtime-callbacks");
const callbacks = require("./realtime-callbacks");
/*
TODO:
@@ -91,7 +91,7 @@ module.exports.MatrixHttpApi.prototype = {
* path and query parameters respectively.
*/
getContentUri: function() {
let params = {
const params = {
access_token: this.opts.accessToken,
};
return {
@@ -145,12 +145,12 @@ module.exports.MatrixHttpApi.prototype = {
// if the file doesn't have a mime type, use a default since
// the HS errors if we don't supply one.
let contentType = opts.type || file.type || 'application/octet-stream';
let fileName = opts.name || file.name;
const contentType = opts.type || file.type || 'application/octet-stream';
const fileName = opts.name || file.name;
// we used to recommend setting file.stream to the thing to upload on
// nodejs.
let body = file.stream ? file.stream : file;
const body = file.stream ? file.stream : file;
// backwards-compatibility hacks where we used to do different things
// between browser and node.
@@ -192,7 +192,7 @@ module.exports.MatrixHttpApi.prototype = {
// (browser-request doesn't support progress either, which is also kind
// of important here)
let upload = { loaded: 0, total: 0 };
const upload = { loaded: 0, total: 0 };
let promise;
// XMLHttpRequest doesn't parse JSON for us. request normally does, but
@@ -214,12 +214,12 @@ module.exports.MatrixHttpApi.prototype = {
}
if (global.XMLHttpRequest) {
let defer = q.defer();
let xhr = new global.XMLHttpRequest();
const defer = q.defer();
const xhr = new global.XMLHttpRequest();
upload.xhr = xhr;
let cb = requestCallback(defer, opts.callback, this.opts.onlyData);
const cb = requestCallback(defer, opts.callback, this.opts.onlyData);
let timeout_fn = function() {
const timeout_fn = function() {
xhr.abort();
cb(new Error('Timeout'));
};
@@ -269,7 +269,7 @@ module.exports.MatrixHttpApi.prototype = {
// dirty hack (as per _request) to allow the upload to be cancelled.
promise.abort = xhr.abort.bind(xhr);
} else {
let queryParams = {
const queryParams = {
filename: fileName,
};
@@ -283,10 +283,10 @@ module.exports.MatrixHttpApi.prototype = {
);
}
let self = this;
const self = this;
// remove the upload from the list on completion
let promise0 = promise.finally(function() {
const promise0 = promise.finally(function() {
for (let i = 0; i < self.uploads.length; ++i) {
if (self.uploads[i] === upload) {
self.uploads.splice(i, 1);
@@ -317,7 +317,7 @@ module.exports.MatrixHttpApi.prototype = {
},
idServerRequest: function(callback, method, path, params, prefix) {
let fullUri = this.opts.idBaseUrl + prefix + path;
const fullUri = this.opts.idBaseUrl + prefix + path;
if (callback !== undefined && !utils.isFunction(callback)) {
throw Error(
@@ -325,7 +325,7 @@ module.exports.MatrixHttpApi.prototype = {
);
}
let opts = {
const opts = {
uri: fullUri,
method: method,
withCredentials: false,
@@ -338,7 +338,7 @@ module.exports.MatrixHttpApi.prototype = {
opts.form = params;
}
let defer = q.defer();
const defer = q.defer();
this.opts.request(
opts,
requestCallback(defer, callback, this.opts.onlyData)
@@ -389,11 +389,11 @@ module.exports.MatrixHttpApi.prototype = {
queryParams.access_token = this.opts.accessToken;
}
let request_promise = this.request(
const request_promise = this.request(
callback, method, path, queryParams, data, opts
);
let self = this;
const self = this;
request_promise.catch(function(err) {
if (err.errcode == 'M_UNKNOWN_TOKEN') {
self.event_emitter.emit("Session.logged_out");
@@ -437,8 +437,8 @@ module.exports.MatrixHttpApi.prototype = {
*/
request: function(callback, method, path, queryParams, data, opts) {
opts = opts || {};
let prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix;
let fullUri = this.opts.baseUrl + prefix + path;
const prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix;
const fullUri = this.opts.baseUrl + prefix + path;
return this.requestOtherUrl(
callback, method, fullUri, queryParams, data, opts
@@ -613,9 +613,9 @@ module.exports.MatrixHttpApi.prototype = {
}
opts = opts || {};
let self = this;
const self = this;
if (this.opts.extraParams) {
for (let key in this.opts.extraParams) {
for (const key in this.opts.extraParams) {
if (!this.opts.extraParams.hasOwnProperty(key)) {
continue;
}
@@ -623,14 +623,14 @@ module.exports.MatrixHttpApi.prototype = {
}
}
let json = opts.json === undefined ? true : opts.json;
const json = opts.json === undefined ? true : opts.json;
let defer = q.defer();
const defer = q.defer();
let timeoutId;
let timedOut = false;
let req;
let localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs;
const localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs;
if (localTimeoutMs) {
timeoutId = callbacks.setTimeout(function() {
timedOut = true;
@@ -645,7 +645,7 @@ module.exports.MatrixHttpApi.prototype = {
}, localTimeoutMs);
}
let reqPromise = defer.promise;
const reqPromise = defer.promise;
try {
req = this.opts.request(
@@ -670,8 +670,8 @@ module.exports.MatrixHttpApi.prototype = {
// if json is falsy, we won't parse any error response, so need
// to do so before turning it into a MatrixError
let parseErrorJson = !json;
let handlerFn = requestCallback(
const parseErrorJson = !json;
const handlerFn = requestCallback(
defer, callback, self.opts.onlyData,
parseErrorJson,
opts.bodyParser
@@ -705,7 +705,7 @@ module.exports.MatrixHttpApi.prototype = {
* If parseErrorJson is true, we will JSON.parse the body if we get a 4xx error.
*
*/
let requestCallback = function(
const requestCallback = function(
defer, userDefinedCallback, onlyData,
parseErrorJson, bodyParser
) {
@@ -735,7 +735,7 @@ let requestCallback = function(
defer.reject(err);
userDefinedCallback(err);
} else {
let res = {
const res = {
code: response.statusCode,
headers: response.headers,
data: body,

View File

@@ -16,9 +16,9 @@ limitations under the License.
"use strict";
/** @module interactive-auth */
let q = require("q");
const q = require("q");
let utils = require("./utils");
const utils = require("./utils");
/**
* Abstracts the logic used to drive the interactive auth process.
@@ -115,7 +115,7 @@ InteractiveAuth.prototype = {
}
// use the sessionid from the last request.
let auth = {
const auth = {
session: this._data.session,
};
utils.extend(auth, authData);
@@ -131,7 +131,7 @@ InteractiveAuth.prototype = {
* @param {object?} auth new auth dict, including session id
*/
_doRequest: function(auth) {
let self = this;
const self = this;
// hackery to make sure that synchronous exceptions end up in the catch
// handler (without the additional event loop entailed by q.fcall or an
@@ -164,7 +164,7 @@ InteractiveAuth.prototype = {
* @private
*/
_startNextAuthStage: function() {
let nextStage = this._chooseStage();
const nextStage = this._chooseStage();
if (!nextStage) {
throw new Error("No incomplete flows from the server");
}
@@ -186,9 +186,9 @@ InteractiveAuth.prototype = {
* @return {string?} login type
*/
_chooseStage: function() {
let flow = this._chooseFlow();
const flow = this._chooseFlow();
console.log("Active flow => %s", JSON.stringify(flow));
let nextStage = this._firstUncompletedStage(flow);
const nextStage = this._firstUncompletedStage(flow);
console.log("Next stage: %s", nextStage);
return nextStage;
},
@@ -200,7 +200,7 @@ InteractiveAuth.prototype = {
* @return {object} flow
*/
_chooseFlow: function() {
let flows = this._data.flows || [];
const flows = this._data.flows || [];
// always use the first flow for now
return flows[0];
},
@@ -213,9 +213,9 @@ InteractiveAuth.prototype = {
* @return {string} login type
*/
_firstUncompletedStage: function(flow) {
let completed = (this._data || {}).completed || [];
const completed = (this._data || {}).completed || [];
for (let i = 0; i < flow.stages.length; ++i) {
let stageType = flow.stages[i];
const stageType = flow.stages[i];
if (completed.indexOf(stageType) === -1) {
return stageType;
}

View File

@@ -94,7 +94,7 @@ module.exports.getRequest = function() {
* @param {requestWrapperFunction} wrapper The wrapping function.
*/
module.exports.wrapRequest = function(wrapper) {
let origRequest = request;
const origRequest = request;
request = function(options, callback) {
return wrapper(origRequest, options, callback);
};

View File

@@ -17,12 +17,12 @@ limitations under the License.
/**
* @module models/event-timeline-set
*/
let EventEmitter = require("events").EventEmitter;
let utils = require("../utils");
let EventTimeline = require("./event-timeline");
const EventEmitter = require("events").EventEmitter;
const utils = require("../utils");
const EventTimeline = require("./event-timeline");
// var DEBUG = false;
let DEBUG = true;
const DEBUG = true;
let debuglog;
if (DEBUG) {
@@ -136,7 +136,7 @@ EventTimelineSet.prototype.eventIdToTimeline = function(eventId) {
* @param {String} newEventId event ID of the replacement event
*/
EventTimelineSet.prototype.replaceEventId = function(oldEventId, newEventId) {
let existingTimeline = this._eventIdToTimeline[oldEventId];
const existingTimeline = this._eventIdToTimeline[oldEventId];
if (existingTimeline) {
delete this._eventIdToTimeline[oldEventId];
this._eventIdToTimeline[newEventId] = existingTimeline;
@@ -166,13 +166,13 @@ EventTimelineSet.prototype.resetLiveTimeline = function(backPaginationToken, flu
}
// initialise the state in the new timeline from our last known state
let evMap = this._liveTimeline.getState(EventTimeline.FORWARDS).events;
let events = [];
for (let evtype in evMap) {
const evMap = this._liveTimeline.getState(EventTimeline.FORWARDS).events;
const events = [];
for (const evtype in evMap) {
if (!evMap.hasOwnProperty(evtype)) {
continue;
}
for (let stateKey in evMap[evtype]) {
for (const stateKey in evMap[evtype]) {
if (!evMap[evtype].hasOwnProperty(stateKey)) {
continue;
}
@@ -198,7 +198,7 @@ EventTimelineSet.prototype.resetLiveTimeline = function(backPaginationToken, flu
* the given event, or null if unknown
*/
EventTimelineSet.prototype.getTimelineForEvent = function(eventId) {
let res = this._eventIdToTimeline[eventId];
const res = this._eventIdToTimeline[eventId];
return (res === undefined) ? null : res;
};
@@ -209,7 +209,7 @@ EventTimelineSet.prototype.getTimelineForEvent = function(eventId) {
* @return {?module:models/event~MatrixEvent} the given event, or undefined if unknown
*/
EventTimelineSet.prototype.findEventById = function(eventId) {
let tl = this.getTimelineForEvent(eventId);
const tl = this.getTimelineForEvent(eventId);
if (!tl) {
return undefined;
}
@@ -230,7 +230,7 @@ EventTimelineSet.prototype.addTimeline = function() {
" it.");
}
let timeline = new EventTimeline(this);
const timeline = new EventTimeline(this);
this._timelines.push(timeline);
return timeline;
};
@@ -277,9 +277,9 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
}
}
let direction = toStartOfTimeline ? EventTimeline.BACKWARDS :
const direction = toStartOfTimeline ? EventTimeline.BACKWARDS :
EventTimeline.FORWARDS;
let inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS :
const inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS :
EventTimeline.BACKWARDS;
// Adding events to timelines can be quite complicated. The following
@@ -354,10 +354,10 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
let didUpdate = false;
let lastEventWasNew = false;
for (let i = 0; i < events.length; i++) {
let event = events[i];
let eventId = event.getId();
const event = events[i];
const eventId = event.getId();
let existingTimeline = this._eventIdToTimeline[eventId];
const existingTimeline = this._eventIdToTimeline[eventId];
if (!existingTimeline) {
// we don't know about this event yet. Just add it to the timeline.
@@ -374,7 +374,7 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
continue;
}
let neighbour = timeline.getNeighbouringTimeline(direction);
const neighbour = timeline.getNeighbouringTimeline(direction);
if (neighbour) {
// this timeline already has a neighbour in the relevant direction;
// let's assume the timelines are already correctly linked up, and
@@ -422,18 +422,18 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
*/
EventTimelineSet.prototype.addLiveEvent = function(event, duplicateStrategy) {
if (this._filter) {
let events = this._filter.filterRoomTimeline([event]);
const events = this._filter.filterRoomTimeline([event]);
if (!events.length) {
return;
}
}
let timeline = this._eventIdToTimeline[event.getId()];
const timeline = this._eventIdToTimeline[event.getId()];
if (timeline) {
if (duplicateStrategy === "replace") {
debuglog("EventTimelineSet.addLiveEvent: replacing duplicate event " +
event.getId());
let tlEvents = timeline.getEvents();
const tlEvents = timeline.getEvents();
for (let j = 0; j < tlEvents.length; j++) {
if (tlEvents[j].getId() === event.getId()) {
// still need to set the right metadata on this event
@@ -475,11 +475,11 @@ EventTimelineSet.prototype.addLiveEvent = function(event, duplicateStrategy) {
*/
EventTimelineSet.prototype.addEventToTimeline = function(event, timeline,
toStartOfTimeline) {
let eventId = event.getId();
const eventId = event.getId();
timeline.addEvent(event, toStartOfTimeline);
this._eventIdToTimeline[eventId] = timeline;
let data = {
const data = {
timeline: timeline,
liveEvent: !toStartOfTimeline && timeline == this._liveTimeline,
};
@@ -500,7 +500,7 @@ EventTimelineSet.prototype.addEventToTimeline = function(event, timeline,
EventTimelineSet.prototype.handleRemoteEcho = function(localEvent, oldEventId,
newEventId) {
// XXX: why don't we infer newEventId from localEvent?
let existingTimeline = this._eventIdToTimeline[oldEventId];
const existingTimeline = this._eventIdToTimeline[oldEventId];
if (existingTimeline) {
delete this._eventIdToTimeline[oldEventId];
this._eventIdToTimeline[newEventId] = existingTimeline;
@@ -524,15 +524,15 @@ EventTimelineSet.prototype.handleRemoteEcho = function(localEvent, oldEventId,
* in this room.
*/
EventTimelineSet.prototype.removeEvent = function(eventId) {
let timeline = this._eventIdToTimeline[eventId];
const timeline = this._eventIdToTimeline[eventId];
if (!timeline) {
return null;
}
let removed = timeline.removeEvent(eventId);
const removed = timeline.removeEvent(eventId);
if (removed) {
delete this._eventIdToTimeline[eventId];
let data = {
const data = {
timeline: timeline,
};
this.emit("Room.timeline", removed, this.room, undefined, true, data);
@@ -558,8 +558,8 @@ EventTimelineSet.prototype.compareEventOrdering = function(eventId1, eventId2) {
return 0;
}
let timeline1 = this._eventIdToTimeline[eventId1];
let timeline2 = this._eventIdToTimeline[eventId2];
const timeline1 = this._eventIdToTimeline[eventId1];
const timeline2 = this._eventIdToTimeline[eventId2];
if (timeline1 === undefined) {
return null;
@@ -572,10 +572,10 @@ EventTimelineSet.prototype.compareEventOrdering = function(eventId1, eventId2) {
// both events are in the same timeline - figure out their
// relative indices
let idx1, idx2;
let events = timeline1.getEvents();
const events = timeline1.getEvents();
for (let idx = 0; idx < events.length &&
(idx1 === undefined || idx2 === undefined); idx++) {
let evId = events[idx].getId();
const evId = events[idx].getId();
if (evId == eventId1) {
idx1 = idx;
}

View File

@@ -4,9 +4,9 @@
* @module models/event-timeline
*/
let RoomState = require("./room-state");
let utils = require("../utils");
let MatrixEvent = require("./event").MatrixEvent;
const RoomState = require("./room-state");
const utils = require("../utils");
const MatrixEvent = require("./event").MatrixEvent;
/**
* Construct a new EventTimeline
@@ -75,7 +75,7 @@ EventTimeline.prototype.initialiseState = function(stateEvents) {
// we deep-copy the events here, in case they get changed later - we don't
// want changes to the start state leaking through to the end state.
let oldStateEvents = utils.map(
const oldStateEvents = utils.map(
utils.deepCopy(
stateEvents.map(function(mxEvent) {
return mxEvent.event;
@@ -237,10 +237,10 @@ EventTimeline.prototype.setNeighbouringTimeline = function(neighbour, direction)
* @param {boolean} atStart true to insert new event at the start
*/
EventTimeline.prototype.addEvent = function(event, atStart) {
let stateContext = atStart ? this._startState : this._endState;
const stateContext = atStart ? this._startState : this._endState;
// only call setEventMetadata on the unfiltered timelineSets
let timelineSet = this.getTimelineSet();
const timelineSet = this.getTimelineSet();
if (timelineSet.room &&
timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {
EventTimeline.setEventMetadata(event, stateContext, atStart);
@@ -314,7 +314,7 @@ EventTimeline.setEventMetadata = function(event, stateContext, toStartOfTimeline
*/
EventTimeline.prototype.removeEvent = function(eventId) {
for (let i = this._events.length - 1; i >= 0; i--) {
let ev = this._events[i];
const ev = this._events[i];
if (ev.getId() == eventId) {
this._events.splice(i, 1);
if (i < this._baseIndex) {

View File

@@ -21,9 +21,9 @@ limitations under the License.
* @module models/event
*/
let EventEmitter = require("events").EventEmitter;
const EventEmitter = require("events").EventEmitter;
let utils = require('../utils.js');
const utils = require('../utils.js');
/**
* Enum for event statuses.
@@ -350,8 +350,8 @@ utils.extend(module.exports.MatrixEvent.prototype, {
}
}
let keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {};
let content = this.getContent();
const keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {};
const content = this.getContent();
for (key in content) {
if (!content.hasOwnProperty(key)) {
continue;
@@ -424,7 +424,7 @@ utils.extend(module.exports.MatrixEvent.prototype, {
* m.room.aliases allows key aliases
*/
// a map giving the keys we keep when an event is redacted
let _REDACT_KEEP_KEY_MAP = [
const _REDACT_KEEP_KEY_MAP = [
'event_id', 'type', 'room_id', 'user_id', 'state_key', 'prev_state',
'content', 'unsigned',
].reduce(function(ret, val) {
@@ -432,7 +432,7 @@ let _REDACT_KEEP_KEY_MAP = [
}, {});
// a map from event type to the .content keys we keep when an event is redacted
let _REDACT_KEEP_CONTENT_MAP = {
const _REDACT_KEEP_CONTENT_MAP = {
'm.room.member': {'membership': 1},
'm.room.create': {'creator': 1},
'm.room.join_rules': {'join_rule': 1},

View File

@@ -17,10 +17,10 @@ limitations under the License.
/**
* @module models/room-member
*/
let EventEmitter = require("events").EventEmitter;
let ContentRepo = require("../content-repo");
const EventEmitter = require("events").EventEmitter;
const ContentRepo = require("../content-repo");
let utils = require("../utils");
const utils = require("../utils");
/**
* Construct a new room member.
@@ -73,10 +73,10 @@ RoomMember.prototype.setMembershipEvent = function(event, roomState) {
}
this.events.member = event;
let oldMembership = this.membership;
const oldMembership = this.membership;
this.membership = event.getDirectionalContent().membership;
let oldName = this.name;
const oldName = this.name;
this.name = calculateDisplayName(this, event, roomState);
if (oldMembership !== this.membership) {
this._updateModifiedTime();
@@ -103,8 +103,8 @@ RoomMember.prototype.setPowerLevelEvent = function(powerLevelEvent) {
utils.forEach(utils.values(powerLevelEvent.getContent().users), function(lvl) {
maxLevel = Math.max(maxLevel, lvl);
});
let oldPowerLevel = this.powerLevel;
let oldPowerLevelNorm = this.powerLevelNorm;
const oldPowerLevel = this.powerLevel;
const oldPowerLevelNorm = this.powerLevelNorm;
if (powerLevelEvent.getContent().users[this.userId] !== undefined) {
this.powerLevel = powerLevelEvent.getContent().users[this.userId];
@@ -136,9 +136,9 @@ RoomMember.prototype.setTypingEvent = function(event) {
if (event.getType() !== "m.typing") {
return;
}
let oldTyping = this.typing;
const oldTyping = this.typing;
this.typing = false;
let typingList = event.getContent().user_ids;
const typingList = event.getContent().user_ids;
if (!utils.isArray(typingList)) {
// malformed event :/ bail early. TODO: whine?
return;
@@ -195,8 +195,8 @@ RoomMember.prototype.getAvatarUrl =
if (!this.events.member && !allowDefault) {
return null;
}
let rawUrl = this.events.member ? this.events.member.getContent().avatar_url : null;
let httpUrl = ContentRepo.getHttpUriForMxc(
const rawUrl = this.events.member ? this.events.member.getContent().avatar_url : null;
const httpUrl = ContentRepo.getHttpUriForMxc(
baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks
);
if (httpUrl) {
@@ -210,8 +210,8 @@ RoomMember.prototype.getAvatarUrl =
};
function calculateDisplayName(member, event, roomState) {
let displayName = event.getDirectionalContent().displayname;
let selfUserId = member.userId;
const displayName = event.getDirectionalContent().displayname;
const selfUserId = member.userId;
if (!displayName) {
return selfUserId;
@@ -221,8 +221,8 @@ function calculateDisplayName(member, event, roomState) {
return displayName;
}
let userIds = roomState.getUserIdsWithDisplayName(displayName);
let otherUsers = userIds.filter(function(u) {
const userIds = roomState.getUserIdsWithDisplayName(displayName);
const otherUsers = userIds.filter(function(u) {
return u !== selfUserId;
});
if (otherUsers.length > 0) {

View File

@@ -17,10 +17,10 @@ limitations under the License.
/**
* @module models/room-state
*/
let EventEmitter = require("events").EventEmitter;
const EventEmitter = require("events").EventEmitter;
let utils = require("../utils");
let RoomMember = require("./room-member");
const utils = require("../utils");
const RoomMember = require("./room-member");
/**
* Construct room state.
@@ -100,7 +100,7 @@ RoomState.prototype.getStateEvents = function(eventType, stateKey) {
if (stateKey === undefined) { // return all values
return utils.values(this.events[eventType]);
}
let event = this.events[eventType][stateKey];
const event = this.events[eventType][stateKey];
return event ? event : null;
};
@@ -115,7 +115,7 @@ RoomState.prototype.getStateEvents = function(eventType, stateKey) {
* @fires module:client~MatrixClient#event:"RoomState.events"
*/
RoomState.prototype.setStateEvents = function(stateEvents) {
let self = this;
const self = this;
this._updateModifiedTime();
// update the core event dict
@@ -153,7 +153,7 @@ RoomState.prototype.setStateEvents = function(stateEvents) {
}
if (event.getType() === "m.room.member") {
let userId = event.getStateKey();
const userId = event.getStateKey();
// leave events apparently elide the displayname or avatar_url,
// so let's fake one up so that we don't leak user ids
@@ -178,11 +178,11 @@ RoomState.prototype.setStateEvents = function(stateEvents) {
// so we don't make assumptions about the properties of RoomMember
// (e.g. and manage to break it because deep copying doesn't do
// everything).
let sentinel = new RoomMember(event.getRoomId(), userId);
const sentinel = new RoomMember(event.getRoomId(), userId);
utils.forEach([member, sentinel], function(roomMember) {
roomMember.setMembershipEvent(event, self);
// this member may have a power level already, so set it.
let pwrLvlEvent = self.getStateEvents("m.room.power_levels", "");
const pwrLvlEvent = self.getStateEvents("m.room.power_levels", "");
if (pwrLvlEvent) {
roomMember.setPowerLevelEvent(pwrLvlEvent);
}
@@ -192,7 +192,7 @@ RoomState.prototype.setStateEvents = function(stateEvents) {
self.members[userId] = member;
self.emit("RoomState.members", event, self, member);
} else if (event.getType() === "m.room.power_levels") {
let members = utils.values(self.members);
const members = utils.values(self.members);
utils.forEach(members, function(member) {
member.setPowerLevelEvent(event);
self.emit("RoomState.members", event, self, member);
@@ -312,12 +312,12 @@ RoomState.prototype.maySendStateEvent = function(stateEventType, userId) {
* according to the room's state.
*/
RoomState.prototype._maySendEventOfType = function(eventType, userId, state) {
let member = this.getMember(userId);
const member = this.getMember(userId);
if (!member || member.membership == 'leave') {
return false;
}
let power_levels_event = this.getStateEvents('m.room.power_levels', '');
const power_levels_event = this.getStateEvents('m.room.power_levels', '');
let power_levels;
let events_levels = {};
@@ -355,11 +355,11 @@ function _updateThirdPartyTokenCache(roomState, memberEvent) {
if (!memberEvent.getContent().third_party_invite) {
return;
}
let token = (memberEvent.getContent().third_party_invite.signed || {}).token;
const token = (memberEvent.getContent().third_party_invite.signed || {}).token;
if (!token) {
return;
}
let threePidInvite = roomState.getStateEvents(
const threePidInvite = roomState.getStateEvents(
"m.room.third_party_invite", token
);
if (!threePidInvite) {
@@ -369,14 +369,14 @@ function _updateThirdPartyTokenCache(roomState, memberEvent) {
}
function _updateDisplayNameCache(roomState, userId, displayName) {
let oldName = roomState._userIdsToDisplayNames[userId];
const oldName = roomState._userIdsToDisplayNames[userId];
delete roomState._userIdsToDisplayNames[userId];
if (oldName) {
// Remove the old name from the cache.
// We clobber the user_id > name lookup but the name -> [user_id] lookup
// means we need to remove that user ID from that array rather than nuking
// the lot.
let existingUserIds = roomState._displayNameToUserIds[oldName] || [];
const existingUserIds = roomState._displayNameToUserIds[oldName] || [];
for (let i = 0; i < existingUserIds.length; i++) {
if (existingUserIds[i] === userId) {
// remove this user ID from this array

View File

@@ -17,22 +17,22 @@ limitations under the License.
/**
* @module models/room
*/
let EventEmitter = require("events").EventEmitter;
const EventEmitter = require("events").EventEmitter;
let EventStatus = require("./event").EventStatus;
let RoomSummary = require("./room-summary");
let MatrixEvent = require("./event").MatrixEvent;
let utils = require("../utils");
let ContentRepo = require("../content-repo");
let EventTimeline = require("./event-timeline");
let EventTimelineSet = require("./event-timeline-set");
const EventStatus = require("./event").EventStatus;
const RoomSummary = require("./room-summary");
const MatrixEvent = require("./event").MatrixEvent;
const utils = require("../utils");
const ContentRepo = require("../content-repo");
const EventTimeline = require("./event-timeline");
const EventTimelineSet = require("./event-timeline-set");
function synthesizeReceipt(userId, event, receiptType) {
// console.log("synthesizing receipt for "+event.getId());
// This is really ugly because JS has no way to express an object literal
// where the name of a key comes from an expression
let fakeReceipt = {
const fakeReceipt = {
content: {},
type: "m.receipt",
room_id: event.getRoomId(),
@@ -308,7 +308,7 @@ Room.prototype.setUnreadNotificationCount = function(type, count) {
*/
Room.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod,
allowDefault) {
let roomAvatarEvent = this.currentState.getStateEvents("m.room.avatar", "");
const roomAvatarEvent = this.currentState.getStateEvents("m.room.avatar", "");
if (allowDefault === undefined) {
allowDefault = true;
}
@@ -316,7 +316,7 @@ Room.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod,
return null;
}
let mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;
const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;
if (mainUrl) {
return ContentRepo.getHttpUriForMxc(
baseUrl, mainUrl, width, height, resizeMethod
@@ -337,12 +337,12 @@ Room.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod,
* @return {array} The room's alias as an array of strings
*/
Room.prototype.getAliases = function() {
let alias_strings = [];
const alias_strings = [];
let alias_events = this.currentState.getStateEvents("m.room.aliases");
const alias_events = this.currentState.getStateEvents("m.room.aliases");
if (alias_events) {
for (let i = 0; i < alias_events.length; ++i) {
let alias_event = alias_events[i];
const alias_event = alias_events[i];
if (utils.isArray(alias_event.getContent().aliases)) {
Array.prototype.push.apply(
alias_strings, alias_event.getContent().aliases
@@ -360,7 +360,7 @@ Room.prototype.getAliases = function() {
* @return {?string} The room's canonical alias, or null if there is none
*/
Room.prototype.getCanonicalAlias = function() {
let canonicalAlias = this.currentState.getStateEvents("m.room.canonical_alias", "");
const canonicalAlias = this.currentState.getStateEvents("m.room.canonical_alias", "");
if (canonicalAlias) {
return canonicalAlias.getContent().alias;
}
@@ -400,7 +400,7 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline,
* @return {RoomMember} The member or <code>null</code>.
*/
Room.prototype.getMember = function(userId) {
let member = this.currentState.members[userId];
const member = this.currentState.members[userId];
if (!member) {
return null;
}
@@ -445,7 +445,7 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline,
* @return {boolean} True if this user_id has the given membership state.
*/
Room.prototype.hasMembershipState = function(userId, membership) {
let member = this.getMember(userId);
const member = this.getMember(userId);
if (!member) {
return false;
}
@@ -461,8 +461,8 @@ Room.prototype.getOrCreateFilteredTimelineSet = function(filter) {
if (this._filteredTimelineSets[filter.filterId]) {
return this._filteredTimelineSets[filter.filterId];
}
let opts = Object.assign({ filter: filter }, this._opts);
let timelineSet = new EventTimelineSet(this, opts);
const opts = Object.assign({ filter: filter }, this._opts);
const timelineSet = new EventTimelineSet(this, opts);
reEmit(this, timelineSet, ["Room.timeline", "Room.timelineReset"]);
this._filteredTimelineSets[filter.filterId] = timelineSet;
this._timelineSets.push(timelineSet);
@@ -474,7 +474,7 @@ Room.prototype.getOrCreateFilteredTimelineSet = function(filter) {
// may have grown huge and so take a long time to filter.
// see https://github.com/vector-im/vector-web/issues/2109
let unfilteredLiveTimeline = this.getLiveTimeline();
const unfilteredLiveTimeline = this.getLiveTimeline();
unfilteredLiveTimeline.getEvents().forEach(function(event) {
timelineSet.addLiveEvent(event);
@@ -508,9 +508,9 @@ Room.prototype.getOrCreateFilteredTimelineSet = function(filter) {
* @param {Filter} filter the filter whose timelineSet is to be forgotten
*/
Room.prototype.removeFilteredTimelineSet = function(filter) {
let timelineSet = this._filteredTimelineSets[filter.filterId];
const timelineSet = this._filteredTimelineSets[filter.filterId];
delete this._filteredTimelineSets[filter.filterId];
let i = this._timelineSets.indexOf(timelineSet);
const i = this._timelineSets.indexOf(timelineSet);
if (i > -1) {
this._timelineSets.splice(i, 1);
}
@@ -528,10 +528,10 @@ Room.prototype.removeFilteredTimelineSet = function(filter) {
Room.prototype._addLiveEvent = function(event, duplicateStrategy) {
let i;
if (event.getType() === "m.room.redaction") {
let redactId = event.event.redacts;
const redactId = event.event.redacts;
// if we know about this event, redact its contents now.
let redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
if (redactedEvent) {
redactedEvent.makeRedacted(event);
this.emit("Room.redaction", event, this);
@@ -551,7 +551,7 @@ Room.prototype._addLiveEvent = function(event, duplicateStrategy) {
}
if (event.getUnsigned().transaction_id) {
let existingEvent = this._txnToEvent[event.getUnsigned().transaction_id];
const existingEvent = this._txnToEvent[event.getUnsigned().transaction_id];
if (existingEvent) {
// remote echo of an event we sent earlier
this._handleRemoteEcho(event, existingEvent);
@@ -625,7 +625,7 @@ Room.prototype.addPendingEvent = function(event, txnId) {
this._pendingEventList.push(event);
} else {
for (let i = 0; i < this._timelineSets.length; i++) {
let timelineSet = this._timelineSets[i];
const timelineSet = this._timelineSets[i];
if (timelineSet.getFilter()) {
if (this._filter.filterRoomTimeline([event]).length) {
timelineSet.addEventToTimeline(event,
@@ -656,9 +656,9 @@ Room.prototype.addPendingEvent = function(event, txnId) {
* @private
*/
Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) {
let oldEventId = localEvent.getId();
let newEventId = remoteEvent.getId();
let oldStatus = localEvent.status;
const oldEventId = localEvent.getId();
const newEventId = remoteEvent.getId();
const oldStatus = localEvent.status;
// no longer pending
delete this._txnToEvent[remoteEvent.transaction_id];
@@ -678,7 +678,7 @@ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) {
localEvent.handleRemoteEcho(remoteEvent.event);
for (let i = 0; i < this._timelineSets.length; i++) {
let timelineSet = this._timelineSets[i];
const timelineSet = this._timelineSets[i];
// if it's already in the timeline, update the timeline map. If it's not, add it.
timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
@@ -690,7 +690,7 @@ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) {
/* a map from current event status to a list of allowed next statuses
*/
let ALLOWED_TRANSITIONS = {};
const ALLOWED_TRANSITIONS = {};
ALLOWED_TRANSITIONS[EventStatus.ENCRYPTING] = [
EventStatus.SENDING,
@@ -737,7 +737,7 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) {
// SENT races against /sync, so we have to special-case it.
if (newStatus == EventStatus.SENT) {
let timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId);
const timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId);
if (timeline) {
// we've already received the event via the event stream.
// nothing more to do here.
@@ -745,15 +745,15 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) {
}
}
let oldStatus = event.status;
let oldEventId = event.getId();
const oldStatus = event.status;
const oldEventId = event.getId();
if (!oldStatus) {
throw new Error("updatePendingEventStatus called on an event which is " +
"not a local echo.");
}
let allowed = ALLOWED_TRANSITIONS[oldStatus];
const allowed = ALLOWED_TRANSITIONS[oldStatus];
if (!allowed || allowed.indexOf(newStatus) < 0) {
throw new Error("Invalid EventStatus transition " + oldStatus + "->" +
newStatus);
@@ -812,7 +812,7 @@ Room.prototype.addLiveEvents = function(events, duplicateStrategy) {
// sanity check that the live timeline is still live
for (i = 0; i < this._timelineSets.length; i++) {
let liveTimeline = this._timelineSets[i].getLiveTimeline();
const liveTimeline = this._timelineSets[i].getLiveTimeline();
if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {
throw new Error(
"live timeline " + i + " is no longer live - it has a pagination token " +
@@ -863,7 +863,7 @@ Room.prototype.removeEvents = function(event_ids) {
Room.prototype.removeEvent = function(eventId) {
let removedAny = false;
for (let i = 0; i < this._timelineSets.length; i++) {
let removed = this._timelineSets[i].removeEvent(eventId);
const removed = this._timelineSets[i].removeEvent(eventId);
if (removed) {
removedAny = true;
}
@@ -882,14 +882,14 @@ Room.prototype.removeEvent = function(eventId) {
Room.prototype.recalculate = function(userId) {
// set fake stripped state events if this is an invite room so logic remains
// consistent elsewhere.
let self = this;
let membershipEvent = this.currentState.getStateEvents(
const self = this;
const membershipEvent = this.currentState.getStateEvents(
"m.room.member", userId
);
if (membershipEvent && membershipEvent.getContent().membership === "invite") {
let strippedStateEvents = membershipEvent.event.invite_room_state || [];
const strippedStateEvents = membershipEvent.event.invite_room_state || [];
utils.forEach(strippedStateEvents, function(strippedEvent) {
let existingEvent = self.currentState.getStateEvents(
const existingEvent = self.currentState.getStateEvents(
strippedEvent.type, strippedEvent.state_key
);
if (!existingEvent) {
@@ -906,7 +906,7 @@ Room.prototype.recalculate = function(userId) {
});
}
let oldName = this.name;
const oldName = this.name;
this.name = calculateRoomName(this, userId);
this.summary = new RoomSummary(this.roomId, {
title: this.name,
@@ -1004,18 +1004,18 @@ Room.prototype.addReceipt = function(event, fake) {
* @param {Object} receipts The object to add receipts to
*/
Room.prototype._addReceiptsToStructure = function(event, receipts) {
let self = this;
const self = this;
utils.keys(event.getContent()).forEach(function(eventId) {
utils.keys(event.getContent()[eventId]).forEach(function(receiptType) {
utils.keys(event.getContent()[eventId][receiptType]).forEach(
function(userId) {
let receipt = event.getContent()[eventId][receiptType][userId];
const receipt = event.getContent()[eventId][receiptType][userId];
if (!receipts[receiptType]) {
receipts[receiptType] = {};
}
let existingReceipt = receipts[receiptType][userId];
const existingReceipt = receipts[receiptType][userId];
if (!existingReceipt) {
receipts[receiptType][userId] = {};
@@ -1024,7 +1024,7 @@ Room.prototype._addReceiptsToStructure = function(event, receipts) {
// than the one we already have. (This is managed
// server-side, but because we synthesize RRs locally we
// have to do it here too.)
let ordering = self.getUnfilteredTimelineSet().compareEventOrdering(
const ordering = self.getUnfilteredTimelineSet().compareEventOrdering(
existingReceipt.eventId, eventId);
if (ordering !== null && ordering >= 0) {
return;
@@ -1046,10 +1046,10 @@ Room.prototype._addReceiptsToStructure = function(event, receipts) {
* @return {Object} Map of receipts by event ID
*/
Room.prototype._buildReceiptCache = function(receipts) {
let receiptCacheByEventId = {};
const receiptCacheByEventId = {};
utils.keys(receipts).forEach(function(receiptType) {
utils.keys(receipts[receiptType]).forEach(function(userId) {
let receipt = receipts[receiptType][userId];
const receipt = receipts[receiptType][userId];
if (!receiptCacheByEventId[receipt.eventId]) {
receiptCacheByEventId[receipt.eventId] = [];
}
@@ -1102,7 +1102,7 @@ Room.prototype.addTags = function(event) {
*/
Room.prototype.addAccountData = function(events) {
for (let i = 0; i < events.length; i++) {
let event = events[i];
const event = events[i];
if (event.getType() === "m.tag") {
this.addTags(event);
}
@@ -1134,7 +1134,7 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) {
if (!ignoreRoomNameEvent) {
// check for an alias, if any. for now, assume first alias is the
// official one.
let mRoomName = room.currentState.getStateEvents("m.room.name", "");
const mRoomName = room.currentState.getStateEvents("m.room.name", "");
if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) {
return mRoomName.getContent().name;
}
@@ -1143,7 +1143,7 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) {
let alias = room.getCanonicalAlias();
if (!alias) {
let aliases = room.getAliases();
const aliases = room.getAliases();
if (aliases.length) {
alias = aliases[0];
@@ -1154,16 +1154,16 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) {
}
// get members that are NOT ourselves and are actually in the room.
let otherMembers = utils.filter(room.currentState.getMembers(), function(m) {
const otherMembers = utils.filter(room.currentState.getMembers(), function(m) {
return (m.userId !== userId && m.membership !== "leave");
});
let allMembers = utils.filter(room.currentState.getMembers(), function(m) {
const allMembers = utils.filter(room.currentState.getMembers(), function(m) {
return (m.membership !== "leave");
});
let myMemberEventArray = utils.filter(room.currentState.getMembers(), function(m) {
const myMemberEventArray = utils.filter(room.currentState.getMembers(), function(m) {
return (m.userId == userId);
});
let myMemberEvent = (
const myMemberEvent = (
(myMemberEventArray.length && myMemberEventArray[0].events) ?
myMemberEventArray[0].events.member.event : undefined
);
@@ -1190,7 +1190,7 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) {
// self-chat, peeked room with 1 participant,
// or inbound invite, or outbound 3PID invite.
if (allMembers[0].userId === userId) {
let thirdPartyInvites =
const thirdPartyInvites =
room.currentState.getStateEvents("m.room.third_party_invite");
if (thirdPartyInvites && thirdPartyInvites.length > 0) {
let name = "Inviting " +
@@ -1238,7 +1238,7 @@ function reEmit(reEmitEntity, emittableEntity, eventNames) {
// Transformation Example:
// listener on "foo" => function(a,b) { ... }
// Re-emit on "thing" => thing.emit("foo", a, b)
let newArgs = [eventName];
const newArgs = [eventName];
for (let i = 0; i < arguments.length; i++) {
newArgs.push(arguments[i]);
}

View File

@@ -19,8 +19,8 @@ limitations under the License.
* @module models/search-result
*/
let EventContext = require("./event-context");
let utils = require("../utils");
const EventContext = require("./event-context");
const utils = require("../utils");
/**
* Construct a new SearchResult
@@ -45,11 +45,11 @@ function SearchResult(rank, eventContext) {
*/
SearchResult.fromJson = function(jsonObj, eventMapper) {
let jsonContext = jsonObj.context || {};
let events_before = jsonContext.events_before || [];
let events_after = jsonContext.events_after || [];
const jsonContext = jsonObj.context || {};
const events_before = jsonContext.events_before || [];
const events_after = jsonContext.events_after || [];
let context = new EventContext(eventMapper(jsonObj.result));
const context = new EventContext(eventMapper(jsonObj.result));
context.setPaginateToken(jsonContext.start, true);
context.addEvents(utils.map(events_before, eventMapper), true);

View File

@@ -17,8 +17,8 @@ limitations under the License.
/**
* @module models/user
*/
let EventEmitter = require("events").EventEmitter;
let utils = require("../utils");
const EventEmitter = require("events").EventEmitter;
const utils = require("../utils");
/**
* Construct a new User. A User must have an ID and can optionally have extra
@@ -73,10 +73,10 @@ User.prototype.setPresenceEvent = function(event) {
if (event.getType() !== "m.presence") {
return;
}
let firstFire = this.events.presence === null;
const firstFire = this.events.presence === null;
this.events.presence = event;
let eventsToFire = [];
const eventsToFire = [];
if (event.getContent().presence !== this.presence || firstFire) {
eventsToFire.push("User.presence");
}
@@ -122,7 +122,7 @@ User.prototype.setPresenceEvent = function(event) {
* @param {string} name The new display name.
*/
User.prototype.setDisplayName = function(name) {
let oldName = this.displayName;
const oldName = this.displayName;
this.displayName = name;
if (name !== oldName) {
this._updateModifiedTime();
@@ -146,7 +146,7 @@ User.prototype.setRawDisplayName = function(name) {
* @param {string} url The new avatar URL.
*/
User.prototype.setAvatarUrl = function(url) {
let oldUrl = this.avatarUrl;
const oldUrl = this.avatarUrl;
this.avatarUrl = url;
if (url !== oldUrl) {
this._updateModifiedTime();

View File

@@ -23,25 +23,25 @@ limitations under the License.
* @param {Object} client The Matrix client object to use
*/
function PushProcessor(client) {
let escapeRegExp = function(string) {
const escapeRegExp = function(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
let matchingRuleFromKindSet = function(ev, kindset, device) {
let rulekinds_in_order = ['override', 'content', 'room', 'sender', 'underride'];
const matchingRuleFromKindSet = function(ev, kindset, device) {
const rulekinds_in_order = ['override', 'content', 'room', 'sender', 'underride'];
for (let ruleKindIndex = 0;
ruleKindIndex < rulekinds_in_order.length;
++ruleKindIndex) {
let kind = rulekinds_in_order[ruleKindIndex];
let ruleset = kindset[kind];
const kind = rulekinds_in_order[ruleKindIndex];
const ruleset = kindset[kind];
for (let ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) {
let rule = ruleset[ruleIndex];
const rule = ruleset[ruleIndex];
if (!rule.enabled) {
continue;
}
let rawrule = templateRuleToRaw(kind, rule, device);
const rawrule = templateRuleToRaw(kind, rule, device);
if (!rawrule) {
continue;
}
@@ -55,8 +55,8 @@ function PushProcessor(client) {
return null;
};
let templateRuleToRaw = function(kind, tprule, device) {
let rawrule = {
const templateRuleToRaw = function(kind, tprule, device) {
const rawrule = {
'rule_id': tprule.rule_id,
'actions': tprule.actions,
'conditions': [],
@@ -106,18 +106,18 @@ function PushProcessor(client) {
return rawrule;
};
let ruleMatchesEvent = function(rule, ev) {
const ruleMatchesEvent = function(rule, ev) {
let ret = true;
for (let i = 0; i < rule.conditions.length; ++i) {
let cond = rule.conditions[i];
const cond = rule.conditions[i];
ret &= eventFulfillsCondition(cond, ev);
}
//console.log("Rule "+rule.rule_id+(ret ? " matches" : " doesn't match"));
return ret;
};
let eventFulfillsCondition = function(cond, ev) {
let condition_functions = {
const eventFulfillsCondition = function(cond, ev) {
const condition_functions = {
"event_match": eventFulfillsEventMatchCondition,
"device": eventFulfillsDeviceCondition,
"contains_display_name": eventFulfillsDisplayNameCondition,
@@ -129,26 +129,26 @@ function PushProcessor(client) {
return true;
};
let eventFulfillsRoomMemberCountCondition = function(cond, ev) {
const eventFulfillsRoomMemberCountCondition = function(cond, ev) {
if (!cond.is) {
return false;
}
let room = client.getRoom(ev.getRoomId());
const room = client.getRoom(ev.getRoomId());
if (!room || !room.currentState || !room.currentState.members) {
return false;
}
let memberCount = Object.keys(room.currentState.members).filter(function(m) {
const memberCount = Object.keys(room.currentState.members).filter(function(m) {
return room.currentState.members[m].membership == 'join';
}).length;
let m = cond.is.match(/^([=<>]*)([0-9]*)$/);
const m = cond.is.match(/^([=<>]*)([0-9]*)$/);
if (!m) {
return false;
}
let ineq = m[1];
let rhs = parseInt(m[2]);
const ineq = m[1];
const rhs = parseInt(m[2]);
if (isNaN(rhs)) {
return false;
}
@@ -169,32 +169,32 @@ function PushProcessor(client) {
}
};
let eventFulfillsDisplayNameCondition = function(cond, ev) {
let content = ev.getContent();
const eventFulfillsDisplayNameCondition = function(cond, ev) {
const content = ev.getContent();
if (!content || !content.body || typeof content.body != 'string') {
return false;
}
let room = client.getRoom(ev.getRoomId());
const room = client.getRoom(ev.getRoomId());
if (!room || !room.currentState || !room.currentState.members ||
!room.currentState.getMember(client.credentials.userId)) {
return false;
}
let displayName = room.currentState.getMember(client.credentials.userId).name;
const displayName = room.currentState.getMember(client.credentials.userId).name;
// N.B. we can't use \b as it chokes on unicode. however \W seems to be okay
// as shorthand for [^0-9A-Za-z_].
let pat = new RegExp("(^|\\W)" + escapeRegExp(displayName) + "(\\W|$)", 'i');
const pat = new RegExp("(^|\\W)" + escapeRegExp(displayName) + "(\\W|$)", 'i');
return content.body.search(pat) > -1;
};
let eventFulfillsDeviceCondition = function(cond, ev) {
const eventFulfillsDeviceCondition = function(cond, ev) {
return false; // XXX: Allow a profile tag to be set for the web client instance
};
let eventFulfillsEventMatchCondition = function(cond, ev) {
let val = valueForDottedKey(cond.key, ev);
const eventFulfillsEventMatchCondition = function(cond, ev) {
const val = valueForDottedKey(cond.key, ev);
if (!val || typeof val != 'string') {
return false;
}
@@ -205,11 +205,11 @@ function PushProcessor(client) {
} else {
pat = '^' + globToRegexp(cond.pattern) + '$';
}
let regex = new RegExp(pat, 'i');
const regex = new RegExp(pat, 'i');
return !!val.match(regex);
};
let globToRegexp = function(glob) {
const globToRegexp = function(glob) {
// From
// https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132
// Because micromatch is about 130KB with dependencies,
@@ -218,19 +218,19 @@ function PushProcessor(client) {
pat = pat.replace(/\\\*/, '.*');
pat = pat.replace(/\?/, '.');
pat = pat.replace(/\\\[(!|)(.*)\\]/, function(match, p1, p2, offset, string) {
let first = p1 && '^' || '';
let second = p2.replace(/\\\-/, '-');
const first = p1 && '^' || '';
const second = p2.replace(/\\\-/, '-');
return '[' + first + second + ']';
});
return pat;
};
let valueForDottedKey = function(key, ev) {
let parts = key.split('.');
const valueForDottedKey = function(key, ev) {
const parts = key.split('.');
let val;
// special-case the first component to deal with encrypted messages
let firstPart = parts[0];
const firstPart = parts[0];
if (firstPart == 'content') {
val = ev.getContent();
parts.shift();
@@ -243,7 +243,7 @@ function PushProcessor(client) {
}
while (parts.length > 0) {
let thispart = parts.shift();
const thispart = parts.shift();
if (!val[thispart]) {
return null;
}
@@ -252,7 +252,7 @@ function PushProcessor(client) {
return val;
};
let matchingRuleForEventWithRulesets = function(ev, rulesets) {
const matchingRuleForEventWithRulesets = function(ev, rulesets) {
if (!rulesets || !rulesets.device) {
return null;
}
@@ -260,12 +260,12 @@ function PushProcessor(client) {
return null;
}
let allDevNames = Object.keys(rulesets.device);
const allDevNames = Object.keys(rulesets.device);
for (let i = 0; i < allDevNames.length; ++i) {
let devname = allDevNames[i];
let devrules = rulesets.device[devname];
const devname = allDevNames[i];
const devrules = rulesets.device[devname];
let matchingRule = matchingRuleFromKindSet(devrules, devname);
const matchingRule = matchingRuleFromKindSet(devrules, devname);
if (matchingRule) {
return matchingRule;
}
@@ -273,13 +273,13 @@ function PushProcessor(client) {
return matchingRuleFromKindSet(ev, rulesets.global);
};
let pushActionsForEventAndRulesets = function(ev, rulesets) {
let rule = matchingRuleForEventWithRulesets(ev, rulesets);
const pushActionsForEventAndRulesets = function(ev, rulesets) {
const rule = matchingRuleForEventWithRulesets(ev, rulesets);
if (!rule) {
return {};
}
let actionObj = PushProcessor.actionListToActionsObject(rule.actions);
const actionObj = PushProcessor.actionListToActionsObject(rule.actions);
// Some actions are implicit in some situations: we add those here
if (actionObj.tweaks.highlight === undefined) {
@@ -312,9 +312,9 @@ function PushProcessor(client) {
* @return {object} A object with key 'notify' (true or false) and an object of actions
*/
PushProcessor.actionListToActionsObject = function(actionlist) {
let actionobj = { 'notify': false, 'tweaks': {} };
const actionobj = { 'notify': false, 'tweaks': {} };
for (let i = 0; i < actionlist.length; ++i) {
let action = actionlist[i];
const action = actionlist[i];
if (action === 'notify') {
actionobj.notify = true;
} else if (typeof action === 'object') {

View File

@@ -27,7 +27,7 @@ limitations under the License.
// we schedule a callback at least this often, to check if we've missed out on
// some wall-clock time due to being suspended.
let TIMER_CHECK_PERIOD_MS = 1000;
const TIMER_CHECK_PERIOD_MS = 1000;
// counter, for making up ids to return from setTimeout
let _count = 0;
@@ -37,10 +37,10 @@ let _realCallbackKey;
// a sorted list of the callbacks to be run.
// each is an object with keys [runAt, func, params, key].
let _callbackList = [];
const _callbackList = [];
// var debuglog = console.log.bind(console);
let debuglog = function() {};
const debuglog = function() {};
/**
* Replace the function used by this module to get the current time.
@@ -72,12 +72,12 @@ module.exports.setTimeout = function(func, delayMs) {
delayMs = 0;
}
let params = Array.prototype.slice.call(arguments, 2);
let runAt = _now() + delayMs;
let key = _count++;
const params = Array.prototype.slice.call(arguments, 2);
const runAt = _now() + delayMs;
const key = _count++;
debuglog("setTimeout: scheduling cb", key, "at", runAt,
"(delay", delayMs, ")");
let data = {
const data = {
runAt: runAt,
func: func,
params: params,
@@ -85,7 +85,7 @@ module.exports.setTimeout = function(func, delayMs) {
};
// figure out where it goes in the list
let idx = binarySearch(
const idx = binarySearch(
_callbackList, function(el) {
return el.runAt - runAt;
}
@@ -110,7 +110,7 @@ module.exports.clearTimeout = function(key) {
// remove the element from the list
let i;
for (i = 0; i < _callbackList.length; i++) {
let cb = _callbackList[i];
const cb = _callbackList[i];
if (cb.key == key) {
_callbackList.splice(i, 1);
break;
@@ -129,15 +129,15 @@ function _scheduleRealCallback() {
global.clearTimeout(_realCallbackKey);
}
let first = _callbackList[0];
const first = _callbackList[0];
if (!first) {
debuglog("_scheduleRealCallback: no more callbacks, not rescheduling");
return;
}
let now = _now();
let delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);
const now = _now();
const delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);
debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs);
_realCallbackKey = global.setTimeout(_runCallbacks, delayMs);
@@ -145,13 +145,13 @@ function _scheduleRealCallback() {
function _runCallbacks() {
let cb;
let now = _now();
const now = _now();
debuglog("_runCallbacks: now:", now);
// get the list of things to call
let callbacksToRun = [];
const callbacksToRun = [];
while (true) {
let first = _callbackList[0];
const first = _callbackList[0];
if (!first || first.runAt > now) {
break;
}
@@ -188,8 +188,8 @@ function binarySearch(array, func) {
max = array.length;
while (min < max) {
let mid = (min + max) >> 1;
let res = func(array[mid]);
const mid = (min + max) >> 1;
const res = func(array[mid]);
if (res > 0) {
// the element at 'mid' is too big; set it as the new max.
max = mid;

View File

@@ -19,10 +19,10 @@ limitations under the License.
* of requests.
* @module scheduler
*/
let utils = require("./utils");
let q = require("q");
const utils = require("./utils");
const q = require("q");
let DEBUG = false; // set true to enable console logging.
const DEBUG = false; // set true to enable console logging.
/**
* Construct a scheduler for Matrix. Requires
@@ -60,7 +60,7 @@ function MatrixScheduler(retryAlgorithm, queueAlgorithm) {
* @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.
*/
MatrixScheduler.prototype.getQueueForEvent = function(event) {
let name = this.queueAlgorithm(event);
const name = this.queueAlgorithm(event);
if (!name || !this._queues[name]) {
return null;
}
@@ -76,7 +76,7 @@ MatrixScheduler.prototype.getQueueForEvent = function(event) {
* @return {boolean} True if this event was removed.
*/
MatrixScheduler.prototype.removeEventFromQueue = function(event) {
let name = this.queueAlgorithm(event);
const name = this.queueAlgorithm(event);
if (!name || !this._queues[name]) {
return false;
}
@@ -110,7 +110,7 @@ MatrixScheduler.prototype.setProcessFunction = function(fn) {
* resolved or rejected in due time, else null.
*/
MatrixScheduler.prototype.queueEvent = function(event) {
let queueName = this.queueAlgorithm(event);
const queueName = this.queueAlgorithm(event);
if (!queueName) {
return null;
}
@@ -118,7 +118,7 @@ MatrixScheduler.prototype.queueEvent = function(event) {
if (!this._queues[queueName]) {
this._queues[queueName] = [];
}
let defer = q.defer();
const defer = q.defer();
this._queues[queueName].push({
event: event,
defer: defer,
@@ -155,7 +155,7 @@ MatrixScheduler.RETRY_BACKOFF_RATELIMIT = function(event, attempts, err) {
}
if (err.name === "M_LIMIT_EXCEEDED") {
let waitTime = err.data.retry_after_ms;
const waitTime = err.data.retry_after_ms;
if (waitTime) {
return waitTime;
}
@@ -201,10 +201,10 @@ function _startProcessingQueues(scheduler) {
function _processQueue(scheduler, queueName) {
// get head of queue
let obj = _peekNextEvent(scheduler, queueName);
const obj = _peekNextEvent(scheduler, queueName);
if (!obj) {
// queue is empty. Mark as inactive and stop recursing.
let index = scheduler._activeQueues.indexOf(queueName);
const index = scheduler._activeQueues.indexOf(queueName);
if (index >= 0) {
scheduler._activeQueues.splice(index, 1);
}
@@ -227,7 +227,7 @@ function _processQueue(scheduler, queueName) {
}, function(err) {
obj.attempts += 1;
// ask the retry algorithm when/if we should try again
let waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);
const waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);
debuglog(
"retry(%s) err=%s event_id=%s waitTime=%s",
obj.attempts, err, obj.event.getId(), waitTimeMs
@@ -250,7 +250,7 @@ function _processQueue(scheduler, queueName) {
}
function _peekNextEvent(scheduler, queueName) {
let queue = scheduler._queues[queueName];
const queue = scheduler._queues[queueName];
if (!utils.isArray(queue)) {
return null;
}
@@ -258,7 +258,7 @@ function _peekNextEvent(scheduler, queueName) {
}
function _removeNextEvent(scheduler, queueName) {
let queue = scheduler._queues[queueName];
const queue = scheduler._queues[queueName];
if (!utils.isArray(queue)) {
return null;
}

View File

@@ -18,8 +18,8 @@ limitations under the License.
* This is an internal module. See {@link MatrixInMemoryStore} for the public class.
* @module store/memory
*/
let utils = require("../utils");
let User = require("../models/user");
const utils = require("../utils");
const User = require("../models/user");
/**
* Construct a new in-memory data store for the Matrix Client.
@@ -77,7 +77,7 @@ module.exports.MatrixInMemoryStore.prototype = {
// map up-to-date.
room.currentState.on("RoomState.members", this._onRoomMember.bind(this));
// add existing members
let self = this;
const self = this;
room.currentState.getMembers().forEach(function(m) {
self._onRoomMember(null, room.currentState, m);
});
@@ -97,7 +97,7 @@ module.exports.MatrixInMemoryStore.prototype = {
return;
}
let user = this.users[member.userId] || new User(member.userId);
const user = this.users[member.userId] || new User(member.userId);
if (member.name) {
user.setDisplayName(member.name);
if (member.events.member) {
@@ -260,7 +260,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* @param {Array<MatrixEvent>} events The events to store.
*/
storeAccountDataEvents: function(events) {
let self = this;
const self = this;
events.forEach(function(event) {
self.accountData[event.getType()] = event;
});

View File

@@ -19,10 +19,10 @@ limitations under the License.
* @module store/session/webstorage
*/
let utils = require("../../utils");
const utils = require("../../utils");
let DEBUG = false; // set true to enable console logging.
let E2E_PREFIX = "session.e2e.";
const DEBUG = false; // set true to enable console logging.
const E2E_PREFIX = "session.e2e.";
/**
* Construct a web storage session store, capable of storing account keys,
@@ -106,7 +106,7 @@ WebStorageSessionStore.prototype = {
* @param {string} session Base64 encoded end-to-end session.
*/
storeEndToEndSession: function(deviceKey, sessionId, session) {
let sessions = this.getEndToEndSessions(deviceKey) || {};
const sessions = this.getEndToEndSessions(deviceKey) || {};
sessions[sessionId] = session;
setJsonItem(
this.store, keyEndToEndSessions(deviceKey), sessions
@@ -150,12 +150,12 @@ WebStorageSessionStore.prototype = {
},
getEndToEndInboundGroupSession: function(senderKey, sessionId) {
let key = keyEndToEndInboundGroupSession(senderKey, sessionId);
const key = keyEndToEndInboundGroupSession(senderKey, sessionId);
return this.store.getItem(key);
},
storeEndToEndInboundGroupSession: function(senderKey, sessionId, pickledSession) {
let key = keyEndToEndInboundGroupSession(senderKey, sessionId);
const key = keyEndToEndInboundGroupSession(senderKey, sessionId);
return this.store.setItem(key, pickledSession);
},
@@ -178,8 +178,8 @@ WebStorageSessionStore.prototype = {
},
};
let KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account";
let KEY_END_TO_END_ANNOUNCED = E2E_PREFIX + "announced";
const KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account";
const KEY_END_TO_END_ANNOUNCED = E2E_PREFIX + "announced";
function keyEndToEndDevicesForUser(userId) {
return E2E_PREFIX + "devices/" + userId;

View File

@@ -23,20 +23,20 @@ limitations under the License.
* an alternative syncing API, we may want to have a proper syncing interface
* for HTTP and WS at some point.
*/
let q = require("q");
let User = require("./models/user");
let Room = require("./models/room");
let utils = require("./utils");
let Filter = require("./filter");
let EventTimeline = require("./models/event-timeline");
const q = require("q");
const User = require("./models/user");
const Room = require("./models/room");
const utils = require("./utils");
const Filter = require("./filter");
const EventTimeline = require("./models/event-timeline");
let DEBUG = true;
const DEBUG = true;
// /sync requests allow you to set a timeout= but the request may continue
// beyond that and wedge forever, so we need to track how long we are willing
// to keep open the connection. This constant is *ADDED* to the timeout= value
// to determine the max time we're willing to wait.
let BUFFER_PERIOD_MS = 80 * 1000;
const BUFFER_PERIOD_MS = 80 * 1000;
function getFilterName(userId, suffix) {
// scope this on the user ID because people may login on many accounts
@@ -88,8 +88,8 @@ function SyncApi(client, opts) {
* @return {Room}
*/
SyncApi.prototype.createRoom = function(roomId) {
let client = this.client;
let room = new Room(roomId, {
const client = this.client;
const room = new Room(roomId, {
pendingEventOrdering: this.opts.pendingEventOrdering,
timelineSupport: client.timelineSupport,
});
@@ -108,7 +108,7 @@ SyncApi.prototype.createRoom = function(roomId) {
* @private
*/
SyncApi.prototype._registerStateListeners = function(room) {
let client = this.client;
const client = this.client;
// we need to also re-emit room state and room member events, so hook it up
// to the client now. We need to add a listener for RoomState.members in
// order to hook them correctly. (TODO: find a better way?)
@@ -144,16 +144,16 @@ SyncApi.prototype._deregisterStateListeners = function(room) {
* @return {Promise} Resolved when they've been added to the store.
*/
SyncApi.prototype.syncLeftRooms = function() {
let client = this.client;
let self = this;
const client = this.client;
const self = this;
// grab a filter with limit=1 and include_leave=true
let filter = new Filter(this.client.credentials.userId);
const filter = new Filter(this.client.credentials.userId);
filter.setTimelineLimit(1);
filter.setIncludeLeaveRooms(true);
let localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;
let qps = {
const localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;
const qps = {
timeout: 0, // don't want to block since this is a single isolated req
};
@@ -169,9 +169,9 @@ SyncApi.prototype.syncLeftRooms = function() {
if (data.rooms && data.rooms.leave) {
leaveRooms = self._mapSyncResponseToRoomArray(data.rooms.leave);
}
let rooms = [];
const rooms = [];
leaveRooms.forEach(function(leaveObj) {
let room = leaveObj.room;
const room = leaveObj.room;
rooms.push(room);
if (!leaveObj.isBrandNewRoom) {
// the intention behind syncLeftRooms is to add in rooms which were
@@ -185,9 +185,9 @@ SyncApi.prototype.syncLeftRooms = function() {
return;
}
leaveObj.timeline = leaveObj.timeline || {};
let timelineEvents =
const timelineEvents =
self._mapSyncEventsFormat(leaveObj.timeline, room);
let stateEvents = self._mapSyncEventsFormat(leaveObj.state, room);
const stateEvents = self._mapSyncEventsFormat(leaveObj.state, room);
// set the back-pagination token. Do this *before* adding any
// events so that clients can start back-paginating.
@@ -212,8 +212,8 @@ SyncApi.prototype.syncLeftRooms = function() {
* store.
*/
SyncApi.prototype.peek = function(roomId) {
let self = this;
let client = this.client;
const self = this;
const client = this.client;
this._peekRoomId = roomId;
return this.client.roomInitialSync(roomId, 20).then(function(response) {
// make sure things are init'd
@@ -221,17 +221,17 @@ SyncApi.prototype.peek = function(roomId) {
response.messages.chunk = response.messages.chunk || [];
response.state = response.state || [];
let peekRoom = self.createRoom(roomId);
const peekRoom = self.createRoom(roomId);
// FIXME: Mostly duplicated from _processRoomEvents but not entirely
// because "state" in this API is at the BEGINNING of the chunk
let oldStateEvents = utils.map(
const oldStateEvents = utils.map(
utils.deepCopy(response.state), client.getEventMapper()
);
let stateEvents = utils.map(
const stateEvents = utils.map(
response.state, client.getEventMapper()
);
let messages = utils.map(
const messages = utils.map(
response.messages.chunk, client.getEventMapper()
);
@@ -301,7 +301,7 @@ SyncApi.prototype._peekPoll = function(roomId, token) {
return;
}
let self = this;
const self = this;
// FIXME: gut wrenching; hard-coded timeout values
this.client._http.authedRequest(undefined, "GET", "/events", {
room_id: roomId,
@@ -332,10 +332,10 @@ SyncApi.prototype._peekPoll = function(roomId, token) {
});
// strip out events which aren't for the given room_id (e.g presence)
let events = res.chunk.filter(function(e) {
const events = res.chunk.filter(function(e) {
return e.room_id === roomId;
}).map(self.client.getEventMapper());
let room = self.client.getRoom(roomId);
const room = self.client.getRoom(roomId);
room.addLiveEvents(events);
self._peekPoll(roomId, res.end);
}, function(err) {
@@ -362,8 +362,8 @@ SyncApi.prototype.sync = function() {
debuglog("SyncApi.sync: starting with sync token " +
this.client.store.getSyncToken());
let client = this.client;
let self = this;
const client = this.client;
const self = this;
this._running = true;
@@ -465,8 +465,8 @@ SyncApi.prototype.retryImmediately = function() {
* @param {boolean} syncOptions.hasSyncedBefore
*/
SyncApi.prototype._sync = function(syncOptions) {
let client = this.client;
let self = this;
const client = this.client;
const self = this;
if (!this._running) {
debuglog("Sync no longer running: exiting.");
@@ -483,9 +483,9 @@ SyncApi.prototype._sync = function(syncOptions) {
filterId = this._getGuestFilter();
}
let syncToken = client.store.getSyncToken();
const syncToken = client.store.getSyncToken();
let qps = {
const qps = {
filter: filterId,
timeout: this.opts.pollTimeout,
};
@@ -508,7 +508,7 @@ SyncApi.prototype._sync = function(syncOptions) {
}
// normal timeout= plus buffer time
let clientSideTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;
const clientSideTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;
this._currentSyncRequest = client._http.authedRequest(
undefined, "GET", "/sync", qps, undefined, clientSideTimeoutMs
@@ -576,8 +576,8 @@ SyncApi.prototype._sync = function(syncOptions) {
* @param {Object} data The response from /sync
*/
SyncApi.prototype._processSyncResponse = function(syncToken, data) {
let client = this.client;
let self = this;
const client = this.client;
const self = this;
// data looks like:
// {
@@ -635,7 +635,7 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
// handle non-room account_data
if (data.account_data && utils.isArray(data.account_data.events)) {
let events = data.account_data.events.map(client.getEventMapper());
const events = data.account_data.events.map(client.getEventMapper());
client.store.storeAccountDataEvents(events);
events.forEach(
function(accountDataEvent) {
@@ -654,7 +654,7 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
.map(client.getEventMapper())
.forEach(
function(toDeviceEvent) {
let content = toDeviceEvent.getContent();
const content = toDeviceEvent.getContent();
if (
toDeviceEvent.getType() == "m.room.message" &&
content.msgtype == "m.bad.encrypted"
@@ -693,8 +693,8 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
// Handle invites
inviteRooms.forEach(function(inviteObj) {
let room = inviteObj.room;
let stateEvents =
const room = inviteObj.room;
const stateEvents =
self._mapSyncEventsFormat(inviteObj.invite_state, room);
self._processRoomEvents(room, stateEvents);
if (inviteObj.isBrandNewRoom) {
@@ -709,11 +709,11 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
// Handle joins
joinRooms.forEach(function(joinObj) {
let room = joinObj.room;
let stateEvents = self._mapSyncEventsFormat(joinObj.state, room);
let timelineEvents = self._mapSyncEventsFormat(joinObj.timeline, room);
let ephemeralEvents = self._mapSyncEventsFormat(joinObj.ephemeral);
let accountDataEvents = self._mapSyncEventsFormat(joinObj.account_data);
const room = joinObj.room;
const stateEvents = self._mapSyncEventsFormat(joinObj.state, room);
const timelineEvents = self._mapSyncEventsFormat(joinObj.timeline, room);
const ephemeralEvents = self._mapSyncEventsFormat(joinObj.ephemeral);
const accountDataEvents = self._mapSyncEventsFormat(joinObj.account_data);
// we do this first so it's correct when any of the events fire
if (joinObj.unread_notifications) {
@@ -748,7 +748,7 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
// will stop us linking the empty timeline into the chain).
//
for (let i = timelineEvents.length - 1; i >= 0; i--) {
let eventId = timelineEvents[i].getId();
const eventId = timelineEvents[i].getId();
if (room.getTimelineForEvent(eventId)) {
debuglog("Already have event " + eventId + " in limited " +
"sync - not resetting");
@@ -818,12 +818,12 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
// Handle leaves (e.g. kicked rooms)
leaveRooms.forEach(function(leaveObj) {
let room = leaveObj.room;
let stateEvents =
const room = leaveObj.room;
const stateEvents =
self._mapSyncEventsFormat(leaveObj.state, room);
let timelineEvents =
const timelineEvents =
self._mapSyncEventsFormat(leaveObj.timeline, room);
let accountDataEvents =
const accountDataEvents =
self._mapSyncEventsFormat(leaveObj.account_data);
self._processRoomEvents(room, stateEvents, timelineEvents);
@@ -876,7 +876,7 @@ SyncApi.prototype._startKeepAlives = function(delay) {
if (this._keepAliveTimer !== null) {
clearTimeout(this._keepAliveTimer);
}
let self = this;
const self = this;
if (delay > 0) {
self._keepAliveTimer = setTimeout(
self._pokeKeepAlive.bind(self),
@@ -895,7 +895,7 @@ SyncApi.prototype._startKeepAlives = function(delay) {
*
*/
SyncApi.prototype._pokeKeepAlive = function() {
let self = this;
const self = this;
function success() {
clearTimeout(self._keepAliveTimer);
if (self._connectionReturnedDefer) {
@@ -947,10 +947,10 @@ SyncApi.prototype._mapSyncResponseToRoomArray = function(obj) {
// Maps { roomid: {stuff}, roomid: {stuff} }
// to
// [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]
let client = this.client;
let self = this;
const client = this.client;
const self = this;
return utils.keys(obj).map(function(roomId) {
let arrObj = obj[roomId];
const arrObj = obj[roomId];
let room = client.store.getRoom(roomId);
let isBrandNewRoom = false;
if (!room) {
@@ -972,7 +972,7 @@ SyncApi.prototype._mapSyncEventsFormat = function(obj, room) {
if (!obj || !utils.isArray(obj.events)) {
return [];
}
let mapper = this.client.getEventMapper();
const mapper = this.client.getEventMapper();
return obj.events.map(function(e) {
if (room) {
e.room_id = room.roomId;
@@ -988,7 +988,7 @@ SyncApi.prototype._resolveInvites = function(room) {
if (!room || !this.opts.resolveInvitesToProfiles) {
return;
}
let client = this.client;
const client = this.client;
// For each invited room member we want to give them a displayname/avatar url
// if they have one (the m.room.member invites don't contain this).
room.getMembersWithMembership("invite").forEach(function(member) {
@@ -997,7 +997,7 @@ SyncApi.prototype._resolveInvites = function(room) {
}
member._requestedProfileInfo = true;
// try to get a cached copy first.
let user = client.getUser(member.userId);
const user = client.getUser(member.userId);
let promise;
if (user) {
promise = q({
@@ -1011,7 +1011,7 @@ SyncApi.prototype._resolveInvites = function(room) {
// slightly naughty by doctoring the invite event but this means all
// the code paths remain the same between invite/join display name stuff
// which is a worthy trade-off for some minor pollution.
let inviteEvent = member.events.member;
const inviteEvent = member.events.member;
if (inviteEvent.getContent().membership !== "invite") {
// between resolving and now they have since joined, so don't clobber
return;
@@ -1036,19 +1036,19 @@ SyncApi.prototype._resolveInvites = function(room) {
SyncApi.prototype._processRoomEvents = function(room, stateEventList,
timelineEventList) {
timelineEventList = timelineEventList || [];
let client = this.client;
const client = this.client;
// "old" and "current" state are the same initially; they
// start diverging if the user paginates.
// We must deep copy otherwise membership changes in old state
// will leak through to current state!
let oldStateEvents = utils.map(
const oldStateEvents = utils.map(
utils.deepCopy(
stateEventList.map(function(mxEvent) {
return mxEvent.event;
})
), client.getEventMapper()
);
let stateEvents = stateEventList;
const stateEvents = stateEventList;
// set the state of the room to as it was before the timeline executes
//
@@ -1068,7 +1068,7 @@ SyncApi.prototype._processRoomEvents = function(room, stateEventList,
// gather our notifications into this._notifEvents
if (client.getNotifTimelineSet()) {
for (let i = 0; i < timelineEventList.length; i++) {
let pushActions = client.getPushActionsForEvent(timelineEventList[i]);
const pushActions = client.getPushActionsForEvent(timelineEventList[i]);
if (pushActions && pushActions.notify &&
pushActions.tweaks && pushActions.tweaks.highlight) {
this._notifEvents.push(timelineEventList[i]);
@@ -1085,7 +1085,7 @@ SyncApi.prototype._processRoomEvents = function(room, stateEventList,
* @return {string}
*/
SyncApi.prototype._getGuestFilter = function() {
let guestRooms = this.client._guestRooms; // FIXME: horrible gut-wrenching
const guestRooms = this.client._guestRooms; // FIXME: horrible gut-wrenching
if (!guestRooms) {
return "{}";
}
@@ -1106,7 +1106,7 @@ SyncApi.prototype._getGuestFilter = function() {
* @param {Object} data Object of additional data to emit in the event
*/
SyncApi.prototype._updateSyncState = function(newState, data) {
let old = this._syncState;
const old = this._syncState;
this._syncState = newState;
this.client.emit("sync", this._syncState, old, data);
};
@@ -1123,7 +1123,7 @@ SyncApi.prototype._onOnline = function() {
};
function createNewUser(client, userId) {
let user = new User(userId);
const user = new User(userId);
reEmit(client, user, [
"User.avatarUrl", "User.displayName", "User.presence",
"User.currentlyActive", "User.lastPresenceTs",
@@ -1140,7 +1140,7 @@ function reEmit(reEmitEntity, emittableEntity, eventNames) {
// Transformation Example:
// listener on "foo" => function(a,b) { ... }
// Re-emit on "thing" => thing.emit("foo", a, b)
let newArgs = [eventName];
const newArgs = [eventName];
for (let i = 0; i < arguments.length; i++) {
newArgs.push(arguments[i]);
}

View File

@@ -17,25 +17,25 @@ limitations under the License.
/** @module timeline-window */
let q = require("q");
let EventTimeline = require("./models/event-timeline");
const q = require("q");
const EventTimeline = require("./models/event-timeline");
/**
* @private
*/
let DEBUG = false;
const DEBUG = false;
/**
* @private
*/
let debuglog = DEBUG ? console.log.bind(console) : function() {};
const debuglog = DEBUG ? console.log.bind(console) : function() {};
/**
* the number of times we ask the server for more events before giving up
*
* @private
*/
let DEFAULT_PAGINATE_LOOP_LIMIT = 5;
const DEFAULT_PAGINATE_LOOP_LIMIT = 5;
/**
* Construct a TimelineWindow.
@@ -92,15 +92,15 @@ function TimelineWindow(client, timelineSet, opts) {
* @return {module:client.Promise}
*/
TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) {
let self = this;
const self = this;
initialWindowSize = initialWindowSize || 20;
// given an EventTimeline, and an event index within it, initialise our
// fields so that the event in question is in the middle of the window.
let initFields = function(timeline, eventIndex) {
let endIndex = Math.min(timeline.getEvents().length,
const initFields = function(timeline, eventIndex) {
const endIndex = Math.min(timeline.getEvents().length,
eventIndex + Math.ceil(initialWindowSize / 2));
let startIndex = Math.max(0, endIndex - initialWindowSize);
const startIndex = Math.max(0, endIndex - initialWindowSize);
self._start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());
self._end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());
self._eventCount = endIndex - startIndex;
@@ -126,7 +126,7 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) {
});
} else {
// start with the most recent events
let tl = this._timelineSet.getLiveTimeline();
const tl = this._timelineSet.getLiveTimeline();
initFields(tl, tl.getEvents().length);
return q();
}
@@ -228,7 +228,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
}
// try moving the cap
let count = (direction == EventTimeline.BACKWARDS) ?
const count = (direction == EventTimeline.BACKWARDS) ?
tl.retreat(size) : tl.advance(size);
if (count) {
@@ -236,7 +236,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
debuglog("TimelineWindow: increased cap by " + count +
" (now " + this._eventCount + ")");
// remove some events from the other end, if necessary
let excess = this._eventCount - this._windowLimit;
const excess = this._eventCount - this._windowLimit;
if (excess > 0) {
this.unpaginate(excess, direction != EventTimeline.BACKWARDS);
}
@@ -250,16 +250,16 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
}
// try making a pagination request
let token = tl.timeline.getPaginationToken(direction);
const token = tl.timeline.getPaginationToken(direction);
if (!token) {
debuglog("TimelineWindow: no token");
return q(false);
}
debuglog("TimelineWindow: starting request");
let self = this;
const self = this;
let prom = this._client.paginateEventTimeline(tl.timeline, {
const prom = this._client.paginateEventTimeline(tl.timeline, {
backwards: direction == EventTimeline.BACKWARDS,
limit: size,
}).finally(function() {
@@ -298,7 +298,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
* of the timeline.
*/
TimelineWindow.prototype.unpaginate = function(delta, startOfTimeline) {
let tl = startOfTimeline ? this._start : this._end;
const tl = startOfTimeline ? this._start : this._end;
// sanity-check the delta
if (delta > this._eventCount || delta < 0) {
@@ -307,7 +307,7 @@ TimelineWindow.prototype.unpaginate = function(delta, startOfTimeline) {
}
while (delta > 0) {
let count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta);
const count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta);
if (count <= 0) {
// sadness. This shouldn't be possible.
throw new Error(
@@ -334,13 +334,13 @@ TimelineWindow.prototype.getEvents = function() {
return [];
}
let result = [];
const result = [];
// iterate through each timeline between this._start and this._end
// (inclusive).
let timeline = this._start.timeline;
while (true) {
let events = timeline.getEvents();
const events = timeline.getEvents();
// For the first timeline in the chain, we want to start at
// this._start.index. For the last timeline in the chain, we want to
@@ -447,7 +447,7 @@ TimelineIndex.prototype.advance = function(delta) {
// the index is already at the start/end of the current timeline.
//
// next see if there is a neighbouring timeline to switch to.
let neighbour = this.timeline.getNeighbouringTimeline(
const neighbour = this.timeline.getNeighbouringTimeline(
delta < 0 ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS);
if (neighbour) {
this.timeline = neighbour;

View File

@@ -27,7 +27,7 @@ limitations under the License.
*/
module.exports.encodeParams = function(params) {
let qs = "";
for (let key in params) {
for (const key in params) {
if (!params.hasOwnProperty(key)) {
continue;
}
@@ -46,7 +46,7 @@ module.exports.encodeParams = function(params) {
* @return {string} The result of replacing all template variables e.g. '/foo/baz'.
*/
module.exports.encodeUri = function(pathTemplate, variables) {
for (let key in variables) {
for (const key in variables) {
if (!variables.hasOwnProperty(key)) {
continue;
}
@@ -65,7 +65,7 @@ module.exports.encodeUri = function(pathTemplate, variables) {
* @return {Array} A new array with the results of the function.
*/
module.exports.map = function(array, fn) {
let results = new Array(array.length);
const results = new Array(array.length);
for (let i = 0; i < array.length; i++) {
results[i] = fn(array[i]);
}
@@ -81,7 +81,7 @@ module.exports.map = function(array, fn) {
* @return {Array} A new array with the results of the function.
*/
module.exports.filter = function(array, fn) {
let results = [];
const results = [];
for (let i = 0; i < array.length; i++) {
if (fn(array[i], i, array)) {
results.push(array[i]);
@@ -96,8 +96,8 @@ module.exports.filter = function(array, fn) {
* @return {string[]} The keys of the object.
*/
module.exports.keys = function(obj) {
let keys = [];
for (let key in obj) {
const keys = [];
for (const key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
@@ -112,8 +112,8 @@ module.exports.keys = function(obj) {
* @return {Array<*>} The values of the object.
*/
module.exports.values = function(obj) {
let values = [];
for (let key in obj) {
const values = [];
for (const key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
@@ -235,7 +235,7 @@ module.exports.checkObjectHasKeys = function(obj, keys) {
* @throws If there are extra keys.
*/
module.exports.checkObjectHasNoAdditionalKeys = function(obj, allowedKeys) {
for (let key in obj) {
for (const key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
@@ -263,7 +263,7 @@ module.exports.deepCopy = function(obj) {
*
* @return {boolean} true if the two objects are equal
*/
let deepCompare = module.exports.deepCompare = function(x, y) {
const deepCompare = module.exports.deepCompare = function(x, y) {
// Inspired by
// http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249
@@ -355,10 +355,10 @@ let deepCompare = module.exports.deepCompare = function(x, y) {
* @return {Object} target
*/
module.exports.extend = function() {
let target = arguments[0] || {};
const target = arguments[0] || {};
for (let i = 1; i < arguments.length; i++) {
let source = arguments[i];
for (let propName in source) { // eslint-disable-line guard-for-in
const source = arguments[i];
for (const propName in source) { // eslint-disable-line guard-for-in
target[propName] = source[propName];
}
}
@@ -379,17 +379,17 @@ module.exports.runPolyfills = function() {
throw new TypeError();
}
let t = Object(this);
let len = t.length >>> 0;
const t = Object(this);
const len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
let res = [];
let thisArg = arguments.length >= 2 ? arguments[1] : void 0;
const res = [];
const thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (let i = 0; i < len; i++) {
if (i in t) {
let val = t[i];
const val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
@@ -422,12 +422,12 @@ module.exports.runPolyfills = function() {
// 1. Let O be the result of calling ToObject passing the |this|
// value as the argument.
let O = Object(this);
const O = Object(this);
// 2. Let lenValue be the result of calling the Get internal
// method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
let len = O.length >>> 0;
const len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
@@ -512,12 +512,12 @@ module.exports.runPolyfills = function() {
// 1. Let O be the result of calling ToObject passing the |this| value as the
// argument.
let O = Object(this);
const O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the
// argument "length".
// 3. Let len be ToUint32(lenValue).
let len = O.length >>> 0;
const len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
@@ -582,7 +582,7 @@ module.exports.inherits = function(ctor, superCtor) {
function Temp() {}
// make a safe reference to Object.prototype.hasOwnProperty
let hasOwn = Object.prototype.hasOwnProperty;
const hasOwn = Object.prototype.hasOwnProperty;
return function(O) {
// 1. If Type(O) is not Object or Null throw a TypeError exception.
@@ -595,7 +595,7 @@ module.exports.inherits = function(ctor, superCtor) {
// constructor with that name
// 3. Set the [[Prototype]] internal property of obj to O.
Temp.prototype = O;
let obj = new Temp();
const obj = new Temp();
Temp.prototype = null; // Let's not keep a stray reference to O...
// 4. If the argument Properties is present and not undefined, add
@@ -604,8 +604,8 @@ module.exports.inherits = function(ctor, superCtor) {
// Properties.
if (arguments.length > 1) {
// Object.defineProperties does ToObject on its first argument.
let Properties = Object(arguments[1]);
for (let prop in Properties) {
const Properties = Object(arguments[1]);
for (const prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}

View File

@@ -18,9 +18,9 @@ limitations under the License.
* This is an internal module. See {@link createNewMatrixCall} for the public API.
* @module webrtc/call
*/
let utils = require("../utils");
let EventEmitter = require("events").EventEmitter;
let DEBUG = true; // set true to enable console logging.
const utils = require("../utils");
const EventEmitter = require("events").EventEmitter;
const DEBUG = true; // set true to enable console logging.
// events: hangup, error(err), replaced(call), state(state, oldState)
@@ -125,17 +125,17 @@ MatrixCall.prototype.placeScreenSharingCall =
function(remoteVideoElement, localVideoElement) {
debuglog("placeScreenSharingCall");
checkForErrorListener(this);
let screenConstraints = _getChromeScreenSharingConstraints(this);
const screenConstraints = _getChromeScreenSharingConstraints(this);
if (!screenConstraints) {
return;
}
this.localVideoElement = localVideoElement;
this.remoteVideoElement = remoteVideoElement;
let self = this;
const self = this;
this.webRtc.getUserMedia(screenConstraints, function(stream) {
self.screenSharingStream = stream;
debuglog("Got screen stream, requesting audio stream...");
let audioConstraints = _getUserMediaVideoContraints('voice');
const audioConstraints = _getUserMediaVideoContraints('voice');
_placeCallWithConstraints(self, audioConstraints);
}, function(err) {
self.emit("error",
@@ -266,9 +266,9 @@ MatrixCall.prototype.setLocalVideoElement = function(element) {
this.URL.createObjectURL(this.localAVStream),
"localVideo");
element.muted = true;
let self = this;
const self = this;
setTimeout(function() {
let vel = self.getLocalVideoElement();
const vel = self.getLocalVideoElement();
if (vel.play) {
self.playElement(vel, "localVideo");
}
@@ -306,7 +306,7 @@ MatrixCall.prototype.setRemoteAudioElement = function(element) {
MatrixCall.prototype._initWithInvite = function(event) {
this.msg = event.getContent();
this.peerConn = _createPeerConnection(this);
let self = this;
const self = this;
if (this.peerConn) {
this.peerConn.setRemoteDescription(
new this.webRtc.RtcSessionDescription(this.msg.offer),
@@ -364,7 +364,7 @@ MatrixCall.prototype._initWithHangup = function(event) {
*/
MatrixCall.prototype.answer = function() {
debuglog("Answering call %s of type %s", this.callId, this.type);
let self = this;
const self = this;
if (!this.localAVStream && !this.waitForLocalAVStream) {
this.webRtc.getUserMedia(
@@ -416,7 +416,7 @@ MatrixCall.prototype._replacedBy = function(newCall) {
MatrixCall.prototype.hangup = function(reason, suppressEvent) {
debuglog("Ending call " + this.callId);
terminate(this, "local", reason, !suppressEvent);
let content = {
const content = {
version: 0,
call_id: this.callId,
reason: reason,
@@ -492,8 +492,8 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) {
return;
}
debuglog("_gotUserMediaForInvite -> " + this.type);
let self = this;
let videoEl = this.getLocalVideoElement();
const self = this;
const videoEl = this.getLocalVideoElement();
if (videoEl && this.type == 'video') {
videoEl.autoplay = true;
@@ -509,7 +509,7 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) {
}
videoEl.muted = true;
setTimeout(function() {
let vel = self.getLocalVideoElement();
const vel = self.getLocalVideoElement();
if (vel.play) {
self.playElement(vel, "localVideo");
}
@@ -539,11 +539,11 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) {
* @param {Object} stream
*/
MatrixCall.prototype._gotUserMediaForAnswer = function(stream) {
let self = this;
const self = this;
if (self.state == 'ended') {
return;
}
let localVidEl = self.getLocalVideoElement();
const localVidEl = self.getLocalVideoElement();
if (localVidEl && self.type == 'video') {
localVidEl.autoplay = true;
@@ -552,7 +552,7 @@ MatrixCall.prototype._gotUserMediaForAnswer = function(stream) {
"localVideo");
localVidEl.muted = true;
setTimeout(function() {
let vel = self.getLocalVideoElement();
const vel = self.getLocalVideoElement();
if (vel.play) {
self.playElement(vel, "localVideo");
}
@@ -563,7 +563,7 @@ MatrixCall.prototype._gotUserMediaForAnswer = function(stream) {
setTracksEnabled(stream.getAudioTracks(), true);
self.peerConn.addStream(stream);
let constraints = {
const constraints = {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': self.type == 'video',
@@ -572,7 +572,7 @@ MatrixCall.prototype._gotUserMediaForAnswer = function(stream) {
self.peerConn.createAnswer(function(description) {
debuglog("Created answer: " + description);
self.peerConn.setLocalDescription(description, function() {
let content = {
const content = {
version: 0,
call_id: self.callId,
answer: {
@@ -604,7 +604,7 @@ MatrixCall.prototype._gotLocalIceCandidate = function(event) {
);
// As with the offer, note we need to make a copy of this object, not
// pass the original: that broke in Chrome ~m43.
let c = {
const c = {
candidate: event.candidate.candidate,
sdpMid: event.candidate.sdpMid,
sdpMLineIndex: event.candidate.sdpMLineIndex,
@@ -641,7 +641,7 @@ MatrixCall.prototype._receivedAnswer = function(msg) {
return;
}
let self = this;
const self = this;
this.peerConn.setRemoteDescription(
new this.webRtc.RtcSessionDescription(msg.answer),
hookCallback(self, self._onSetRemoteDescriptionSuccess),
@@ -656,7 +656,7 @@ MatrixCall.prototype._receivedAnswer = function(msg) {
* @param {Object} description
*/
MatrixCall.prototype._gotLocalOffer = function(description) {
let self = this;
const self = this;
debuglog("Created offer: " + description);
if (self.state == 'ended') {
@@ -666,7 +666,7 @@ MatrixCall.prototype._gotLocalOffer = function(description) {
}
self.peerConn.setLocalDescription(description, function() {
let content = {
const content = {
version: 0,
call_id: self.callId,
// OpenWebRTC appears to add extra stuff (like the DTLS fingerprint)
@@ -784,7 +784,7 @@ MatrixCall.prototype._onSetRemoteDescriptionError = function(e) {
MatrixCall.prototype._onAddStream = function(event) {
debuglog("Stream id " + event.stream.id + " added");
let s = event.stream;
const s = event.stream;
if (s.getVideoTracks().length > 0) {
this.type = 'video';
@@ -795,7 +795,7 @@ MatrixCall.prototype._onAddStream = function(event) {
this.remoteAStream = s;
}
let self = this;
const self = this;
forAllTracksOnStream(s, function(t) {
debuglog("Track id " + t.id + " added");
// not currently implemented in chrome
@@ -874,13 +874,13 @@ MatrixCall.prototype._onAnsweredElsewhere = function(msg) {
terminate(this, "remote", "answered_elsewhere", true);
};
let setTracksEnabled = function(tracks, enabled) {
const setTracksEnabled = function(tracks, enabled) {
for (let i = 0; i < tracks.length; i++) {
tracks[i].enabled = enabled;
}
};
let isTracksEnabled = function(tracks) {
const isTracksEnabled = function(tracks) {
for (let i = 0; i < tracks.length; i++) {
if (tracks[i].enabled) {
return true; // at least one track is enabled
@@ -889,8 +889,8 @@ let isTracksEnabled = function(tracks) {
return false;
};
let setState = function(self, state) {
let oldState = self.state;
const setState = function(self, state) {
const oldState = self.state;
self.state = state;
self.emit("state", state, oldState);
};
@@ -902,11 +902,11 @@ let setState = function(self, state) {
* @param {Object} content
* @return {Promise}
*/
let sendEvent = function(self, eventType, content) {
const sendEvent = function(self, eventType, content) {
return self.client.sendEvent(self.roomId, eventType, content);
};
let sendCandidate = function(self, content) {
const sendCandidate = function(self, content) {
// Sends candidates with are sent in a special way because we try to amalgamate
// them into one message
self.candidateSendQueue.push(content);
@@ -917,7 +917,7 @@ let sendCandidate = function(self, content) {
}
};
let terminate = function(self, hangupParty, hangupReason, shouldEmit) {
const terminate = function(self, hangupParty, hangupReason, shouldEmit) {
if (self.getRemoteVideoElement()) {
if (self.getRemoteVideoElement().pause) {
self.pauseElement(self.getRemoteVideoElement(), "remoteVideo");
@@ -948,7 +948,7 @@ let terminate = function(self, hangupParty, hangupReason, shouldEmit) {
}
};
let stopAllMedia = function(self) {
const stopAllMedia = function(self) {
debuglog("stopAllMedia (stream=%s)", self.localAVStream);
if (self.localAVStream) {
forAllTracksOnStream(self.localAVStream, function(t) {
@@ -988,15 +988,15 @@ let stopAllMedia = function(self) {
}
};
let _tryPlayRemoteStream = function(self) {
const _tryPlayRemoteStream = function(self) {
if (self.getRemoteVideoElement() && self.remoteAVStream) {
let player = self.getRemoteVideoElement();
const player = self.getRemoteVideoElement();
player.autoplay = true;
self.assignElement(player,
self.URL.createObjectURL(self.remoteAVStream),
"remoteVideo");
setTimeout(function() {
let vel = self.getRemoteVideoElement();
const vel = self.getRemoteVideoElement();
if (vel.play) {
self.playElement(vel, "remoteVideo");
}
@@ -1008,15 +1008,15 @@ let _tryPlayRemoteStream = function(self) {
}
};
let _tryPlayRemoteAudioStream = function(self) {
const _tryPlayRemoteAudioStream = function(self) {
if (self.getRemoteAudioElement() && self.remoteAStream) {
let player = self.getRemoteAudioElement();
const player = self.getRemoteAudioElement();
player.autoplay = true;
self.assignElement(player,
self.URL.createObjectURL(self.remoteAStream),
"remoteAudio");
setTimeout(function() {
let ael = self.getRemoteAudioElement();
const ael = self.getRemoteAudioElement();
if (ael.play) {
self.playElement(ael, "remoteAudio");
}
@@ -1028,7 +1028,7 @@ let _tryPlayRemoteAudioStream = function(self) {
}
};
let checkForErrorListener = function(self) {
const checkForErrorListener = function(self) {
if (self.listeners("error").length === 0) {
throw new Error(
"You MUST attach an error listener using call.on('error', function() {})"
@@ -1036,27 +1036,27 @@ let checkForErrorListener = function(self) {
}
};
let callError = function(code, msg) {
let e = new Error(msg);
const callError = function(code, msg) {
const e = new Error(msg);
e.code = code;
return e;
};
let debuglog = function() {
const debuglog = function() {
if (DEBUG) {
console.log(...arguments);
}
};
let _sendCandidateQueue = function(self) {
const _sendCandidateQueue = function(self) {
if (self.candidateSendQueue.length === 0) {
return;
}
let cands = self.candidateSendQueue;
const cands = self.candidateSendQueue;
self.candidateSendQueue = [];
++self.candidateSendTries;
let content = {
const content = {
version: 0,
call_id: self.callId,
candidates: cands,
@@ -1079,7 +1079,7 @@ let _sendCandidateQueue = function(self) {
return;
}
let delayMs = 500 * Math.pow(2, self.candidateSendTries);
const delayMs = 500 * Math.pow(2, self.candidateSendTries);
++self.candidateSendTries;
debuglog("Failed to send candidates. Retrying in " + delayMs + "ms");
setTimeout(function() {
@@ -1088,7 +1088,7 @@ let _sendCandidateQueue = function(self) {
});
};
let _placeCallWithConstraints = function(self, constraints) {
const _placeCallWithConstraints = function(self, constraints) {
self.client.callList[self.callId] = self;
self.webRtc.getUserMedia(
constraints,
@@ -1100,7 +1100,7 @@ let _placeCallWithConstraints = function(self, constraints) {
self.config = constraints;
};
let _createPeerConnection = function(self) {
const _createPeerConnection = function(self) {
let servers = self.turnServers;
if (self.webRtc.vendor === "mozilla") {
// modify turnServers struct to match what mozilla expects.
@@ -1116,7 +1116,7 @@ let _createPeerConnection = function(self) {
}
}
let pc = new self.webRtc.RtcPeerConnection({
const pc = new self.webRtc.RtcPeerConnection({
iceServers: servers,
});
pc.oniceconnectionstatechange = hookCallback(self, self._onIceConnectionStateChanged);
@@ -1126,8 +1126,8 @@ let _createPeerConnection = function(self) {
return pc;
};
let _getChromeScreenSharingConstraints = function(call) {
let screen = global.screen;
const _getChromeScreenSharingConstraints = function(call) {
const screen = global.screen;
if (!screen) {
call.emit("error", callError(
MatrixCall.ERR_NO_USER_MEDIA,
@@ -1150,7 +1150,7 @@ let _getChromeScreenSharingConstraints = function(call) {
};
};
let _getUserMediaVideoContraints = function(callType) {
const _getUserMediaVideoContraints = function(callType) {
switch (callType) {
case 'voice':
return ({audio: true, video: false});
@@ -1166,27 +1166,27 @@ let _getUserMediaVideoContraints = function(callType) {
}
};
let hookCallback = function(call, fn) {
const hookCallback = function(call, fn) {
return function() {
return fn.apply(call, arguments);
};
};
let forAllVideoTracksOnStream = function(s, f) {
let tracks = s.getVideoTracks();
const forAllVideoTracksOnStream = function(s, f) {
const tracks = s.getVideoTracks();
for (let i = 0; i < tracks.length; i++) {
f(tracks[i]);
}
};
let forAllAudioTracksOnStream = function(s, f) {
let tracks = s.getAudioTracks();
const forAllAudioTracksOnStream = function(s, f) {
const tracks = s.getAudioTracks();
for (let i = 0; i < tracks.length; i++) {
f(tracks[i]);
}
};
let forAllTracksOnStream = function(s, f) {
const forAllTracksOnStream = function(s, f) {
forAllVideoTracksOnStream(s, f);
forAllAudioTracksOnStream(s, f);
};
@@ -1202,14 +1202,14 @@ module.exports.MatrixCall = MatrixCall;
* @return {MatrixCall} the call or null if the browser doesn't support calling.
*/
module.exports.createNewMatrixCall = function(client, roomId) {
let w = global.window;
let doc = global.document;
const w = global.window;
const doc = global.document;
if (!w || !doc) {
return null;
}
let webRtc = {};
const webRtc = {};
webRtc.isOpenWebRTC = function() {
let scripts = doc.getElementById("script");
const scripts = doc.getElementById("script");
if (!scripts || !scripts.length) {
return false;
}
@@ -1220,7 +1220,7 @@ module.exports.createNewMatrixCall = function(client, roomId) {
}
return false;
};
let getUserMedia = (
const getUserMedia = (
w.navigator.getUserMedia || w.navigator.webkitGetUserMedia ||
w.navigator.mozGetUserMedia
);
@@ -1251,7 +1251,7 @@ module.exports.createNewMatrixCall = function(client, roomId) {
!webRtc.RtcPeerConnection || !webRtc.getUserMedia) {
return null; // WebRTC is not supported.
}
let opts = {
const opts = {
webRtc: webRtc,
client: client,
URL: w.URL,