diff --git a/spec/MockStorageApi.js b/spec/MockStorageApi.js index 9a1f738bf..b1ac4e2fb 100644 --- a/spec/MockStorageApi.js +++ b/spec/MockStorageApi.js @@ -40,14 +40,16 @@ MockStorageApi.prototype = { return this.keys[index]; }, _recalc: function() { - var keys = []; - for (var k in this.data) { - if (!this.data.hasOwnProperty(k)) { continue; } + let keys = []; + for (let k in this.data) { + if (!this.data.hasOwnProperty(k)) { + continue; +} keys.push(k); } this.keys = keys; this.length = keys.length; - } + }, }; /** */ diff --git a/spec/integ/matrix-client-crypto.spec.js b/spec/integ/matrix-client-crypto.spec.js index 051df7d0c..fcdf29cf3 100644 --- a/spec/integ/matrix-client-crypto.spec.js +++ b/spec/integ/matrix-client-crypto.spec.js @@ -1,30 +1,30 @@ "use strict"; -var sdk = require("../.."); -var q = require("q"); -var HttpBackend = require("../mock-request"); -var utils = require("../../lib/utils"); -var test_utils = require("../test-utils"); +let sdk = require("../.."); +let q = require("q"); +let HttpBackend = require("../mock-request"); +let utils = require("../../lib/utils"); +let test_utils = require("../test-utils"); -var aliHttpBackend; -var bobHttpBackend; -var aliClient; -var roomId = "!room:localhost"; -var aliUserId = "@ali:localhost"; -var aliDeviceId = "zxcvb"; -var aliAccessToken = "aseukfgwef"; -var bobClient; -var bobUserId = "@bob:localhost"; -var bobDeviceId = "bvcxz"; -var bobAccessToken = "fewgfkuesa"; -var bobOneTimeKeys; -var aliDeviceKeys; -var bobDeviceKeys; -var bobDeviceCurve25519Key; -var bobDeviceEd25519Key; -var aliStorage; -var bobStorage; -var aliMessages; -var bobMessages; +let aliHttpBackend; +let bobHttpBackend; +let aliClient; +let roomId = "!room:localhost"; +let aliUserId = "@ali:localhost"; +let aliDeviceId = "zxcvb"; +let aliAccessToken = "aseukfgwef"; +let bobClient; +let bobUserId = "@bob:localhost"; +let bobDeviceId = "bvcxz"; +let bobAccessToken = "fewgfkuesa"; +let bobOneTimeKeys; +let aliDeviceKeys; +let bobDeviceKeys; +let bobDeviceCurve25519Key; +let bobDeviceEd25519Key; +let aliStorage; +let bobStorage; +let aliMessages; +let bobMessages; /** @@ -38,8 +38,8 @@ var bobMessages; * {one_time_keys: {}, device_keys: {}} */ function expectKeyUpload(deviceId, httpBackend) { - var uploadPath = "/keys/upload/" + deviceId; - var keys = {}; + let uploadPath = "/keys/upload/" + deviceId; + let keys = {}; httpBackend.when("POST", uploadPath).respond(200, function(path, content) { expect(content.one_time_keys).not.toBeDefined(); @@ -52,8 +52,8 @@ function expectKeyUpload(deviceId, httpBackend) { expect(content.device_keys).not.toBeDefined(); expect(content.one_time_keys).toBeDefined(); expect(content.one_time_keys).not.toEqual({}); - var count = 0; - for (var key in content.one_time_keys) { + let count = 0; + for (let key in content.one_time_keys) { if (content.one_time_keys.hasOwnProperty(key)) { count++; } @@ -119,11 +119,11 @@ function expectAliQueryKeys() { // can't query keys before bob has uploaded them expect(bobDeviceKeys).toBeDefined(); - var bobKeys = {}; + let bobKeys = {}; bobKeys[bobDeviceId] = bobDeviceKeys; aliHttpBackend.when("POST", "/keys/query").respond(200, function(path, content) { expect(content.device_keys[bobUserId]).toEqual({}); - var result = {}; + let result = {}; result[bobUserId] = bobKeys; return {device_keys: result}; }); @@ -139,11 +139,11 @@ function expectBobQueryKeys() { // can't query keys before ali has uploaded them expect(aliDeviceKeys).toBeDefined(); - var aliKeys = {}; + let aliKeys = {}; aliKeys[aliDeviceId] = aliDeviceKeys; bobHttpBackend.when("POST", "/keys/query").respond(200, function(path, content) { expect(content.device_keys[aliUserId]).toEqual({}); - var result = {}; + let result = {}; result[aliUserId] = aliKeys; return {device_keys: result}; }); @@ -160,7 +160,7 @@ function expectAliClaimKeys() { expect(bobOneTimeKeys).toBeDefined(); aliHttpBackend.when("POST", "/keys/claim").respond(200, function(path, content) { - var claimType = content.one_time_keys[bobUserId][bobDeviceId]; + let claimType = content.one_time_keys[bobUserId][bobDeviceId]; expect(claimType).toEqual("signed_curve25519"); for (var keyId in bobOneTimeKeys) { if (bobOneTimeKeys.hasOwnProperty(keyId)) { @@ -169,7 +169,7 @@ function expectAliClaimKeys() { } } } - var result = {}; + let result = {}; result[bobUserId] = {}; result[bobUserId][bobDeviceId] = {}; result[bobUserId][bobDeviceId][keyId] = bobOneTimeKeys[keyId]; @@ -184,7 +184,7 @@ function aliDownloadsKeys() { // can't query keys before bob has uploaded them expect(bobDeviceEd25519Key).toBeDefined(); - var p1 = aliClient.downloadKeys([bobUserId]).then(function() { + let p1 = aliClient.downloadKeys([bobUserId]).then(function() { expect(aliClient.listDeviceKeys(bobUserId)).toEqual([{ id: "bvcxz", key: bobDeviceEd25519Key, @@ -193,12 +193,12 @@ function aliDownloadsKeys() { display_name: null, }]); }); - var p2 = expectAliQueryKeys(); + let p2 = expectAliQueryKeys(); // check that the localStorage is updated as we expect (not sure this is // an integration test, but meh) return q.all([p1, p2]).then(function() { - var devices = aliStorage.getEndToEndDevicesForUser(bobUserId); + let devices = aliStorage.getEndToEndDevicesForUser(bobUserId); expect(devices[bobDeviceId].keys).toEqual(bobDeviceKeys.keys); expect(devices[bobDeviceId].verified). toBe(0); // DeviceVerification.UNVERIFIED @@ -232,7 +232,7 @@ function aliSendsFirstMessage() { sendMessage(aliClient), expectAliQueryKeys() .then(expectAliClaimKeys) - .then(expectAliSendMessageRequest) + .then(expectAliSendMessageRequest), ]).spread(function(_, ciphertext) { return ciphertext; }); @@ -247,7 +247,7 @@ function aliSendsFirstMessage() { function aliSendsMessage() { return q.all([ sendMessage(aliClient), - expectAliSendMessageRequest() + expectAliSendMessageRequest(), ]).spread(function(_, ciphertext) { return ciphertext; }); @@ -263,7 +263,7 @@ function bobSendsReplyMessage() { return q.all([ sendMessage(bobClient), expectBobQueryKeys() - .then(expectBobSendMessageRequest) + .then(expectBobSendMessageRequest), ]).spread(function(_, ciphertext) { return ciphertext; }); @@ -278,7 +278,7 @@ function expectAliSendMessageRequest() { return expectSendMessageRequest(aliHttpBackend).then(function(content) { aliMessages.push(content); expect(utils.keys(content.ciphertext)).toEqual([bobDeviceCurve25519Key]); - var ciphertext = content.ciphertext[bobDeviceCurve25519Key]; + let ciphertext = content.ciphertext[bobDeviceCurve25519Key]; expect(ciphertext).toBeDefined(); return ciphertext; }); @@ -292,10 +292,10 @@ function expectAliSendMessageRequest() { function expectBobSendMessageRequest() { return expectSendMessageRequest(bobHttpBackend).then(function(content) { bobMessages.push(content); - var aliKeyId = "curve25519:" + aliDeviceId; - var aliDeviceCurve25519Key = aliDeviceKeys.keys[aliKeyId]; + let aliKeyId = "curve25519:" + aliDeviceId; + let aliDeviceCurve25519Key = aliDeviceKeys.keys[aliKeyId]; expect(utils.keys(content.ciphertext)).toEqual([aliDeviceCurve25519Key]); - var ciphertext = content.ciphertext[aliDeviceCurve25519Key]; + let ciphertext = content.ciphertext[aliDeviceCurve25519Key]; expect(ciphertext).toBeDefined(); return ciphertext; }); @@ -308,8 +308,8 @@ function sendMessage(client) { } function expectSendMessageRequest(httpBackend) { - var path = "/send/m.room.encrypted/"; - var sent; + let path = "/send/m.room.encrypted/"; + let sent; httpBackend.when("PUT", path).respond(200, function(path, content) { sent = content; return { @@ -322,23 +322,23 @@ function expectSendMessageRequest(httpBackend) { } function aliRecvMessage() { - var message = bobMessages.shift(); + let message = bobMessages.shift(); return recvMessage(aliHttpBackend, aliClient, bobUserId, message); } function bobRecvMessage() { - var message = aliMessages.shift(); + let message = aliMessages.shift(); return recvMessage(bobHttpBackend, bobClient, aliUserId, message); } function recvMessage(httpBackend, client, sender, message) { - var syncData = { + let syncData = { next_batch: "x", rooms: { join: { - } - } + }, + }, }; syncData.rooms.join[roomId] = { timeline: { @@ -348,13 +348,13 @@ function recvMessage(httpBackend, client, sender, message) { room: roomId, content: message, sender: sender, - }) - ] - } + }), + ], + }, }; httpBackend.when("GET", "/sync").respond(200, syncData); - var deferred = q.defer(); - var onEvent = function(event) { + let deferred = q.defer(); + let onEvent = function(event) { console.log(client.credentials.userId + " received event", event); @@ -366,7 +366,7 @@ function recvMessage(httpBackend, client, sender, message) { expect(event.getType()).toEqual("m.room.message"); expect(event.getContent()).toEqual({ msgtype: "m.text", - body: "Hello, World" + body: "Hello, World", }); expect(event.isEncrypted()).toBeTruthy(); @@ -387,7 +387,7 @@ function aliStartClient() { // ali will try to query her own keys on start aliHttpBackend.when("POST", "/keys/query").respond(200, function(path, content) { expect(content.device_keys[aliUserId]).toEqual({}); - var result = {}; + let result = {}; result[aliUserId] = {}; return {device_keys: result}; }); @@ -404,7 +404,7 @@ function bobStartClient() { // bob will try to query his own keys on start bobHttpBackend.when("POST", "/keys/query").respond(200, function(path, content) { expect(content.device_keys[bobUserId]).toEqual({}); - var result = {}; + let result = {}; result[bobUserId] = {}; return {device_keys: result}; }); @@ -428,11 +428,11 @@ function startClient(httpBackend, client) { httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" }); // send a sync response including our test room. - var syncData = { + let syncData = { next_batch: "x", rooms: { - join: { } - } + join: { }, + }, }; syncData.rooms.join[roomId] = { state: { @@ -445,11 +445,11 @@ function startClient(httpBackend, client) { mship: "join", user: bobUserId, }), - ] + ], }, timeline: { - events: [] - } + events: [], + }, }; httpBackend.when("GET", "/sync").respond(200, syncData); @@ -506,14 +506,14 @@ describe("MatrixClient crypto", function() { aliHttpBackend.when('POST', '/keys/query').respond(200, { device_keys: { '@bob:id': {}, - } + }, }); - var p1 = aliClient.downloadKeys(['@bob:id']); - var p2 = aliHttpBackend.flush('/keys/query', 1); + let p1 = aliClient.downloadKeys(['@bob:id']); + let p2 = aliHttpBackend.flush('/keys/query', 1); q.all([p1, p2]).then(function() { - var devices = aliStorage.getEndToEndDevicesForUser('@bob:id'); + let devices = aliStorage.getEndToEndDevicesForUser('@bob:id'); expect(utils.keys(devices).length).toEqual(0); // request again: should be no more requests @@ -554,9 +554,9 @@ describe("MatrixClient crypto", function() { }); it("Ali gets keys with an incorrect userId", function(done) { - var eveUserId = "@eve:localhost"; + let eveUserId = "@eve:localhost"; - var bobDeviceKeys = { + let bobDeviceKeys = { algorithms: ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'], device_id: 'bvcxz', keys: { @@ -572,10 +572,10 @@ describe("MatrixClient crypto", function() { }, }; - var bobKeys = {}; + let bobKeys = {}; bobKeys[bobDeviceId] = bobDeviceKeys; aliHttpBackend.when("POST", "/keys/query").respond(200, function(path, content) { - var result = {}; + let result = {}; result[bobUserId] = bobKeys; return {device_keys: result}; }); @@ -591,7 +591,7 @@ describe("MatrixClient crypto", function() { }); it("Ali gets keys with an incorrect deviceId", function(done) { - var bobDeviceKeys = { + let bobDeviceKeys = { algorithms: ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'], device_id: 'bad_device', keys: { @@ -607,10 +607,10 @@ describe("MatrixClient crypto", function() { }, }; - var bobKeys = {}; + let bobKeys = {}; bobKeys[bobDeviceId] = bobDeviceKeys; aliHttpBackend.when("POST", "/keys/query").respond(200, function(path, content) { - var result = {}; + let result = {}; result[bobUserId] = bobKeys; return {device_keys: result}; }); @@ -660,14 +660,14 @@ describe("MatrixClient crypto", function() { .then(aliSendsFirstMessage) .then(bobStartClient) .then(function() { - var message = aliMessages.shift(); - var syncData = { + let message = aliMessages.shift(); + let syncData = { next_batch: "x", rooms: { join: { - } - } + }, + }, }; syncData.rooms.join[roomId] = { timeline: { @@ -677,14 +677,14 @@ describe("MatrixClient crypto", function() { room: roomId, content: message, sender: "@bogus:sender", - }) - ] - } + }), + ], + }, }; bobHttpBackend.when("GET", "/sync").respond(200, syncData); - var deferred = q.defer(); - var onEvent = function(event) { + let deferred = q.defer(); + let onEvent = function(event) { console.log(bobClient.credentials.userId + " received event", event); @@ -717,8 +717,8 @@ describe("MatrixClient crypto", function() { .then(aliDownloadsKeys) .then(function() { aliClient.setDeviceBlocked(bobUserId, bobDeviceId, true); - var p1 = sendMessage(aliClient); - var p2 = expectAliQueryKeys() + let p1 = sendMessage(aliClient); + let p2 = expectAliQueryKeys() .then(expectAliClaimKeys) .then(function() { return expectSendMessageRequest(aliHttpBackend); @@ -764,7 +764,7 @@ describe("MatrixClient crypto", function() { .then(bobUploadsKeys) .then(aliStartClient) .then(function() { - var syncData = { + let syncData = { next_batch: '2', to_device: { events: [ diff --git a/spec/integ/matrix-client-event-emitter.spec.js b/spec/integ/matrix-client-event-emitter.spec.js index 9f67c5b79..43a4f6424 100644 --- a/spec/integ/matrix-client-event-emitter.spec.js +++ b/spec/integ/matrix-client-event-emitter.spec.js @@ -1,13 +1,13 @@ "use strict"; -var sdk = require("../.."); -var HttpBackend = require("../mock-request"); -var utils = require("../test-utils"); +let sdk = require("../.."); +let HttpBackend = require("../mock-request"); +let utils = require("../test-utils"); describe("MatrixClient events", function() { - var baseUrl = "http://localhost.or.something"; - var client, httpBackend; - var selfUserId = "@alice:localhost"; - var selfAccessToken = "aseukfgwef"; + let baseUrl = "http://localhost.or.something"; + let client, httpBackend; + let selfUserId = "@alice:localhost"; + let selfAccessToken = "aseukfgwef"; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -16,7 +16,7 @@ describe("MatrixClient events", function() { client = sdk.createClient({ baseUrl: baseUrl, userId: selfUserId, - accessToken: selfAccessToken + accessToken: selfAccessToken, }); httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("POST", "/filter").respond(200, { filter_id: "a filter id" }); @@ -28,14 +28,14 @@ describe("MatrixClient events", function() { }); describe("emissions", function() { - var SYNC_DATA = { + let SYNC_DATA = { next_batch: "s_5_3", presence: { events: [ utils.mkPresence({ - user: "@foo:bar", name: "Foo Bar", presence: "online" - }) - ] + user: "@foo:bar", name: "Foo Bar", presence: "online", + }), + ], }, rooms: { join: { @@ -43,30 +43,30 @@ describe("MatrixClient events", function() { timeline: { events: [ utils.mkMessage({ - room: "!erufh:bar", user: "@foo:bar", msg: "hmmm" - }) + room: "!erufh:bar", user: "@foo:bar", msg: "hmmm", + }), ], - prev_batch: "s" + prev_batch: "s", }, state: { events: [ utils.mkMembership({ - room: "!erufh:bar", mship: "join", user: "@foo:bar" + room: "!erufh:bar", mship: "join", user: "@foo:bar", }), utils.mkEvent({ type: "m.room.create", room: "!erufh:bar", user: "@foo:bar", content: { - creator: "@foo:bar" - } - }) - ] - } - } - } - } + creator: "@foo:bar", + }, + }), + ], + }, + }, + }, + }, }; - var NEXT_SYNC_DATA = { + let NEXT_SYNC_DATA = { next_batch: "e_6_7", rooms: { join: { @@ -74,25 +74,25 @@ describe("MatrixClient events", function() { timeline: { events: [ utils.mkMessage({ - room: "!erufh:bar", user: "@foo:bar", msg: "ello ello" + room: "!erufh:bar", user: "@foo:bar", msg: "ello ello", }), utils.mkMessage({ - room: "!erufh:bar", user: "@foo:bar", msg: ":D" + room: "!erufh:bar", user: "@foo:bar", msg: ":D", }), - ] + ], }, ephemeral: { events: [ utils.mkEvent({ type: "m.typing", room: "!erufh:bar", content: { - user_ids: ["@foo:bar"] - } - }) - ] - } - } - } - } + user_ids: ["@foo:bar"], + }, + }), + ], + }, + }, + }, + }, }; it("should emit events from both the first and subsequent /sync calls", @@ -100,7 +100,7 @@ describe("MatrixClient events", function() { httpBackend.when("GET", "/sync").respond(200, SYNC_DATA); httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA); - var expectedEvents = []; + let expectedEvents = []; expectedEvents = expectedEvents.concat( SYNC_DATA.presence.events, SYNC_DATA.rooms.join["!erufh:bar"].timeline.events, @@ -110,8 +110,8 @@ describe("MatrixClient events", function() { ); client.on("event", function(event) { - var found = false; - for (var i = 0; i < expectedEvents.length; i++) { + let found = false; + for (let i = 0; i < expectedEvents.length; i++) { if (expectedEvents[i].event_id === event.getId()) { expectedEvents.splice(i, 1); found = true; @@ -136,12 +136,14 @@ describe("MatrixClient events", function() { it("should emit User events", function(done) { httpBackend.when("GET", "/sync").respond(200, SYNC_DATA); httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA); - var fired = false; + let fired = false; client.on("User.presence", function(event, user) { fired = true; expect(user).toBeDefined(); expect(event).toBeDefined(); - if (!user || !event) { return; } + if (!user || !event) { + return; +} expect(event.event).toEqual(SYNC_DATA.presence.events[0]); expect(user.presence).toEqual( @@ -159,9 +161,9 @@ describe("MatrixClient events", function() { it("should emit Room events", function(done) { httpBackend.when("GET", "/sync").respond(200, SYNC_DATA); httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA); - var roomInvokeCount = 0; - var roomNameInvokeCount = 0; - var timelineFireCount = 0; + let roomInvokeCount = 0; + let roomNameInvokeCount = 0; + let timelineFireCount = 0; client.on("Room", function(room) { roomInvokeCount++; expect(room.roomId).toEqual("!erufh:bar"); @@ -194,15 +196,15 @@ describe("MatrixClient events", function() { httpBackend.when("GET", "/sync").respond(200, SYNC_DATA); httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA); - var roomStateEventTypes = [ - "m.room.member", "m.room.create" + let roomStateEventTypes = [ + "m.room.member", "m.room.create", ]; - var eventsInvokeCount = 0; - var membersInvokeCount = 0; - var newMemberInvokeCount = 0; + let eventsInvokeCount = 0; + let membersInvokeCount = 0; + let newMemberInvokeCount = 0; client.on("RoomState.events", function(event, state) { eventsInvokeCount++; - var index = roomStateEventTypes.indexOf(event.getType()); + let index = roomStateEventTypes.indexOf(event.getType()); expect(index).not.toEqual( -1, "Unexpected room state event type: " + event.getType() ); @@ -243,10 +245,10 @@ describe("MatrixClient events", function() { httpBackend.when("GET", "/sync").respond(200, SYNC_DATA); httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA); - var typingInvokeCount = 0; - var powerLevelInvokeCount = 0; - var nameInvokeCount = 0; - var membershipInvokeCount = 0; + let typingInvokeCount = 0; + let powerLevelInvokeCount = 0; + let nameInvokeCount = 0; + let membershipInvokeCount = 0; client.on("RoomMember.name", function(event, member) { nameInvokeCount++; }); @@ -284,7 +286,7 @@ describe("MatrixClient events", function() { it("should emit Session.logged_out on M_UNKNOWN_TOKEN", function(done) { httpBackend.when("GET", "/sync").respond(401, { errcode: 'M_UNKNOWN_TOKEN' }); - var sessionLoggedOutCount = 0; + let sessionLoggedOutCount = 0; client.on("Session.logged_out", function(event, member) { sessionLoggedOutCount++; }); @@ -299,5 +301,4 @@ describe("MatrixClient events", function() { }); }); }); - }); diff --git a/spec/integ/matrix-client-event-timeline.spec.js b/spec/integ/matrix-client-event-timeline.spec.js index 890b564d8..238494331 100644 --- a/spec/integ/matrix-client-event-timeline.spec.js +++ b/spec/integ/matrix-client-event-timeline.spec.js @@ -1,29 +1,29 @@ "use strict"; -var q = require("q"); -var sdk = require("../.."); -var HttpBackend = require("../mock-request"); -var utils = require("../test-utils"); -var EventTimeline = sdk.EventTimeline; +let q = require("q"); +let sdk = require("../.."); +let HttpBackend = require("../mock-request"); +let utils = require("../test-utils"); +let EventTimeline = sdk.EventTimeline; -var baseUrl = "http://localhost.or.something"; -var userId = "@alice:localhost"; -var userName = "Alice"; -var accessToken = "aseukfgwef"; -var roomId = "!foo:bar"; -var otherUserId = "@bob:localhost"; +let baseUrl = "http://localhost.or.something"; +let userId = "@alice:localhost"; +let userName = "Alice"; +let accessToken = "aseukfgwef"; +let roomId = "!foo:bar"; +let otherUserId = "@bob:localhost"; -var USER_MEMBERSHIP_EVENT = utils.mkMembership({ - room: roomId, mship: "join", user: userId, name: userName +let USER_MEMBERSHIP_EVENT = utils.mkMembership({ + room: roomId, mship: "join", user: userId, name: userName, }); -var ROOM_NAME_EVENT = utils.mkEvent({ +let ROOM_NAME_EVENT = utils.mkEvent({ type: "m.room.name", room: roomId, user: otherUserId, content: { - name: "Old room name" - } + name: "Old room name", + }, }); -var INITIAL_SYNC_DATA = { +let INITIAL_SYNC_DATA = { next_batch: "s_5_3", rooms: { join: { @@ -31,33 +31,33 @@ var INITIAL_SYNC_DATA = { timeline: { events: [ utils.mkMessage({ - room: roomId, user: otherUserId, msg: "hello" - }) + room: roomId, user: otherUserId, msg: "hello", + }), ], - prev_batch: "f_1_1" + prev_batch: "f_1_1", }, state: { events: [ ROOM_NAME_EVENT, utils.mkMembership({ room: roomId, mship: "join", - user: otherUserId, name: "Bob" + user: otherUserId, name: "Bob", }), USER_MEMBERSHIP_EVENT, utils.mkEvent({ type: "m.room.create", room: roomId, user: userId, content: { - creator: userId - } - }) - ] - } - } - } - } + creator: userId, + }, + }), + ], + }, + }, + }, + }, }; -var EVENTS = [ +let EVENTS = [ utils.mkMessage({ room: roomId, user: userId, msg: "we", }), @@ -81,7 +81,7 @@ function startClient(httpBackend, client) { client.startClient(); // set up a promise which will resolve once the client is initialised - var deferred = q.defer(); + let deferred = q.defer(); client.on("sync", function(state) { console.log("sync", state); if (state != "SYNCING") { @@ -96,8 +96,8 @@ function startClient(httpBackend, client) { describe("getEventTimeline support", function() { - var httpBackend; - var client; + let httpBackend; + let client; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -120,9 +120,11 @@ describe("getEventTimeline support", function() { startClient(httpBackend, client ).then(function() { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; - expect(function() { client.getEventTimeline(timelineSet, "event"); }) + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; + expect(function() { + client.getEventTimeline(timelineSet, "event"); +}) .toThrow(); }).catch(utils.failTest).done(done); }); @@ -137,9 +139,11 @@ describe("getEventTimeline support", function() { startClient(httpBackend, client ).then(function() { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; - expect(function() { client.getEventTimeline(timelineSet, "event"); }) + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; + expect(function() { + client.getEventTimeline(timelineSet, "event"); +}) .not.toThrow(); }).catch(utils.failTest).done(done); @@ -155,7 +159,7 @@ describe("getEventTimeline support", function() { userId: userId, accessToken: accessToken, }); - var room; + let room; startClient(httpBackend, client ).then(function() { @@ -218,7 +222,7 @@ describe("getEventTimeline support", function() { }); describe("MatrixClient event timelines", function() { - var client, httpBackend; + let client, httpBackend; beforeEach(function(done) { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -243,8 +247,8 @@ describe("MatrixClient event timelines", function() { describe("getEventTimeline", function() { it("should create a new timeline for new events", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; httpBackend.when("GET", "/rooms/!foo%3Abar/context/event1%3Abar") .respond(200, function() { return { @@ -262,7 +266,7 @@ describe("MatrixClient event timelines", function() { client.getEventTimeline(timelineSet, "event1:bar").then(function(tl) { expect(tl.getEvents().length).toEqual(4); - for (var i = 0; i < 4; i++) { + for (let i = 0; i < 4; i++) { expect(tl.getEvents()[i].event).toEqual(EVENTS[i]); expect(tl.getEvents()[i].sender.name).toEqual(userName); } @@ -276,8 +280,8 @@ describe("MatrixClient event timelines", function() { }); it("should return existing timeline for known events", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; httpBackend.when("GET", "/sync").respond(200, { next_batch: "s_5_4", rooms: { @@ -308,8 +312,8 @@ describe("MatrixClient event timelines", function() { }); it("should update timelines where they overlap a previous /sync", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; httpBackend.when("GET", "/sync").respond(200, { next_batch: "s_5_4", rooms: { @@ -358,8 +362,8 @@ describe("MatrixClient event timelines", function() { it("should join timelines where they overlap a previous /context", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; // we fetch event 0, then 2, then 3, and finally 1. 1 is returned // with context which joins them all up. @@ -415,7 +419,7 @@ describe("MatrixClient event timelines", function() { }; }); - var tl0, tl3; + let tl0, tl3; client.getEventTimeline(timelineSet, EVENTS[0].event_id ).then(function(tl) { expect(tl.getEvents().length).toEqual(1); @@ -451,8 +455,8 @@ describe("MatrixClient event timelines", function() { }); it("should fail gracefully if there is no event field", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; // we fetch event 0, then 2, then 3, and finally 1. 1 is returned // with context which joins them all up. httpBackend.when("GET", "/rooms/!foo%3Abar/context/event1") @@ -480,8 +484,8 @@ describe("MatrixClient event timelines", function() { describe("paginateEventTimeline", function() { it("should allow you to paginate backwards", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; httpBackend.when("GET", "/rooms/!foo%3Abar/context/" + encodeURIComponent(EVENTS[0].event_id)) @@ -498,7 +502,7 @@ describe("MatrixClient event timelines", function() { httpBackend.when("GET", "/rooms/!foo%3Abar/messages") .check(function(req) { - var params = req.queryParams; + let params = req.queryParams; expect(params.dir).toEqual("b"); expect(params.from).toEqual("start_token0"); expect(params.limit).toEqual(30); @@ -509,7 +513,7 @@ describe("MatrixClient event timelines", function() { }; }); - var tl; + let tl; client.getEventTimeline(timelineSet, EVENTS[0].event_id ).then(function(tl0) { tl = tl0; @@ -531,8 +535,8 @@ describe("MatrixClient event timelines", function() { it("should allow you to paginate forwards", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; httpBackend.when("GET", "/rooms/!foo%3Abar/context/" + encodeURIComponent(EVENTS[0].event_id)) @@ -549,7 +553,7 @@ describe("MatrixClient event timelines", function() { httpBackend.when("GET", "/rooms/!foo%3Abar/messages") .check(function(req) { - var params = req.queryParams; + let params = req.queryParams; expect(params.dir).toEqual("f"); expect(params.from).toEqual("end_token0"); expect(params.limit).toEqual(20); @@ -560,7 +564,7 @@ describe("MatrixClient event timelines", function() { }; }); - var tl; + let tl; client.getEventTimeline(timelineSet, EVENTS[0].event_id ).then(function(tl0) { tl = tl0; @@ -583,8 +587,8 @@ describe("MatrixClient event timelines", function() { }); describe("event timeline for sent events", function() { - var TXN_ID = "txn1"; - var event = utils.mkMessage({ + let TXN_ID = "txn1"; + let event = utils.mkMessage({ room: roomId, user: userId, msg: "a body", }); event.unsigned = {transaction_id: TXN_ID}; @@ -603,7 +607,7 @@ describe("MatrixClient event timelines", function() { "!foo:bar": { timeline: { events: [ - event + event, ], prev_batch: "f_1_1", }, @@ -614,8 +618,8 @@ describe("MatrixClient event timelines", function() { }); it("should work when /send returns before /sync", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) { expect(res.event_id).toEqual(event.event_id); @@ -638,8 +642,8 @@ describe("MatrixClient event timelines", function() { }); it("should work when /send returns after /sync", function(done) { - var room = client.getRoom(roomId); - var timelineSet = room.getTimelineSets()[0]; + let room = client.getRoom(roomId); + let timelineSet = room.getTimelineSets()[0]; // initiate the send, and set up checks to be done when it completes // - but note that it won't complete until after the /sync does, below. @@ -671,18 +675,18 @@ describe("MatrixClient event timelines", function() { // https://github.com/vector-im/vector-web/issues/1389 // a state event, followed by a redaction thereof - var event = utils.mkMembership({ - room: roomId, mship: "join", user: otherUserId + let event = utils.mkMembership({ + room: roomId, mship: "join", user: otherUserId, }); - var redaction = utils.mkEvent({ + let redaction = utils.mkEvent({ type: "m.room.redaction", room_id: roomId, sender: otherUserId, - content: {} + content: {}, }); redaction.redacts = event.event_id; - var syncData = { + let syncData = { next_batch: "batch1", rooms: { join: {}, @@ -700,12 +704,12 @@ describe("MatrixClient event timelines", function() { httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.flush().then(function() { - var room = client.getRoom(roomId); - var tl = room.getLiveTimeline(); + let room = client.getRoom(roomId); + let tl = room.getLiveTimeline(); expect(tl.getEvents().length).toEqual(3); expect(tl.getEvents()[1].isRedacted()).toBe(true); - var sync2 = { + let sync2 = { next_batch: "batch2", rooms: { join: {}, @@ -715,7 +719,7 @@ describe("MatrixClient event timelines", function() { timeline: { events: [ utils.mkMessage({ - room: roomId, user: otherUserId, msg: "world" + room: roomId, user: otherUserId, msg: "world", }), ], limited: true, @@ -726,8 +730,8 @@ describe("MatrixClient event timelines", function() { return httpBackend.flush(); }).then(function() { - var room = client.getRoom(roomId); - var tl = room.getLiveTimeline(); + let room = client.getRoom(roomId); + let tl = room.getLiveTimeline(); expect(tl.getEvents().length).toEqual(1); }).catch(utils.failTest).done(done); }); diff --git a/spec/integ/matrix-client-methods.spec.js b/spec/integ/matrix-client-methods.spec.js index 5a8d17800..4d7a8d8a8 100644 --- a/spec/integ/matrix-client-methods.spec.js +++ b/spec/integ/matrix-client-methods.spec.js @@ -1,25 +1,25 @@ "use strict"; -var sdk = require("../.."); -var HttpBackend = require("../mock-request"); -var publicGlobals = require("../../lib/matrix"); -var Room = publicGlobals.Room; -var MatrixInMemoryStore = publicGlobals.MatrixInMemoryStore; -var Filter = publicGlobals.Filter; -var utils = require("../test-utils"); -var MockStorageApi = require("../MockStorageApi"); +let sdk = require("../.."); +let HttpBackend = require("../mock-request"); +let publicGlobals = require("../../lib/matrix"); +let Room = publicGlobals.Room; +let MatrixInMemoryStore = publicGlobals.MatrixInMemoryStore; +let Filter = publicGlobals.Filter; +let utils = require("../test-utils"); +let MockStorageApi = require("../MockStorageApi"); describe("MatrixClient", function() { - var baseUrl = "http://localhost.or.something"; - var client, httpBackend, store, sessionStore; - var userId = "@alice:localhost"; - var accessToken = "aseukfgwef"; + let baseUrl = "http://localhost.or.something"; + let client, httpBackend, store, sessionStore; + let userId = "@alice:localhost"; + let accessToken = "aseukfgwef"; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this httpBackend = new HttpBackend(); store = new MatrixInMemoryStore(); - var mockStorage = new MockStorageApi(); + let mockStorage = new MockStorageApi(); sessionStore = new sdk.WebStorageSessionStore(mockStorage); sdk.request(httpBackend.requestFn); @@ -38,7 +38,7 @@ describe("MatrixClient", function() { }); describe("uploadContent", function() { - var buf = new Buffer('hello world'); + let buf = new Buffer('hello world'); it("should upload the file", function(done) { httpBackend.when( "POST", "/_matrix/media/v1/upload" @@ -51,7 +51,7 @@ describe("MatrixClient", function() { expect(req.opts.timeout).toBe(undefined); }).respond(200, "content"); - var prom = client.uploadContent({ + let prom = client.uploadContent({ stream: buf, name: "hi.txt", type: "text/plain", @@ -59,7 +59,7 @@ describe("MatrixClient", function() { expect(prom).toBeDefined(); - var uploads = client.getCurrentUploads(); + let uploads = client.getCurrentUploads(); expect(uploads.length).toEqual(1); expect(uploads[0].promise).toBe(prom); expect(uploads[0].loaded).toEqual(0); @@ -68,7 +68,7 @@ describe("MatrixClient", function() { // for backwards compatibility, we return the raw JSON expect(response).toEqual("content"); - var uploads = client.getCurrentUploads(); + let uploads = client.getCurrentUploads(); expect(uploads.length).toEqual(0); }).catch(utils.failTest).done(done); @@ -123,13 +123,13 @@ describe("MatrixClient", function() { }); it("should return a promise which can be cancelled", function(done) { - var prom = client.uploadContent({ + let prom = client.uploadContent({ stream: buf, name: "hi.txt", type: "text/plain", }); - var uploads = client.getCurrentUploads(); + let uploads = client.getCurrentUploads(); expect(uploads.length).toEqual(1); expect(uploads[0].promise).toBe(prom); expect(uploads[0].loaded).toEqual(0); @@ -139,23 +139,23 @@ describe("MatrixClient", function() { }, function(error) { expect(error).toEqual("aborted"); - var uploads = client.getCurrentUploads(); + let uploads = client.getCurrentUploads(); expect(uploads.length).toEqual(0); }).catch(utils.failTest).done(done); - var r = client.cancelUpload(prom); + let r = client.cancelUpload(prom); expect(r).toBe(true); }); }); describe("joinRoom", function() { it("should no-op if you've already joined a room", function() { - var roomId = "!foo:bar"; - var room = new Room(roomId); + let roomId = "!foo:bar"; + let room = new Room(roomId); room.addLiveEvents([ utils.mkMembership({ - user: userId, room: roomId, mship: "join", event: true - }) + user: userId, room: roomId, mship: "join", event: true, + }), ]); store.storeRoom(room); client.joinRoom(roomId); @@ -164,11 +164,11 @@ describe("MatrixClient", function() { }); describe("getFilter", function() { - var filterId = "f1lt3r1d"; + let filterId = "f1lt3r1d"; it("should return a filter from the store if allowCached", function(done) { - var filter = Filter.fromJson(userId, filterId, { - event_format: "client" + let filter = Filter.fromJson(userId, filterId, { + event_format: "client", }); store.storeFilter(filter); client.getFilter(userId, filterId, true).done(function(gotFilter) { @@ -180,16 +180,16 @@ describe("MatrixClient", function() { it("should do an HTTP request if !allowCached even if one exists", function(done) { - var httpFilterDefinition = { - event_format: "federation" + let httpFilterDefinition = { + event_format: "federation", }; httpBackend.when( "GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId ).respond(200, httpFilterDefinition); - var storeFilter = Filter.fromJson(userId, filterId, { - event_format: "client" + let storeFilter = Filter.fromJson(userId, filterId, { + event_format: "client", }); store.storeFilter(storeFilter); client.getFilter(userId, filterId, false).done(function(gotFilter) { @@ -202,8 +202,8 @@ describe("MatrixClient", function() { it("should do an HTTP request if nothing is in the cache and then store it", function(done) { - var httpFilterDefinition = { - event_format: "federation" + let httpFilterDefinition = { + event_format: "federation", }; expect(store.getFilter(userId, filterId)).toBeNull(); @@ -221,13 +221,13 @@ describe("MatrixClient", function() { }); describe("createFilter", function() { - var filterId = "f1llllllerid"; + let filterId = "f1llllllerid"; it("should do an HTTP request and then store the filter", function(done) { expect(store.getFilter(userId, filterId)).toBeNull(); - var filterDefinition = { - event_format: "client" + let filterDefinition = { + event_format: "client", }; httpBackend.when( @@ -235,7 +235,7 @@ describe("MatrixClient", function() { ).check(function(req) { expect(req.data).toEqual(filterDefinition); }).respond(200, { - filter_id: filterId + filter_id: filterId, }); client.createFilter(filterDefinition).done(function(gotFilter) { @@ -249,8 +249,7 @@ describe("MatrixClient", function() { }); describe("searching", function() { - - var response = { + let response = { search_categories: { room_events: { count: 24, @@ -263,26 +262,26 @@ describe("MatrixClient", function() { room_id: "!feuiwhf:localhost", content: { body: "a result", - msgtype: "m.text" - } - } - } - } - } - } + msgtype: "m.text", + }, + }, + }, + }, + }, + }, }; it("searchMessageText should perform a /search for room_events", function(done) { client.searchMessageText({ - query: "monkeys" + query: "monkeys", }); httpBackend.when("POST", "/search").check(function(req) { expect(req.data).toEqual({ search_categories: { room_events: { - search_term: "monkeys" - } - } + search_term: "monkeys", + }, + }, }); }).respond(200, response); @@ -295,9 +294,9 @@ describe("MatrixClient", function() { describe("downloadKeys", function() { it("should do an HTTP request and then store the keys", function(done) { - var ed25519key = "7wG2lzAqbjcyEkOP7O4gU7ItYcn+chKzh5sT/5r2l78"; + let ed25519key = "7wG2lzAqbjcyEkOP7O4gU7ItYcn+chKzh5sT/5r2l78"; // ed25519key = client.getDeviceEd25519Key(); - var borisKeys = { + let borisKeys = { dev1: { algorithms: ["1"], device_id: "dev1", @@ -306,14 +305,14 @@ describe("MatrixClient", function() { boris: { "ed25519:dev1": "RAhmbNDq1efK3hCpBzZDsKoGSsrHUxb25NW5/WbEV9R" + - "JVwLdP032mg5QsKt/pBDUGtggBcnk43n3nBWlA88WAw" - } + "JVwLdP032mg5QsKt/pBDUGtggBcnk43n3nBWlA88WAw", + }, }, unsigned: { "abc": "def" }, user_id: "boris", - } + }, }; - var chazKeys = { + let chazKeys = { dev2: { algorithms: ["2"], device_id: "dev2", @@ -322,12 +321,12 @@ describe("MatrixClient", function() { chaz: { "ed25519:dev2": "FwslH/Q7EYSb7swDJbNB5PSzcbEO1xRRBF1riuijqvL" + - "EkrK9/XVN8jl4h7thGuRITQ01siBQnNmMK9t45QfcCQ" - } + "EkrK9/XVN8jl4h7thGuRITQ01siBQnNmMK9t45QfcCQ", + }, }, unsigned: { "ghi": "def" }, user_id: "chaz", - } + }, }; /* @@ -374,7 +373,7 @@ describe("MatrixClient", function() { }); describe("deleteDevice", function() { - var auth = {a: 1}; + let auth = {a: 1}; it("should pass through an auth dict", function(done) { httpBackend.when( "DELETE", "/_matrix/client/unstable/devices/my_device" @@ -392,7 +391,7 @@ describe("MatrixClient", function() { }); function assertObjectContains(obj, expected) { - for (var k in expected) { + for (let k in expected) { if (expected.hasOwnProperty(k)) { expect(obj[k]).toEqual(expected[k]); } diff --git a/spec/integ/matrix-client-opts.spec.js b/spec/integ/matrix-client-opts.spec.js index 27a9514b4..294dc2a43 100644 --- a/spec/integ/matrix-client-opts.spec.js +++ b/spec/integ/matrix-client-opts.spec.js @@ -1,17 +1,17 @@ "use strict"; -var sdk = require("../.."); -var MatrixClient = sdk.MatrixClient; -var HttpBackend = require("../mock-request"); -var utils = require("../test-utils"); +let sdk = require("../.."); +let MatrixClient = sdk.MatrixClient; +let HttpBackend = require("../mock-request"); +let utils = require("../test-utils"); describe("MatrixClient opts", function() { - var baseUrl = "http://localhost.or.something"; - var client, httpBackend; - var userId = "@alice:localhost"; - var userB = "@bob:localhost"; - var accessToken = "aseukfgwef"; - var roomId = "!foo:bar"; - var syncData = { + let baseUrl = "http://localhost.or.something"; + let client, httpBackend; + let userId = "@alice:localhost"; + let userB = "@bob:localhost"; + let accessToken = "aseukfgwef"; + let roomId = "!foo:bar"; + let syncData = { next_batch: "s_5_3", presence: {}, rooms: { @@ -20,36 +20,36 @@ describe("MatrixClient opts", function() { timeline: { events: [ utils.mkMessage({ - room: roomId, user: userB, msg: "hello" - }) + room: roomId, user: userB, msg: "hello", + }), ], - prev_batch: "f_1_1" + prev_batch: "f_1_1", }, state: { events: [ utils.mkEvent({ type: "m.room.name", room: roomId, user: userB, content: { - name: "Old room name" - } + name: "Old room name", + }, }), utils.mkMembership({ - room: roomId, mship: "join", user: userB, name: "Bob" + room: roomId, mship: "join", user: userB, name: "Bob", }), utils.mkMembership({ - room: roomId, mship: "join", user: userId, name: "Alice" + room: roomId, mship: "join", user: userId, name: "Alice", }), utils.mkEvent({ type: "m.room.create", room: roomId, user: userId, content: { - creator: userId - } - }) - ] - } - } - } - } + creator: userId, + }, + }), + ], + }, + }, + }, + }, }; beforeEach(function() { @@ -69,7 +69,7 @@ describe("MatrixClient opts", function() { baseUrl: baseUrl, userId: userId, accessToken: accessToken, - scheduler: new sdk.MatrixScheduler() + scheduler: new sdk.MatrixScheduler(), }); }); @@ -78,9 +78,9 @@ describe("MatrixClient opts", function() { }); it("should be able to send messages", function(done) { - var eventId = "$flibble:wibble"; + let eventId = "$flibble:wibble"; httpBackend.when("PUT", "/txn1").respond(200, { - event_id: eventId + event_id: eventId, }); client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) { expect(res.event_id).toEqual(eventId); @@ -90,9 +90,9 @@ describe("MatrixClient opts", function() { }); it("should be able to sync / get new events", function(done) { - var expectedEventTypes = [ // from /initialSync + let expectedEventTypes = [ // from /initialSync "m.room.message", "m.room.name", "m.room.member", "m.room.member", - "m.room.create" + "m.room.create", ]; client.on("event", function(event) { expect(expectedEventTypes.indexOf(event.getType())).not.toEqual( @@ -127,14 +127,14 @@ describe("MatrixClient opts", function() { baseUrl: baseUrl, userId: userId, accessToken: accessToken, - scheduler: undefined + scheduler: undefined, }); }); it("shouldn't retry sending events", function(done) { httpBackend.when("PUT", "/txn1").fail(500, { errcode: "M_SOMETHING", - error: "Ruh roh" + error: "Ruh roh", }); client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) { expect(false).toBe(true, "sendTextMessage resolved but shouldn't"); @@ -147,13 +147,13 @@ describe("MatrixClient opts", function() { it("shouldn't queue events", function(done) { httpBackend.when("PUT", "/txn1").respond(200, { - event_id: "AAA" + event_id: "AAA", }); httpBackend.when("PUT", "/txn2").respond(200, { - event_id: "BBB" + event_id: "BBB", }); - var sentA = false; - var sentB = false; + let sentA = false; + let sentB = false; client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) { sentA = true; expect(sentB).toBe(true); @@ -171,7 +171,7 @@ describe("MatrixClient opts", function() { it("should be able to send messages", function(done) { httpBackend.when("PUT", "/txn1").respond(200, { - event_id: "foo" + event_id: "foo", }); client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) { expect(res.event_id).toEqual("foo"); diff --git a/spec/integ/matrix-client-retrying.spec.js b/spec/integ/matrix-client-retrying.spec.js index 184231d4b..db8120715 100644 --- a/spec/integ/matrix-client-retrying.spec.js +++ b/spec/integ/matrix-client-retrying.spec.js @@ -1,17 +1,17 @@ "use strict"; -var sdk = require("../.."); -var HttpBackend = require("../mock-request"); -var utils = require("../test-utils"); -var EventStatus = sdk.EventStatus; +let sdk = require("../.."); +let HttpBackend = require("../mock-request"); +let utils = require("../test-utils"); +let EventStatus = sdk.EventStatus; describe("MatrixClient retrying", function() { - var baseUrl = "http://localhost.or.something"; - var client, httpBackend; - var scheduler; - var userId = "@alice:localhost"; - var accessToken = "aseukfgwef"; - var roomId = "!room:here"; - var room; + let baseUrl = "http://localhost.or.something"; + let client, httpBackend; + let scheduler; + let userId = "@alice:localhost"; + let accessToken = "aseukfgwef"; + let roomId = "!room:here"; + let room; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -49,9 +49,8 @@ describe("MatrixClient retrying", function() { }); it("should mark events as EventStatus.CANCELLED when cancelled", function(done) { - // send a couple of events; the second will be queued - var ev1, ev2; + let ev1, ev2; client.sendMessage(roomId, "m1").then(function(ev) { expect(ev).toEqual(ev1); }); @@ -60,7 +59,7 @@ describe("MatrixClient retrying", function() { }); // both events should be in the timeline at this point - var tl = room.getLiveTimeline().getEvents(); + let tl = room.getLiveTimeline().getEvents(); expect(tl.length).toEqual(2); ev1 = tl[0]; ev2 = tl[1]; @@ -79,7 +78,9 @@ describe("MatrixClient retrying", function() { expect(tl.length).toEqual(1); // shouldn't be able to cancel the first message yet - expect(function() { client.cancelPendingEvent(ev1); }) + expect(function() { + client.cancelPendingEvent(ev1); +}) .toThrow(); }).respond(400); // fail the first message diff --git a/spec/integ/matrix-client-room-timeline.spec.js b/spec/integ/matrix-client-room-timeline.spec.js index 20d678657..acd8deb97 100644 --- a/spec/integ/matrix-client-room-timeline.spec.js +++ b/spec/integ/matrix-client-room-timeline.spec.js @@ -1,28 +1,28 @@ "use strict"; -var sdk = require("../.."); -var EventStatus = sdk.EventStatus; -var HttpBackend = require("../mock-request"); -var utils = require("../test-utils"); +let sdk = require("../.."); +let EventStatus = sdk.EventStatus; +let HttpBackend = require("../mock-request"); +let utils = require("../test-utils"); describe("MatrixClient room timelines", function() { - var baseUrl = "http://localhost.or.something"; - var client, httpBackend; - var userId = "@alice:localhost"; - var userName = "Alice"; - var accessToken = "aseukfgwef"; - var roomId = "!foo:bar"; - var otherUserId = "@bob:localhost"; - var USER_MEMBERSHIP_EVENT = utils.mkMembership({ - room: roomId, mship: "join", user: userId, name: userName + let baseUrl = "http://localhost.or.something"; + let client, httpBackend; + let userId = "@alice:localhost"; + let userName = "Alice"; + let accessToken = "aseukfgwef"; + let roomId = "!foo:bar"; + let otherUserId = "@bob:localhost"; + let USER_MEMBERSHIP_EVENT = utils.mkMembership({ + room: roomId, mship: "join", user: userId, name: userName, }); - var ROOM_NAME_EVENT = utils.mkEvent({ + let ROOM_NAME_EVENT = utils.mkEvent({ type: "m.room.name", room: roomId, user: otherUserId, content: { - name: "Old room name" - } + name: "Old room name", + }, }); - var NEXT_SYNC_DATA; - var SYNC_DATA = { + let NEXT_SYNC_DATA; + let SYNC_DATA = { next_batch: "s_5_3", rooms: { join: { @@ -30,30 +30,30 @@ describe("MatrixClient room timelines", function() { timeline: { events: [ utils.mkMessage({ - room: roomId, user: otherUserId, msg: "hello" - }) + room: roomId, user: otherUserId, msg: "hello", + }), ], - prev_batch: "f_1_1" + prev_batch: "f_1_1", }, state: { events: [ ROOM_NAME_EVENT, utils.mkMembership({ room: roomId, mship: "join", - user: otherUserId, name: "Bob" + user: otherUserId, name: "Bob", }), USER_MEMBERSHIP_EVENT, utils.mkEvent({ type: "m.room.create", room: roomId, user: userId, content: { - creator: userId - } - }) - ] - } - } - } - } + creator: userId, + }, + }), + ], + }, + }, + }, + }, }; function setNextSyncData(events) { @@ -67,11 +67,11 @@ describe("MatrixClient room timelines", function() { "!foo:bar": { timeline: { events: [] }, state: { events: [] }, - ephemeral: { events: [] } - } + ephemeral: { events: [] }, + }, }, - leave: {} - } + leave: {}, + }, }; events.forEach(function(e) { if (e.room_id !== roomId) { @@ -90,11 +90,9 @@ describe("MatrixClient room timelines", function() { } // push the current NEXT_SYNC_DATA.rooms.join[roomId].timeline.events.push(e); - } - else if (["m.typing", "m.receipt"].indexOf(e.type) !== -1) { + } else if (["m.typing", "m.receipt"].indexOf(e.type) !== -1) { NEXT_SYNC_DATA.rooms.join[roomId].ephemeral.events.push(e); - } - else { + } else { NEXT_SYNC_DATA.rooms.join[roomId].timeline.events.push(e); } }); @@ -130,12 +128,13 @@ describe("MatrixClient room timelines", function() { }); describe("local echo events", function() { - it("should be added immediately after calling MatrixClient.sendEvent " + "with EventStatus.SENDING and the right event.sender", function(done) { client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); expect(room.timeline.length).toEqual(1); client.sendTextMessage(roomId, "I am a fish", "txn1"); @@ -144,7 +143,7 @@ describe("MatrixClient room timelines", function() { // check status expect(room.timeline[1].status).toEqual(EventStatus.SENDING); // check member - var member = room.timeline[1].sender; + let member = room.timeline[1].sender; expect(member.userId).toEqual(userId); expect(member.name).toEqual(userName); @@ -157,21 +156,23 @@ describe("MatrixClient room timelines", function() { it("should be updated correctly when the send request finishes " + "BEFORE the event comes down the event stream", function(done) { - var eventId = "$foo:bar"; + let eventId = "$foo:bar"; httpBackend.when("PUT", "/txn1").respond(200, { - event_id: eventId + event_id: eventId, }); - var ev = utils.mkMessage({ - body: "I am a fish", user: userId, room: roomId + let ev = utils.mkMessage({ + body: "I am a fish", user: userId, room: roomId, }); ev.event_id = eventId; ev.unsigned = {transaction_id: "txn1"}; setNextSyncData([ev]); client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); client.sendTextMessage(roomId, "I am a fish", "txn1").done( function() { expect(room.timeline[1].getId()).toEqual(eventId); @@ -187,22 +188,24 @@ describe("MatrixClient room timelines", function() { it("should be updated correctly when the send request finishes " + "AFTER the event comes down the event stream", function(done) { - var eventId = "$foo:bar"; + let eventId = "$foo:bar"; httpBackend.when("PUT", "/txn1").respond(200, { - event_id: eventId + event_id: eventId, }); - var ev = utils.mkMessage({ - body: "I am a fish", user: userId, room: roomId + let ev = utils.mkMessage({ + body: "I am a fish", user: userId, room: roomId, }); ev.event_id = eventId; ev.unsigned = {transaction_id: "txn1"}; setNextSyncData([ev]); client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); - var promise = client.sendTextMessage(roomId, "I am a fish", "txn1"); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); + let promise = client.sendTextMessage(roomId, "I am a fish", "txn1"); httpBackend.flush("/sync", 1).done(function() { expect(room.timeline.length).toEqual(2); httpBackend.flush("/txn1", 1); @@ -212,15 +215,14 @@ describe("MatrixClient room timelines", function() { done(); }); }); - }); httpBackend.flush("/sync", 1); }); }); describe("paginated events", function() { - var sbEvents; - var sbEndTok = "pagin_end"; + let sbEvents; + let sbEndTok = "pagin_end"; beforeEach(function() { sbEvents = []; @@ -228,7 +230,7 @@ describe("MatrixClient room timelines", function() { return { chunk: sbEvents, start: "pagin_start", - end: sbEndTok + end: sbEndTok, }; }); }); @@ -236,8 +238,10 @@ describe("MatrixClient room timelines", function() { it("should set Room.oldState.paginationToken to null at the start" + " of the timeline.", function(done) { client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); expect(room.timeline.length).toEqual(1); client.scrollback(room).done(function() { @@ -263,49 +267,51 @@ describe("MatrixClient room timelines", function() { // hello // make an m.room.member event for alice's join - var joinMshipEvent = utils.mkMembership({ + let joinMshipEvent = utils.mkMembership({ mship: "join", user: userId, room: roomId, name: "Old Alice", - url: null + url: null, }); // make an m.room.member event with prev_content for alice's nick // change - var oldMshipEvent = utils.mkMembership({ + let oldMshipEvent = utils.mkMembership({ mship: "join", user: userId, room: roomId, name: userName, - url: "mxc://some/url" + url: "mxc://some/url", }); oldMshipEvent.prev_content = { displayname: "Old Alice", avatar_url: null, - membership: "join" + membership: "join", }; // set the list of events to return on scrollback (/messages) // N.B. synapse returns /messages in reverse chronological order sbEvents = [ utils.mkMessage({ - user: userId, room: roomId, msg: "I'm alice" + user: userId, room: roomId, msg: "I'm alice", }), oldMshipEvent, utils.mkMessage({ - user: userId, room: roomId, msg: "I'm old alice" + user: userId, room: roomId, msg: "I'm old alice", }), joinMshipEvent, ]; client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); // sync response expect(room.timeline.length).toEqual(1); client.scrollback(room).done(function() { expect(room.timeline.length).toEqual(5); - var joinMsg = room.timeline[0]; + let joinMsg = room.timeline[0]; expect(joinMsg.sender.name).toEqual("Old Alice"); - var oldMsg = room.timeline[1]; + let oldMsg = room.timeline[1]; expect(oldMsg.sender.name).toEqual("Old Alice"); - var newMsg = room.timeline[3]; + let newMsg = room.timeline[3]; expect(newMsg.sender.name).toEqual(userName); done(); }); @@ -320,16 +326,18 @@ describe("MatrixClient room timelines", function() { // set the list of events to return on scrollback sbEvents = [ utils.mkMessage({ - user: userId, room: roomId, msg: "I am new" + user: userId, room: roomId, msg: "I am new", }), utils.mkMessage({ - user: userId, room: roomId, msg: "I am old" - }) + user: userId, room: roomId, msg: "I am old", + }), ]; client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); expect(room.timeline.length).toEqual(1); client.scrollback(room).done(function() { @@ -349,13 +357,15 @@ describe("MatrixClient room timelines", function() { // set the list of events to return on scrollback sbEvents = [ utils.mkMessage({ - user: userId, room: roomId, msg: "I am new" - }) + user: userId, room: roomId, msg: "I am new", + }), ]; client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); expect(room.oldState.paginationToken).toBeDefined(); client.scrollback(room, 1).done(function() { @@ -373,17 +383,19 @@ describe("MatrixClient room timelines", function() { describe("new events", function() { it("should be added to the right place in the timeline", function(done) { - var eventData = [ + let eventData = [ + utils.mkMessage({user: userId, room: roomId}), utils.mkMessage({user: userId, room: roomId}), - utils.mkMessage({user: userId, room: roomId}) ]; setNextSyncData(eventData); client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); - var index = 0; + let index = 0; client.on("Room.timeline", function(event, rm, toStart) { expect(toStart).toBe(false); expect(rm).toEqual(room); @@ -407,22 +419,24 @@ describe("MatrixClient room timelines", function() { }); it("should set the right event.sender values", function(done) { - var eventData = [ + let eventData = [ utils.mkMessage({user: userId, room: roomId}), utils.mkMembership({ - user: userId, room: roomId, mship: "join", name: "New Name" + user: userId, room: roomId, mship: "join", name: "New Name", }), - utils.mkMessage({user: userId, room: roomId}) + utils.mkMessage({user: userId, room: roomId}), ]; eventData[1].__prev_event = USER_MEMBERSHIP_EVENT; setNextSyncData(eventData); client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); httpBackend.flush("/sync", 1).then(function() { - var preNameEvent = room.timeline[room.timeline.length - 3]; - var postNameEvent = room.timeline[room.timeline.length - 1]; + let preNameEvent = room.timeline[room.timeline.length - 3]; + let postNameEvent = room.timeline[room.timeline.length - 1]; expect(preNameEvent.sender.name).toEqual(userName); expect(postNameEvent.sender.name).toEqual("New Name"); }).catch(utils.failTest).done(done); @@ -431,18 +445,20 @@ describe("MatrixClient room timelines", function() { }); it("should set the right room.name", function(done) { - var secondRoomNameEvent = utils.mkEvent({ + let secondRoomNameEvent = utils.mkEvent({ user: userId, room: roomId, type: "m.room.name", content: { - name: "Room 2" - } + name: "Room 2", + }, }); secondRoomNameEvent.__prev_event = ROOM_NAME_EVENT; setNextSyncData([secondRoomNameEvent]); client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); - var nameEmitCount = 0; + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); + let nameEmitCount = 0; client.on("Room.name", function(rm) { nameEmitCount += 1; }); @@ -451,10 +467,10 @@ describe("MatrixClient room timelines", function() { expect(nameEmitCount).toEqual(1); expect(room.name).toEqual("Room 2"); // do another round - var thirdRoomNameEvent = utils.mkEvent({ + let thirdRoomNameEvent = utils.mkEvent({ user: userId, room: roomId, type: "m.room.name", content: { - name: "Room 3" - } + name: "Room 3", + }, }); thirdRoomNameEvent.__prev_event = secondRoomNameEvent; setNextSyncData([thirdRoomNameEvent]); @@ -470,23 +486,25 @@ describe("MatrixClient room timelines", function() { }); it("should set the right room members", function(done) { - var userC = "@cee:bar"; - var userD = "@dee:bar"; - var eventData = [ + let userC = "@cee:bar"; + let userD = "@dee:bar"; + let eventData = [ utils.mkMembership({ - user: userC, room: roomId, mship: "join", name: "C" + user: userC, room: roomId, mship: "join", name: "C", }), utils.mkMembership({ - user: userC, room: roomId, mship: "invite", skey: userD - }) + user: userC, room: roomId, mship: "invite", skey: userD, + }), ]; eventData[0].__prev_event = null; eventData[1].__prev_event = null; setNextSyncData(eventData); client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); httpBackend.flush("/sync", 1).then(function() { expect(room.currentState.getMembers().length).toEqual(4); expect(room.currentState.getMember(userC).name).toEqual("C"); @@ -505,15 +523,17 @@ describe("MatrixClient room timelines", function() { describe("gappy sync", function() { it("should copy the last known state to the new timeline", function(done) { - var eventData = [ + let eventData = [ utils.mkMessage({user: userId, room: roomId}), ]; setNextSyncData(eventData); NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true; client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); httpBackend.flush("/messages", 1); httpBackend.flush("/sync", 1).done(function() { @@ -535,17 +555,19 @@ describe("MatrixClient room timelines", function() { }); it("should emit a 'Room.timelineReset' event", function(done) { - var eventData = [ + let eventData = [ utils.mkMessage({user: userId, room: roomId}), ]; setNextSyncData(eventData); NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true; client.on("sync", function(state) { - if (state !== "PREPARED") { return; } - var room = client.getRoom(roomId); + if (state !== "PREPARED") { + return; +} + let room = client.getRoom(roomId); - var emitCount = 0; + let emitCount = 0; client.on("Room.timelineReset", function(emitRoom) { expect(emitRoom).toEqual(room); emitCount++; diff --git a/spec/integ/matrix-client-syncing.spec.js b/spec/integ/matrix-client-syncing.spec.js index e9257ad67..df2d0f42b 100644 --- a/spec/integ/matrix-client-syncing.spec.js +++ b/spec/integ/matrix-client-syncing.spec.js @@ -1,21 +1,21 @@ "use strict"; -var sdk = require("../.."); -var HttpBackend = require("../mock-request"); -var utils = require("../test-utils"); -var MatrixEvent = sdk.MatrixEvent; -var EventTimeline = sdk.EventTimeline; +let sdk = require("../.."); +let HttpBackend = require("../mock-request"); +let utils = require("../test-utils"); +let MatrixEvent = sdk.MatrixEvent; +let EventTimeline = sdk.EventTimeline; describe("MatrixClient syncing", function() { - var baseUrl = "http://localhost.or.something"; - var client, httpBackend; - var selfUserId = "@alice:localhost"; - var selfAccessToken = "aseukfgwef"; - var otherUserId = "@bob:localhost"; - var userA = "@alice:bar"; - var userB = "@bob:bar"; - var userC = "@claire:bar"; - var roomOne = "!foo:localhost"; - var roomTwo = "!bar:localhost"; + let baseUrl = "http://localhost.or.something"; + let client, httpBackend; + let selfUserId = "@alice:localhost"; + let selfAccessToken = "aseukfgwef"; + let otherUserId = "@bob:localhost"; + let userA = "@alice:bar"; + let userB = "@bob:bar"; + let userC = "@claire:bar"; + let roomOne = "!foo:localhost"; + let roomTwo = "!bar:localhost"; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -24,7 +24,7 @@ describe("MatrixClient syncing", function() { client = sdk.createClient({ baseUrl: baseUrl, userId: selfUserId, - accessToken: selfAccessToken + accessToken: selfAccessToken, }); httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("POST", "/filter").respond(200, { filter_id: "a filter id" }); @@ -36,10 +36,10 @@ describe("MatrixClient syncing", function() { }); describe("startClient", function() { - var syncData = { + let syncData = { next_batch: "batch_token", rooms: {}, - presence: {} + presence: {}, }; it("should /sync after /pushrules and /filter.", function(done) { @@ -68,17 +68,16 @@ describe("MatrixClient syncing", function() { }); describe("resolving invites to profile info", function() { - - var syncData = { + let syncData = { next_batch: "s_5_3", presence: { - events: [] + events: [], }, rooms: { join: { - } - } + }, + }, }; beforeEach(function() { @@ -87,33 +86,33 @@ describe("MatrixClient syncing", function() { timeline: { events: [ utils.mkMessage({ - room: roomOne, user: otherUserId, msg: "hello" - }) - ] + room: roomOne, user: otherUserId, msg: "hello", + }), + ], }, state: { events: [ utils.mkMembership({ - room: roomOne, mship: "join", user: otherUserId + room: roomOne, mship: "join", user: otherUserId, }), utils.mkMembership({ - room: roomOne, mship: "join", user: selfUserId + room: roomOne, mship: "join", user: selfUserId, }), utils.mkEvent({ type: "m.room.create", room: roomOne, user: selfUserId, content: { - creator: selfUserId - } - }) - ] - } + creator: selfUserId, + }, + }), + ], + }, }; }); it("should resolve incoming invites from /sync", function(done) { syncData.rooms.join[roomOne].state.events.push( utils.mkMembership({ - room: roomOne, mship: "invite", user: userC + room: roomOne, mship: "invite", user: userC, }) ); @@ -121,16 +120,16 @@ describe("MatrixClient syncing", function() { httpBackend.when("GET", "/profile/" + encodeURIComponent(userC)).respond( 200, { avatar_url: "mxc://flibble/wibble", - displayname: "The Boss" + displayname: "The Boss", } ); client.startClient({ - resolveInvitesToProfiles: true + resolveInvitesToProfiles: true, }); httpBackend.flush().done(function() { - var member = client.getRoom(roomOne).getMember(userC); + let member = client.getRoom(roomOne).getMember(userC); expect(member.name).toEqual("The Boss"); expect( member.getAvatarUrl("home.server.url", null, null, null, false) @@ -142,23 +141,23 @@ describe("MatrixClient syncing", function() { it("should use cached values from m.presence wherever possible", function(done) { syncData.presence.events = [ utils.mkPresence({ - user: userC, presence: "online", name: "The Ghost" + user: userC, presence: "online", name: "The Ghost", }), ]; syncData.rooms.join[roomOne].state.events.push( utils.mkMembership({ - room: roomOne, mship: "invite", user: userC + room: roomOne, mship: "invite", user: userC, }) ); httpBackend.when("GET", "/sync").respond(200, syncData); client.startClient({ - resolveInvitesToProfiles: true + resolveInvitesToProfiles: true, }); httpBackend.flush().done(function() { - var member = client.getRoom(roomOne).getMember(userC); + let member = client.getRoom(roomOne).getMember(userC); expect(member.name).toEqual("The Ghost"); done(); }); @@ -167,18 +166,18 @@ describe("MatrixClient syncing", function() { it("should result in events on the room member firing", function(done) { syncData.presence.events = [ utils.mkPresence({ - user: userC, presence: "online", name: "The Ghost" - }) + user: userC, presence: "online", name: "The Ghost", + }), ]; syncData.rooms.join[roomOne].state.events.push( utils.mkMembership({ - room: roomOne, mship: "invite", user: userC + room: roomOne, mship: "invite", user: userC, }) ); httpBackend.when("GET", "/sync").respond(200, syncData); - var latestFiredName = null; + let latestFiredName = null; client.on("RoomMember.name", function(event, m) { if (m.userId === userC && m.roomId === roomOne) { latestFiredName = m.name; @@ -186,7 +185,7 @@ describe("MatrixClient syncing", function() { }); client.startClient({ - resolveInvitesToProfiles: true + resolveInvitesToProfiles: true, }); httpBackend.flush().done(function() { @@ -198,7 +197,7 @@ describe("MatrixClient syncing", function() { it("should no-op if resolveInvitesToProfiles is not set", function(done) { syncData.rooms.join[roomOne].state.events.push( utils.mkMembership({ - room: roomOne, mship: "invite", user: userC + room: roomOne, mship: "invite", user: userC, }) ); @@ -207,7 +206,7 @@ describe("MatrixClient syncing", function() { client.startClient(); httpBackend.flush().done(function() { - var member = client.getRoom(roomOne).getMember(userC); + let member = client.getRoom(roomOne).getMember(userC); expect(member.name).toEqual(userC); expect( member.getAvatarUrl("home.server.url", null, null, null, false) @@ -218,18 +217,18 @@ describe("MatrixClient syncing", function() { }); describe("users", function() { - var syncData = { + let syncData = { next_batch: "nb", presence: { events: [ utils.mkPresence({ - user: userA, presence: "online" + user: userA, presence: "online", }), utils.mkPresence({ - user: userB, presence: "unavailable" - }) - ] - } + user: userB, presence: "unavailable", + }), + ], + }, }; it("should create users for presence events from /sync", @@ -247,80 +246,80 @@ describe("MatrixClient syncing", function() { }); describe("room state", function() { - var msgText = "some text here"; - var otherDisplayName = "Bob Smith"; + let msgText = "some text here"; + let otherDisplayName = "Bob Smith"; - var syncData = { + let syncData = { rooms: { join: { - } - } + }, + }, }; syncData.rooms.join[roomOne] = { timeline: { events: [ utils.mkMessage({ - room: roomOne, user: otherUserId, msg: "hello" - }) - ] + room: roomOne, user: otherUserId, msg: "hello", + }), + ], }, state: { events: [ utils.mkEvent({ type: "m.room.name", room: roomOne, user: otherUserId, content: { - name: "Old room name" - } + name: "Old room name", + }, }), utils.mkMembership({ - room: roomOne, mship: "join", user: otherUserId + room: roomOne, mship: "join", user: otherUserId, }), utils.mkMembership({ - room: roomOne, mship: "join", user: selfUserId + room: roomOne, mship: "join", user: selfUserId, }), utils.mkEvent({ type: "m.room.create", room: roomOne, user: selfUserId, content: { - creator: selfUserId - } - }) - ] - } + creator: selfUserId, + }, + }), + ], + }, }; syncData.rooms.join[roomTwo] = { timeline: { events: [ utils.mkMessage({ - room: roomTwo, user: otherUserId, msg: "hiii" - }) - ] + room: roomTwo, user: otherUserId, msg: "hiii", + }), + ], }, state: { events: [ utils.mkMembership({ room: roomTwo, mship: "join", user: otherUserId, - name: otherDisplayName + name: otherDisplayName, }), utils.mkMembership({ - room: roomTwo, mship: "join", user: selfUserId + room: roomTwo, mship: "join", user: selfUserId, }), utils.mkEvent({ type: "m.room.create", room: roomTwo, user: selfUserId, content: { - creator: selfUserId - } - }) - ] - } + creator: selfUserId, + }, + }), + ], + }, }; - var nextSyncData = { + let nextSyncData = { rooms: { join: { - } - } + }, + }, }; nextSyncData.rooms.join[roomOne] = { @@ -328,28 +327,28 @@ describe("MatrixClient syncing", function() { events: [ utils.mkEvent({ type: "m.room.name", room: roomOne, user: selfUserId, - content: { name: "A new room name" } - }) - ] - } + content: { name: "A new room name" }, + }), + ], + }, }; nextSyncData.rooms.join[roomTwo] = { timeline: { events: [ utils.mkMessage({ - room: roomTwo, user: otherUserId, msg: msgText - }) - ] + room: roomTwo, user: otherUserId, msg: msgText, + }), + ], }, ephemeral: { events: [ utils.mkEvent({ type: "m.typing", room: roomTwo, - content: { user_ids: [otherUserId] } - }) - ] - } + content: { user_ids: [otherUserId] }, + }), + ], + }, }; it("should continually recalculate the right room name.", function(done) { @@ -359,7 +358,7 @@ describe("MatrixClient syncing", function() { client.startClient(); httpBackend.flush().done(function() { - var room = client.getRoom(roomOne); + let room = client.getRoom(roomOne); // should have clobbered the name to the one from /events expect(room.name).toEqual( nextSyncData.rooms.join[roomOne].state.events[0].content.name @@ -375,7 +374,7 @@ describe("MatrixClient syncing", function() { client.startClient(); httpBackend.flush().done(function() { - var room = client.getRoom(roomTwo); + let room = client.getRoom(roomTwo); // should have added the message from /events expect(room.timeline.length).toEqual(2); expect(room.timeline[1].getContent().body).toEqual(msgText); @@ -389,7 +388,7 @@ describe("MatrixClient syncing", function() { client.startClient(); httpBackend.flush().done(function() { - var room = client.getRoom(roomTwo); + let room = client.getRoom(roomTwo); // should use the display name of the other person. expect(room.name).toEqual(otherDisplayName); done(); @@ -403,8 +402,8 @@ describe("MatrixClient syncing", function() { client.startClient(); httpBackend.flush().done(function() { - var room = client.getRoom(roomTwo); - var member = room.getMember(otherUserId); + let room = client.getRoom(roomTwo); + let member = room.getMember(otherUserId); expect(member).toBeDefined(); expect(member.typing).toEqual(true); member = room.getMember(selfUserId); @@ -425,7 +424,7 @@ describe("MatrixClient syncing", function() { describe("timeline", function() { beforeEach(function() { - var syncData = { + let syncData = { next_batch: "batch_token", rooms: { join: {}, @@ -435,7 +434,7 @@ describe("MatrixClient syncing", function() { timeline: { events: [ utils.mkMessage({ - room: roomOne, user: otherUserId, msg: "hello" + room: roomOne, user: otherUserId, msg: "hello", }), ], prev_batch: "pagTok", @@ -449,7 +448,7 @@ describe("MatrixClient syncing", function() { }); it("should set the back-pagination token on new rooms", function(done) { - var syncData = { + let syncData = { next_batch: "batch_token", rooms: { join: {}, @@ -459,7 +458,7 @@ describe("MatrixClient syncing", function() { timeline: { events: [ utils.mkMessage({ - room: roomTwo, user: otherUserId, msg: "roomtwo" + room: roomTwo, user: otherUserId, msg: "roomtwo", }), ], prev_batch: "roomtwotok", @@ -469,8 +468,8 @@ describe("MatrixClient syncing", function() { httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.flush().then(function() { - var room = client.getRoom(roomTwo); - var tok = room.getLiveTimeline() + let room = client.getRoom(roomTwo); + let tok = room.getLiveTimeline() .getPaginationToken(EventTimeline.BACKWARDS); expect(tok).toEqual("roomtwotok"); done(); @@ -478,7 +477,7 @@ describe("MatrixClient syncing", function() { }); it("should set the back-pagination token on gappy syncs", function(done) { - var syncData = { + let syncData = { next_batch: "batch_token", rooms: { join: {}, @@ -488,7 +487,7 @@ describe("MatrixClient syncing", function() { timeline: { events: [ utils.mkMessage({ - room: roomOne, user: otherUserId, msg: "world" + room: roomOne, user: otherUserId, msg: "world", }), ], limited: true, @@ -497,20 +496,20 @@ describe("MatrixClient syncing", function() { }; httpBackend.when("GET", "/sync").respond(200, syncData); - var resetCallCount = 0; + let resetCallCount = 0; // the token should be set *before* timelineReset is emitted client.on("Room.timelineReset", function(room) { resetCallCount++; - var tl = room.getLiveTimeline(); + let tl = room.getLiveTimeline(); expect(tl.getEvents().length).toEqual(0); - var tok = tl.getPaginationToken(EventTimeline.BACKWARDS); + let tok = tl.getPaginationToken(EventTimeline.BACKWARDS); expect(tok).toEqual("newerTok"); }); httpBackend.flush().then(function() { - var room = client.getRoom(roomOne); - var tl = room.getLiveTimeline(); + let room = client.getRoom(roomOne); + let tl = room.getLiveTimeline(); expect(tl.getEvents().length).toEqual(1); expect(resetCallCount).toEqual(1); done(); @@ -519,80 +518,80 @@ describe("MatrixClient syncing", function() { }); describe("receipts", function() { - var syncData = { + let syncData = { rooms: { join: { - } - } + }, + }, }; syncData.rooms.join[roomOne] = { timeline: { events: [ utils.mkMessage({ - room: roomOne, user: otherUserId, msg: "hello" + room: roomOne, user: otherUserId, msg: "hello", }), utils.mkMessage({ - room: roomOne, user: otherUserId, msg: "world" - }) - ] + room: roomOne, user: otherUserId, msg: "world", + }), + ], }, state: { events: [ utils.mkEvent({ type: "m.room.name", room: roomOne, user: otherUserId, content: { - name: "Old room name" - } + name: "Old room name", + }, }), utils.mkMembership({ - room: roomOne, mship: "join", user: otherUserId + room: roomOne, mship: "join", user: otherUserId, }), utils.mkMembership({ - room: roomOne, mship: "join", user: selfUserId + room: roomOne, mship: "join", user: selfUserId, }), utils.mkEvent({ type: "m.room.create", room: roomOne, user: selfUserId, content: { - creator: selfUserId - } - }) - ] - } + creator: selfUserId, + }, + }), + ], + }, }; beforeEach(function() { syncData.rooms.join[roomOne].ephemeral = { - events: [] + events: [], }; }); it("should sync receipts from /sync.", function(done) { - var ackEvent = syncData.rooms.join[roomOne].timeline.events[0]; - var receipt = {}; + let ackEvent = syncData.rooms.join[roomOne].timeline.events[0]; + let receipt = {}; receipt[ackEvent.event_id] = { - "m.read": {} + "m.read": {}, }; receipt[ackEvent.event_id]["m.read"][userC] = { - ts: 176592842636 + ts: 176592842636, }; syncData.rooms.join[roomOne].ephemeral.events = [{ content: receipt, room_id: roomOne, - type: "m.receipt" + type: "m.receipt", }]; httpBackend.when("GET", "/sync").respond(200, syncData); client.startClient(); httpBackend.flush().done(function() { - var room = client.getRoom(roomOne); + let room = client.getRoom(roomOne); expect(room.getReceiptsForEvent(new MatrixEvent(ackEvent))).toEqual([{ type: "m.read", userId: userC, data: { - ts: 176592842636 - } + ts: 176592842636, + }, }]); done(); }); @@ -647,10 +646,10 @@ describe("MatrixClient syncing", function() { }); it("should set the back-pagination token on left rooms", function(done) { - var syncData = { + let syncData = { next_batch: "batch_token", rooms: { - leave: {} + leave: {}, }, }; @@ -658,7 +657,7 @@ describe("MatrixClient syncing", function() { timeline: { events: [ utils.mkMessage({ - room: roomTwo, user: otherUserId, msg: "hello" + room: roomTwo, user: otherUserId, msg: "hello", }), ], prev_batch: "pagTok", @@ -666,14 +665,14 @@ describe("MatrixClient syncing", function() { }; httpBackend.when("POST", "/filter").respond(200, { - filter_id: "another_id" + filter_id: "another_id", }); httpBackend.when("GET", "/sync").respond(200, syncData); client.syncLeftRooms().then(function() { - var room = client.getRoom(roomTwo); - var tok = room.getLiveTimeline().getPaginationToken( + let room = client.getRoom(roomTwo); + let tok = room.getLiveTimeline().getPaginationToken( EventTimeline.BACKWARDS); expect(tok).toEqual("pagTok"); diff --git a/spec/integ/megolm.spec.js b/spec/integ/megolm.spec.js index c8eb07ac8..c4531765c 100644 --- a/spec/integ/megolm.spec.js +++ b/spec/integ/megolm.spec.js @@ -21,15 +21,15 @@ try { var Olm = require('olm'); } catch (e) {} -var anotherjson = require('another-json'); -var q = require('q'); +let anotherjson = require('another-json'); +let q = require('q'); -var sdk = require('../..'); -var utils = require('../../lib/utils'); -var test_utils = require('../test-utils'); -var MockHttpBackend = require('../mock-request'); +let sdk = require('../..'); +let utils = require('../../lib/utils'); +let test_utils = require('../test-utils'); +let MockHttpBackend = require('../mock-request'); -var ROOM_ID = "!room:id"; +let ROOM_ID = "!room:id"; /** * Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient @@ -66,14 +66,14 @@ function TestClient(userId, deviceId, accessToken) { * @return {Promise} */ TestClient.prototype.start = function(existingDevices) { - var self = this; + let self = this; this.httpBackend.when("GET", "/pushrules").respond(200, {}); this.httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" }); this.httpBackend.when('POST', '/keys/query').respond(200, function(path, content) { expect(content.device_keys[self.userId]).toEqual({}); - var res = existingDevices; + let res = existingDevices; if (!res) { res = { device_keys: {} }; res.device_keys[self.userId] = {}; @@ -92,7 +92,7 @@ TestClient.prototype.start = function(existingDevices) { expect(content.one_time_keys).not.toEqual({}); self.oneTimeKeys = content.one_time_keys; return {one_time_key_counts: { - signed_curve25519: utils.keys(self.oneTimeKeys).length + signed_curve25519: utils.keys(self.oneTimeKeys).length, }}; }); @@ -114,7 +114,7 @@ TestClient.prototype.stop = function() { * @return {string} base64 device key */ TestClient.prototype.getDeviceKey = function() { - var key_id = 'curve25519:' + this.deviceId; + let key_id = 'curve25519:' + this.deviceId; return this.deviceKeys.keys[key_id]; }; @@ -125,7 +125,7 @@ TestClient.prototype.getDeviceKey = function() { * @return {string} base64 device key */ TestClient.prototype.getSigningKey = function() { - var key_id = 'ed25519:' + this.deviceId; + let key_id = 'ed25519:' + this.deviceId; return this.deviceKeys.keys[key_id]; }; @@ -137,10 +137,10 @@ TestClient.prototype.getSigningKey = function() { * @return {Olm.Session} */ function createOlmSession(olmAccount, recipientTestClient) { - var otk_id = utils.keys(recipientTestClient.oneTimeKeys)[0]; - var otk = recipientTestClient.oneTimeKeys[otk_id]; + let otk_id = utils.keys(recipientTestClient.oneTimeKeys)[0]; + let otk = recipientTestClient.oneTimeKeys[otk_id]; - var session = new Olm.Session(); + let session = new Olm.Session(); session.create_outbound( olmAccount, recipientTestClient.getDeviceKey(), otk.key ); @@ -165,7 +165,7 @@ function encryptOlmEvent(opts) { expect(opts.p2pSession).toBeDefined(); expect(opts.recipient).toBeDefined(); - var plaintext = { + let plaintext = { content: opts.plaincontent || {}, recipient: opts.recipient.userId, recipient_keys: { @@ -175,7 +175,7 @@ function encryptOlmEvent(opts) { type: opts.plaintype || 'm.test', }; - var event = { + let event = { content: { algorithm: 'm.olm.v1.curve25519-aes-sha2', ciphertext: {}, @@ -204,7 +204,7 @@ function encryptMegolmEvent(opts) { expect(opts.senderKey).toBeDefined(); expect(opts.groupSession).toBeDefined(); - var plaintext = opts.plaintext || {}; + let plaintext = opts.plaintext || {}; if (!plaintext.content) { plaintext.content = { body: '42', @@ -267,7 +267,7 @@ function encryptGroupSessionKey(opts) { * @return {object} event */ function getSyncResponse(roomMembers) { - var roomResponse = { + let roomResponse = { state: { events: [ test_utils.mkEvent({ @@ -278,10 +278,10 @@ function getSyncResponse(roomMembers) { }, }), ], - } + }, }; - for (var i = 0; i < roomMembers.length; i++) { + for (let i = 0; i < roomMembers.length; i++) { roomResponse.state.events.push( test_utils.mkMembership({ mship: 'join', @@ -290,7 +290,7 @@ function getSyncResponse(roomMembers) { ); } - var syncResponse = { + let syncResponse = { next_batch: 1, rooms: { join: {}, @@ -306,9 +306,9 @@ describe("megolm", function() { return; } - var testOlmAccount; - var testSenderKey; - var aliceTestClient; + let testOlmAccount; + let testSenderKey; + let aliceTestClient; /** * Get the device keys for testOlmAccount in a format suitable for a @@ -318,8 +318,8 @@ describe("megolm", function() { * @returns {Object} The fake query response */ function getTestKeysQueryResponse(userId) { - var testE2eKeys = JSON.parse(testOlmAccount.identity_keys()); - var testDeviceKeys = { + let testE2eKeys = JSON.parse(testOlmAccount.identity_keys()); + let testDeviceKeys = { algorithms: ['m.olm.v1.curve25519-aes-sha2', 'm.megolm.v1.aes-sha2'], device_id: 'DEVICE_ID', keys: { @@ -328,14 +328,14 @@ describe("megolm", function() { }, user_id: userId, }; - var j = anotherjson.stringify(testDeviceKeys); - var sig = testOlmAccount.sign(j); + let j = anotherjson.stringify(testDeviceKeys); + let sig = testOlmAccount.sign(j); testDeviceKeys.signatures = {}; testDeviceKeys.signatures[userId] = { 'ed25519:DEVICE_ID': sig, }; - var queryResponse = { + let queryResponse = { device_keys: {}, }; @@ -355,22 +355,22 @@ describe("megolm", function() { */ function getTestKeysClaimResponse(userId) { testOlmAccount.generate_one_time_keys(1); - var testOneTimeKeys = JSON.parse(testOlmAccount.one_time_keys()); + let testOneTimeKeys = JSON.parse(testOlmAccount.one_time_keys()); testOlmAccount.mark_keys_as_published(); - var keyId = utils.keys(testOneTimeKeys.curve25519)[0]; - var oneTimeKey = testOneTimeKeys.curve25519[keyId]; - var keyResult = { + let keyId = utils.keys(testOneTimeKeys.curve25519)[0]; + let oneTimeKey = testOneTimeKeys.curve25519[keyId]; + let keyResult = { 'key': oneTimeKey, }; - var j = anotherjson.stringify(keyResult); - var sig = testOlmAccount.sign(j); + let j = anotherjson.stringify(keyResult); + let sig = testOlmAccount.sign(j); keyResult.signatures = {}; keyResult.signatures[userId] = { 'ed25519:DEVICE_ID': sig, }; - var claimResponse = {one_time_keys: {}}; + let claimResponse = {one_time_keys: {}}; claimResponse.one_time_keys[userId] = { 'DEVICE_ID': {}, }; @@ -388,7 +388,7 @@ describe("megolm", function() { testOlmAccount = new Olm.Account(); testOlmAccount.create(); - var testE2eKeys = JSON.parse(testOlmAccount.identity_keys()); + let testE2eKeys = JSON.parse(testOlmAccount.identity_keys()); testSenderKey = testE2eKeys.curve25519; }); @@ -398,13 +398,13 @@ describe("megolm", function() { it("Alice receives a megolm message", function(done) { return aliceTestClient.start().then(function() { - var p2pSession = createOlmSession(testOlmAccount, aliceTestClient); + let p2pSession = createOlmSession(testOlmAccount, aliceTestClient); - var groupSession = new Olm.OutboundGroupSession(); + let groupSession = new Olm.OutboundGroupSession(); groupSession.create(); // make the room_key event - var roomKeyEncrypted = encryptGroupSessionKey({ + let roomKeyEncrypted = encryptGroupSessionKey({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -413,14 +413,14 @@ describe("megolm", function() { }); // encrypt a message with the group session - var messageEncrypted = encryptMegolmEvent({ + let messageEncrypted = encryptMegolmEvent({ senderKey: testSenderKey, groupSession: groupSession, room_id: ROOM_ID, }); // Alice gets both the events in a single sync - var syncResponse = { + let syncResponse = { next_batch: 1, to_device: { events: [roomKeyEncrypted], @@ -438,21 +438,21 @@ describe("megolm", function() { aliceTestClient.httpBackend.when("GET", "/sync").respond(200, syncResponse); return aliceTestClient.httpBackend.flush("/sync", 1); }).then(function() { - var room = aliceTestClient.client.getRoom(ROOM_ID); - var event = room.getLiveTimeline().getEvents()[0]; + let room = aliceTestClient.client.getRoom(ROOM_ID); + let event = room.getLiveTimeline().getEvents()[0]; expect(event.getContent().body).toEqual('42'); }).nodeify(done); }); it("Alice gets a second room_key message", function(done) { return aliceTestClient.start().then(function() { - var p2pSession = createOlmSession(testOlmAccount, aliceTestClient); + let p2pSession = createOlmSession(testOlmAccount, aliceTestClient); - var groupSession = new Olm.OutboundGroupSession(); + let groupSession = new Olm.OutboundGroupSession(); groupSession.create(); // make the room_key event - var roomKeyEncrypted1 = encryptGroupSessionKey({ + let roomKeyEncrypted1 = encryptGroupSessionKey({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -461,7 +461,7 @@ describe("megolm", function() { }); // encrypt a message with the group session - var messageEncrypted = encryptMegolmEvent({ + let messageEncrypted = encryptMegolmEvent({ senderKey: testSenderKey, groupSession: groupSession, room_id: ROOM_ID, @@ -469,7 +469,7 @@ describe("megolm", function() { // make a second room_key event now that we have advanced the group // session. - var roomKeyEncrypted2 = encryptGroupSessionKey({ + let roomKeyEncrypted2 = encryptGroupSessionKey({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -488,7 +488,7 @@ describe("megolm", function() { // on the second sync, send the advanced room key, along with the // message. This simulates the situation where Alice has been sent a // later copy of the room key and is reloading the client. - var syncResponse2 = { + let syncResponse2 = { next_batch: 2, to_device: { events: [roomKeyEncrypted2], @@ -506,22 +506,22 @@ describe("megolm", function() { return aliceTestClient.httpBackend.flush("/sync", 2); }).then(function() { - var room = aliceTestClient.client.getRoom(ROOM_ID); - var event = room.getLiveTimeline().getEvents()[0]; + let room = aliceTestClient.client.getRoom(ROOM_ID); + let event = room.getLiveTimeline().getEvents()[0]; expect(event.getContent().body).toEqual('42'); }).nodeify(done); }); it('Alice sends a megolm message', function(done) { - var p2pSession; + let p2pSession; return aliceTestClient.start().then(function() { - var syncResponse = getSyncResponse(['@bob:xyz']); + let syncResponse = getSyncResponse(['@bob:xyz']); // establish an olm session with alice p2pSession = createOlmSession(testOlmAccount, aliceTestClient); - var olmEvent = encryptOlmEvent({ + let olmEvent = encryptOlmEvent({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -532,7 +532,7 @@ describe("megolm", function() { aliceTestClient.httpBackend.when('GET', '/sync').respond(200, syncResponse); return aliceTestClient.httpBackend.flush('/sync', 1); }).then(function() { - var inboundGroupSession; + let inboundGroupSession; aliceTestClient.httpBackend.when('POST', '/keys/query').respond( 200, getTestKeysQueryResponse('@bob:xyz') ); @@ -540,9 +540,9 @@ describe("megolm", function() { aliceTestClient.httpBackend.when( 'PUT', '/sendToDevice/m.room.encrypted/' ).respond(200, function(path, content) { - var m = content.messages['@bob:xyz'].DEVICE_ID; - var ct = m.ciphertext[testSenderKey]; - var decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); + let m = content.messages['@bob:xyz'].DEVICE_ID; + let ct = m.ciphertext[testSenderKey]; + let decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); expect(decrypted.type).toEqual('m.room_key'); inboundGroupSession = new Olm.InboundGroupSession(); @@ -553,12 +553,12 @@ describe("megolm", function() { aliceTestClient.httpBackend.when( 'PUT', '/send/' ).respond(200, function(path, content) { - var ct = content.ciphertext; - var r = inboundGroupSession.decrypt(ct); + let ct = content.ciphertext; + let r = inboundGroupSession.decrypt(ct); console.log('Decrypted received megolm message', r); expect(r.message_index).toEqual(0); - var decrypted = JSON.parse(r.plaintext); + let decrypted = JSON.parse(r.plaintext); expect(decrypted.type).toEqual('m.room.message'); expect(decrypted.content.body).toEqual('test'); @@ -576,7 +576,7 @@ describe("megolm", function() { it("Alice shouldn't do a second /query for non-e2e-capable devices", function(done) { return aliceTestClient.start().then(function() { - var syncResponse = getSyncResponse(['@bob:xyz']); + let syncResponse = getSyncResponse(['@bob:xyz']); aliceTestClient.httpBackend.when('GET', '/sync').respond(200, syncResponse); return aliceTestClient.httpBackend.flush('/sync', 1); @@ -586,7 +586,7 @@ describe("megolm", function() { aliceTestClient.httpBackend.when('POST', '/keys/query').respond(200, { device_keys: { '@bob:xyz': {}, - } + }, }); return q.all([ @@ -612,12 +612,12 @@ describe("megolm", function() { it("We shouldn't attempt to send to blocked devices", function(done) { return aliceTestClient.start().then(function() { - var syncResponse = getSyncResponse(['@bob:xyz']); + let syncResponse = getSyncResponse(['@bob:xyz']); // establish an olm session with alice - var p2pSession = createOlmSession(testOlmAccount, aliceTestClient); + let p2pSession = createOlmSession(testOlmAccount, aliceTestClient); - var olmEvent = encryptOlmEvent({ + let olmEvent = encryptOlmEvent({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -657,16 +657,16 @@ describe("megolm", function() { }); it("We should start a new megolm session when a device is blocked", function(done) { - var p2pSession; - var megolmSessionId; + let p2pSession; + let megolmSessionId; return aliceTestClient.start().then(function() { - var syncResponse = getSyncResponse(['@bob:xyz']); + let syncResponse = getSyncResponse(['@bob:xyz']); // establish an olm session with alice p2pSession = createOlmSession(testOlmAccount, aliceTestClient); - var olmEvent = encryptOlmEvent({ + let olmEvent = encryptOlmEvent({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -687,10 +687,10 @@ describe("megolm", function() { 'PUT', '/sendToDevice/m.room.encrypted/' ).respond(200, function(path, content) { console.log('sendToDevice: ', content); - var m = content.messages['@bob:xyz'].DEVICE_ID; - var ct = m.ciphertext[testSenderKey]; + let m = content.messages['@bob:xyz'].DEVICE_ID; + let ct = m.ciphertext[testSenderKey]; expect(ct.type).toEqual(1); // normal message - var decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); + let decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); console.log('decrypted sendToDevice:', decrypted); expect(decrypted.type).toEqual('m.room_key'); megolmSessionId = decrypted.content.session_id; @@ -738,15 +738,15 @@ describe("megolm", function() { // for this test, we make the testOlmAccount be another of Alice's devices. // it ought to get include in messages Alice sends. - var p2pSession; - var inboundGroupSession; - var decrypted; + let p2pSession; + let inboundGroupSession; + let decrypted; return aliceTestClient.start( getTestKeysQueryResponse(aliceTestClient.userId) ).then(function() { // an encrypted room with just alice - var syncResponse = { + let syncResponse = { next_batch: 1, rooms: { join: {}, @@ -774,8 +774,7 @@ describe("megolm", function() { return aliceTestClient.httpBackend.flush(); }).then(function() { aliceTestClient.httpBackend.when('POST', '/keys/claim').respond( - 200, function(path, content) - { + 200, function(path, content) { expect(content.one_time_keys[aliceTestClient.userId].DEVICE_ID) .toEqual("signed_curve25519"); return getTestKeysClaimResponse(aliceTestClient.userId); @@ -785,13 +784,13 @@ describe("megolm", function() { 'PUT', '/sendToDevice/m.room.encrypted/' ).respond(200, function(path, content) { console.log("sendToDevice: ", content); - var m = content.messages[aliceTestClient.userId].DEVICE_ID; - var ct = m.ciphertext[testSenderKey]; + let m = content.messages[aliceTestClient.userId].DEVICE_ID; + let ct = m.ciphertext[testSenderKey]; expect(ct.type).toEqual(0); // pre-key message p2pSession = new Olm.Session(); p2pSession.create_inbound(testOlmAccount, ct.body); - var decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); + let decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); expect(decrypted.type).toEqual('m.room_key'); inboundGroupSession = new Olm.InboundGroupSession(); @@ -802,8 +801,8 @@ describe("megolm", function() { aliceTestClient.httpBackend.when( 'PUT', '/send/' ).respond(200, function(path, content) { - var ct = content.ciphertext; - var r = inboundGroupSession.decrypt(ct); + let ct = content.ciphertext; + let r = inboundGroupSession.decrypt(ct); console.log('Decrypted received megolm message', r); decrypted = JSON.parse(r.plaintext); @@ -825,18 +824,18 @@ describe("megolm", function() { it('Alice should wait for device list to complete when sending a megolm message', function(done) { - var p2pSession; - var inboundGroupSession; + let p2pSession; + let inboundGroupSession; - var downloadPromise; - var sendPromise; + let downloadPromise; + let sendPromise; aliceTestClient.httpBackend.when( 'PUT', '/sendToDevice/m.room.encrypted/' ).respond(200, function(path, content) { - var m = content.messages['@bob:xyz'].DEVICE_ID; - var ct = m.ciphertext[testSenderKey]; - var decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); + let m = content.messages['@bob:xyz'].DEVICE_ID; + let ct = m.ciphertext[testSenderKey]; + let decrypted = JSON.parse(p2pSession.decrypt(ct.type, ct.body)); expect(decrypted.type).toEqual('m.room_key'); inboundGroupSession = new Olm.InboundGroupSession(); @@ -847,12 +846,12 @@ describe("megolm", function() { aliceTestClient.httpBackend.when( 'PUT', '/send/' ).respond(200, function(path, content) { - var ct = content.ciphertext; - var r = inboundGroupSession.decrypt(ct); + let ct = content.ciphertext; + let r = inboundGroupSession.decrypt(ct); console.log('Decrypted received megolm message', r); expect(r.message_index).toEqual(0); - var decrypted = JSON.parse(r.plaintext); + let decrypted = JSON.parse(r.plaintext); expect(decrypted.type).toEqual('m.room.message'); expect(decrypted.content.body).toEqual('test'); @@ -862,12 +861,12 @@ describe("megolm", function() { }); return aliceTestClient.start().then(function() { - var syncResponse = getSyncResponse(['@bob:xyz']); + let syncResponse = getSyncResponse(['@bob:xyz']); // establish an olm session with alice p2pSession = createOlmSession(testOlmAccount, aliceTestClient); - var olmEvent = encryptOlmEvent({ + let olmEvent = encryptOlmEvent({ senderKey: testSenderKey, recipient: aliceTestClient, p2pSession: p2pSession, @@ -883,7 +882,6 @@ describe("megolm", function() { // this will block downloadPromise = aliceTestClient.client.downloadKeys(['@bob:xyz']); }).then(function() { - // so will this. sendPromise = aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'); }).then(function() { diff --git a/spec/mock-request.js b/spec/mock-request.js index 3c7dda10d..b8e644218 100644 --- a/spec/mock-request.js +++ b/spec/mock-request.js @@ -1,5 +1,5 @@ "use strict"; -var q = require("q"); +let q = require("q"); /** * Construct a mock HTTP backend, heavily inspired by Angular.js. @@ -8,15 +8,15 @@ var q = require("q"); function HttpBackend() { this.requests = []; this.expectedRequests = []; - var self = this; + let self = this; // the request function dependency that the SDK needs. this.requestFn = function(opts, callback) { - var req = new Request(opts, callback); + let req = new Request(opts, callback); console.log("HTTP backend received request: %s", req); self.requests.push(req); - var abort = function() { - var idx = self.requests.indexOf(req); + let abort = function() { + let idx = self.requests.indexOf(req); if (idx >= 0) { console.log("Aborting HTTP request: %s %s", opts.method, opts.uri); @@ -26,7 +26,7 @@ function HttpBackend() { }; return { - abort: abort + abort: abort, }; }; } @@ -38,14 +38,14 @@ HttpBackend.prototype = { * @return {Promise} resolved when there is nothing left to flush. */ flush: function(path, numToFlush) { - var defer = q.defer(); - var self = this; - var flushed = 0; - var triedWaiting = false; + let defer = q.defer(); + let self = this; + let flushed = 0; + let triedWaiting = false; console.log( "HTTP backend flushing... (path=%s numToFlush=%s)", path, numToFlush ); - var tryFlush = function() { + let tryFlush = function() { // if there's more real requests and more expected requests, flush 'em. console.log( " trying to flush queue => reqs=%s expected=%s [%s]", @@ -58,18 +58,15 @@ HttpBackend.prototype = { if (numToFlush && flushed === numToFlush) { console.log(" [%s] Flushed assigned amount: %s", path, numToFlush); defer.resolve(); - } - else { + } else { setTimeout(tryFlush, 0); } - } - else if (flushed === 0 && !triedWaiting) { + } else if (flushed === 0 && !triedWaiting) { // we may not have made the request yet, wait a generous amount of // time before giving up. setTimeout(tryFlush, 5); triedWaiting = true; - } - else { + } else { console.log(" no more flushes. [%s]", path); defer.resolve(); } @@ -86,14 +83,16 @@ HttpBackend.prototype = { * @return {boolean} true if something was resolved. */ _takeFromQueue: function(path) { - var req = null; - var i, j; - var matchingReq, expectedReq, testResponse = null; + let req = null; + let i, j; + let matchingReq, expectedReq, testResponse = null; for (i = 0; i < this.requests.length; i++) { req = this.requests[i]; for (j = 0; j < this.expectedRequests.length; j++) { expectedReq = this.expectedRequests[j]; - if (path && path !== expectedReq.path) { continue; } + if (path && path !== expectedReq.path) { + continue; +} if (expectedReq.method === req.method && req.path.indexOf(expectedReq.path) !== -1) { if (!expectedReq.data || (JSON.stringify(expectedReq.data) === @@ -115,7 +114,7 @@ HttpBackend.prototype = { } testResponse = matchingReq.response; console.log(" responding to %s", matchingReq.path); - var body = testResponse.body; + let body = testResponse.body; if (Object.prototype.toString.call(body) == "[object Function]") { body = body(req.path, req.data); } @@ -135,7 +134,7 @@ HttpBackend.prototype = { * Makes sure that the SDK hasn't sent any more requests to the backend. */ verifyNoOutstandingRequests: function() { - var firstOutstandingReq = this.requests[0] || {}; + let firstOutstandingReq = this.requests[0] || {}; expect(this.requests.length).toEqual(0, "Expected no more HTTP requests but received request to " + firstOutstandingReq.path @@ -146,7 +145,7 @@ HttpBackend.prototype = { * Makes sure that the test doesn't have any unresolved requests. */ verifyNoOutstandingExpectation: function() { - var firstOutstandingExpectation = this.expectedRequests[0] || {}; + let firstOutstandingExpectation = this.expectedRequests[0] || {}; expect(this.expectedRequests.length).toEqual(0, "Expected to see HTTP request for " + firstOutstandingExpectation.path ); @@ -160,10 +159,10 @@ HttpBackend.prototype = { * @return {Request} An expected request. */ when: function(method, path, data) { - var pendingReq = new ExpectedRequest(method, path, data); + let pendingReq = new ExpectedRequest(method, path, data); this.expectedRequests.push(pendingReq); return pendingReq; - } + }, }; /** @@ -206,10 +205,10 @@ ExpectedRequest.prototype = { this.response = { response: { statusCode: code, - headers: {} + headers: {}, }, body: data, - err: null + err: null, }; }, @@ -222,12 +221,12 @@ ExpectedRequest.prototype = { this.response = { response: { statusCode: code, - headers: {} + headers: {}, }, body: null, - err: err + err: err, }; - } + }, }; /** @@ -242,23 +241,33 @@ function Request(opts, callback) { this.callback = callback; Object.defineProperty(this, 'method', { - get: function() { return opts.method; } + get: function() { + return opts.method; +}, }); Object.defineProperty(this, 'path', { - get: function() { return opts.uri; } + get: function() { + return opts.uri; +}, }); Object.defineProperty(this, 'data', { - get: function() { return opts.body; } + get: function() { + return opts.body; +}, }); Object.defineProperty(this, 'queryParams', { - get: function() { return opts.qs; } + get: function() { + return opts.qs; +}, }); Object.defineProperty(this, 'headers', { - get: function() { return opts.headers || {}; } + get: function() { + return opts.headers || {}; +}, }); } diff --git a/spec/test-utils.js b/spec/test-utils.js index 78deb5642..107a70b16 100644 --- a/spec/test-utils.js +++ b/spec/test-utils.js @@ -1,6 +1,6 @@ "use strict"; -var sdk = require(".."); -var MatrixEvent = sdk.MatrixEvent; +let sdk = require(".."); +let MatrixEvent = sdk.MatrixEvent; /** * Perform common actions before each test case, e.g. printing the test case @@ -8,7 +8,7 @@ var MatrixEvent = sdk.MatrixEvent; * @param {TestCase} testCase The test case that is about to be run. */ module.exports.beforeEach = function(testCase) { - var desc = testCase.suite.description + " : " + testCase.description; + let desc = testCase.suite.description + " : " + testCase.description; console.log(desc); console.log(new Array(1 + desc.length).join("=")); }; @@ -22,19 +22,18 @@ module.exports.beforeEach = function(testCase) { module.exports.mock = function(constr, name) { // By Tim Buschtöns // http://eclipsesource.com/blogs/2014/03/27/mocks-in-jasmine-tests/ - var HelperConstr = new Function(); // jshint ignore:line + let HelperConstr = new Function(); // jshint ignore:line HelperConstr.prototype = constr.prototype; - var result = new HelperConstr(); + let result = new HelperConstr(); result.jasmineToString = function() { return "mock" + (name ? " of " + name : ""); }; - for (var key in constr.prototype) { // eslint-disable-line guard-for-in + for (let key in constr.prototype) { // eslint-disable-line guard-for-in try { if (constr.prototype[key] instanceof Function) { result[key] = jasmine.createSpy((name || "mock") + '.' + key); } - } - catch (ex) { + } catch (ex) { // Direct access to some non-function fields of DOM prototypes may // cause exceptions. // Overwriting will not work either in that case. @@ -58,17 +57,16 @@ module.exports.mkEvent = function(opts) { if (!opts.type || !opts.content) { throw new Error("Missing .type or .content =>" + JSON.stringify(opts)); } - var event = { + let event = { type: opts.type, room_id: opts.room, sender: opts.sender || opts.user, // opts.user for backwards-compat content: opts.content, - event_id: "$" + Math.random() + "-" + Math.random() + event_id: "$" + Math.random() + "-" + Math.random(), }; if (opts.skey !== undefined) { event.state_key = opts.skey; - } - else if (["m.room.name", "m.room.topic", "m.room.create", "m.room.join_rules", + } else if (["m.room.name", "m.room.topic", "m.room.create", "m.room.join_rules", "m.room.power_levels", "m.room.topic", "com.example.state"].indexOf(opts.type) !== -1) { event.state_key = ""; @@ -85,7 +83,7 @@ module.exports.mkPresence = function(opts) { if (!opts.user) { throw new Error("Missing user"); } - var event = { + let event = { event_id: "$" + Math.random() + "-" + Math.random(), type: "m.presence", sender: opts.sender || opts.user, // opts.user for backwards-compat @@ -93,8 +91,8 @@ module.exports.mkPresence = function(opts) { avatar_url: opts.url, displayname: opts.name, last_active_ago: opts.ago, - presence: opts.presence || "offline" - } + presence: opts.presence || "offline", + }, }; return opts.event ? new MatrixEvent(event) : event; }; @@ -121,10 +119,14 @@ module.exports.mkMembership = function(opts) { throw new Error("Missing .mship => " + JSON.stringify(opts)); } opts.content = { - membership: opts.mship + membership: opts.mship, }; - if (opts.name) { opts.content.displayname = opts.name; } - if (opts.url) { opts.content.avatar_url = opts.url; } + if (opts.name) { + opts.content.displayname = opts.name; +} + if (opts.url) { + opts.content.avatar_url = opts.url; +} return module.exports.mkEvent(opts); }; @@ -147,7 +149,7 @@ module.exports.mkMessage = function(opts) { } opts.content = { msgtype: "m.text", - body: opts.msg + body: opts.msg, }; return module.exports.mkEvent(opts); }; @@ -199,5 +201,5 @@ module.exports.MockStorageApi.prototype = { }, removeItem: function(k) { delete this.data[k]; - } + }, }; diff --git a/spec/unit/content-repo.spec.js b/spec/unit/content-repo.spec.js index 0d49b7ee8..de8e6fb3c 100644 --- a/spec/unit/content-repo.spec.js +++ b/spec/unit/content-repo.spec.js @@ -1,9 +1,9 @@ "use strict"; -var ContentRepo = require("../../lib/content-repo"); -var testUtils = require("../test-utils"); +let ContentRepo = require("../../lib/content-repo"); +let testUtils = require("../test-utils"); describe("ContentRepo", function() { - var baseUrl = "https://my.home.server"; + let baseUrl = "https://my.home.server"; beforeEach(function() { testUtils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -11,7 +11,7 @@ describe("ContentRepo", function() { describe("getHttpUriForMxc", function() { it("should do nothing to HTTP URLs when allowing direct links", function() { - var httpUrl = "http://example.com/image.jpeg"; + let httpUrl = "http://example.com/image.jpeg"; expect( ContentRepo.getHttpUriForMxc( baseUrl, httpUrl, undefined, undefined, undefined, true @@ -20,13 +20,13 @@ describe("ContentRepo", function() { }); it("should return the empty string HTTP URLs by default", function() { - var httpUrl = "http://example.com/image.jpeg"; + let httpUrl = "http://example.com/image.jpeg"; expect(ContentRepo.getHttpUriForMxc(baseUrl, httpUrl)).toEqual(""); }); it("should return a download URL if no width/height/resize are specified", function() { - var mxcUri = "mxc://server.name/resourceid"; + let mxcUri = "mxc://server.name/resourceid"; expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri)).toEqual( baseUrl + "/_matrix/media/v1/download/server.name/resourceid" ); @@ -38,7 +38,7 @@ describe("ContentRepo", function() { it("should return a thumbnail URL if a width/height/resize is specified", function() { - var mxcUri = "mxc://server.name/resourceid"; + let mxcUri = "mxc://server.name/resourceid"; expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32, 64, "crop")).toEqual( baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" + "?width=32&height=64&method=crop" @@ -47,7 +47,7 @@ describe("ContentRepo", function() { it("should put fragments from mxc:// URIs after any query parameters", function() { - var mxcUri = "mxc://server.name/resourceid#automade"; + let mxcUri = "mxc://server.name/resourceid#automade"; expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32)).toEqual( baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" + "?width=32#automade" @@ -56,7 +56,7 @@ describe("ContentRepo", function() { it("should put fragments from mxc:// URIs at the end of the HTTP URI", function() { - var mxcUri = "mxc://server.name/resourceid#automade"; + let mxcUri = "mxc://server.name/resourceid#automade"; expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri)).toEqual( baseUrl + "/_matrix/media/v1/download/server.name/resourceid#automade" ); diff --git a/spec/unit/crypto.spec.js b/spec/unit/crypto.spec.js index c26562406..bde8c6c8b 100644 --- a/spec/unit/crypto.spec.js +++ b/spec/unit/crypto.spec.js @@ -1,7 +1,7 @@ "use strict"; -var Crypto = require("../../lib/crypto"); -var sdk = require("../.."); +let Crypto = require("../../lib/crypto"); +let sdk = require("../.."); describe("Crypto", function() { if (!sdk.CRYPTO_ENABLED) { diff --git a/spec/unit/event-timeline.spec.js b/spec/unit/event-timeline.spec.js index 8868621e9..3fac91796 100644 --- a/spec/unit/event-timeline.spec.js +++ b/spec/unit/event-timeline.spec.js @@ -1,7 +1,7 @@ "use strict"; -var sdk = require("../.."); -var EventTimeline = sdk.EventTimeline; -var utils = require("../test-utils"); +let sdk = require("../.."); +let EventTimeline = sdk.EventTimeline; +let utils = require("../test-utils"); function mockRoomStates(timeline) { timeline._startState = utils.mock(sdk.RoomState, "startState"); @@ -9,24 +9,26 @@ function mockRoomStates(timeline) { } describe("EventTimeline", function() { - var roomId = "!foo:bar"; - var userA = "@alice:bar"; - var userB = "@bertha:bar"; - var timeline; + let roomId = "!foo:bar"; + let userA = "@alice:bar"; + let userB = "@bertha:bar"; + let timeline; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this // XXX: this is a horrid hack; should use sinon or something instead to mock - var timelineSet = { room: { roomId: roomId }}; - timelineSet.room.getUnfilteredTimelineSet = function() { return timelineSet; }; + let timelineSet = { room: { roomId: roomId }}; + timelineSet.room.getUnfilteredTimelineSet = function() { + return timelineSet; +}; timeline = new EventTimeline(timelineSet); }); describe("construction", function() { it("getRoomId should get room id", function() { - var v = timeline.getRoomId(); + let v = timeline.getRoomId(); expect(v).toEqual(roomId); }); }); @@ -37,7 +39,7 @@ describe("EventTimeline", function() { }); it("should copy state events to start and end state", function() { - var events = [ + let events = [ utils.mkMembership({ room: roomId, mship: "invite", user: userB, skey: userA, event: true, @@ -46,7 +48,7 @@ describe("EventTimeline", function() { type: "m.room.name", room: roomId, user: userB, event: true, content: { name: "New room" }, - }) + }), ]; timeline.initialiseState(events); expect(timeline._startState.setStateEvents).toHaveBeenCalledWith( @@ -58,22 +60,26 @@ describe("EventTimeline", function() { }); it("should raise an exception if called after events are added", function() { - var event = + let event = utils.mkMessage({ room: roomId, user: userA, msg: "Adam stole the plushies", event: true, }); - var state = [ + let state = [ utils.mkMembership({ room: roomId, mship: "invite", user: userB, skey: userA, event: true, - }) + }), ]; - expect(function() { timeline.initialiseState(state); }).not.toThrow(); + expect(function() { + timeline.initialiseState(state); +}).not.toThrow(); timeline.addEvent(event, false); - expect(function() { timeline.initialiseState(state); }).toThrow(); + expect(function() { + timeline.initialiseState(state); +}).toThrow(); }); }); @@ -99,8 +105,8 @@ describe("EventTimeline", function() { }); it("setNeighbouringTimeline should set neighbour", function() { - var prev = {a: "a"}; - var next = {b: "b"}; + let prev = {a: "a"}; + let next = {b: "b"}; timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS); timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS); expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)).toBe(prev); @@ -108,8 +114,8 @@ describe("EventTimeline", function() { }); it("setNeighbouringTimeline should throw if called twice", function() { - var prev = {a: "a"}; - var next = {b: "b"}; + let prev = {a: "a"}; + let next = {b: "b"}; expect(function() { timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS); }).not.toThrow(); @@ -135,7 +141,7 @@ describe("EventTimeline", function() { mockRoomStates(timeline); }); - var events = [ + let events = [ utils.mkMessage({ room: roomId, user: userA, msg: "hungry hungry hungry", event: true, @@ -148,7 +154,7 @@ describe("EventTimeline", function() { it("should be able to add events to the end", function() { timeline.addEvent(events[0], false); - var initialIndex = timeline.getBaseIndex(); + let initialIndex = timeline.getBaseIndex(); timeline.addEvent(events[1], false); expect(timeline.getBaseIndex()).toEqual(initialIndex); expect(timeline.getEvents().length).toEqual(2); @@ -158,7 +164,7 @@ describe("EventTimeline", function() { it("should be able to add events to the start", function() { timeline.addEvent(events[0], true); - var initialIndex = timeline.getBaseIndex(); + let initialIndex = timeline.getBaseIndex(); timeline.addEvent(events[1], true); expect(timeline.getBaseIndex()).toEqual(initialIndex + 1); expect(timeline.getEvents().length).toEqual(2); @@ -167,15 +173,15 @@ describe("EventTimeline", function() { }); it("should set event.sender for new and old events", function() { - var sentinel = { + let sentinel = { userId: userA, membership: "join", - name: "Alice" + name: "Alice", }; - var oldSentinel = { + let oldSentinel = { userId: userA, membership: "join", - name: "Old Alice" + name: "Old Alice", }; timeline.getState(EventTimeline.FORWARDS).getSentinelMember .andCallFake(function(uid) { @@ -192,13 +198,13 @@ describe("EventTimeline", function() { return null; }); - var newEv = utils.mkEvent({ + let newEv = utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "New Room Name" } + content: { name: "New Room Name" }, }); - var oldEv = utils.mkEvent({ + let oldEv = utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "Old Room Name" } + content: { name: "Old Room Name" }, }); timeline.addEvent(newEv, false); @@ -209,15 +215,15 @@ describe("EventTimeline", function() { it("should set event.target for new and old m.room.member events", function() { - var sentinel = { + let sentinel = { userId: userA, membership: "join", - name: "Alice" + name: "Alice", }; - var oldSentinel = { + let oldSentinel = { userId: userA, membership: "join", - name: "Old Alice" + name: "Old Alice", }; timeline.getState(EventTimeline.FORWARDS).getSentinelMember .andCallFake(function(uid) { @@ -234,11 +240,11 @@ describe("EventTimeline", function() { return null; }); - var newEv = utils.mkMembership({ - room: roomId, mship: "invite", user: userB, skey: userA, event: true + let newEv = utils.mkMembership({ + room: roomId, mship: "invite", user: userB, skey: userA, event: true, }); - var oldEv = utils.mkMembership({ - room: roomId, mship: "ban", user: userB, skey: userA, event: true + let oldEv = utils.mkMembership({ + room: roomId, mship: "ban", user: userB, skey: userA, event: true, }); timeline.addEvent(newEv, false); expect(newEv.target).toEqual(sentinel); @@ -248,16 +254,16 @@ describe("EventTimeline", function() { it("should call setStateEvents on the right RoomState with the right " + "forwardLooking value for new events", function() { - var events = [ + let events = [ utils.mkMembership({ - room: roomId, mship: "invite", user: userB, skey: userA, event: true + room: roomId, mship: "invite", user: userB, skey: userA, event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userB, event: true, content: { - name: "New room" - } - }) + name: "New room", + }, + }), ]; timeline.addEvent(events[0], false); @@ -278,16 +284,16 @@ describe("EventTimeline", function() { it("should call setStateEvents on the right RoomState with the right " + "forwardLooking value for old events", function() { - var events = [ + let events = [ utils.mkMembership({ - room: roomId, mship: "invite", user: userB, skey: userA, event: true + room: roomId, mship: "invite", user: userB, skey: userA, event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userB, event: true, content: { - name: "New room" - } - }) + name: "New room", + }, + }), ]; timeline.addEvent(events[0], true); @@ -307,7 +313,7 @@ describe("EventTimeline", function() { }); describe("removeEvent", function() { - var events = [ + let events = [ utils.mkMessage({ room: roomId, user: userA, msg: "hungry hungry hungry", event: true, @@ -327,7 +333,7 @@ describe("EventTimeline", function() { timeline.addEvent(events[1], false); expect(timeline.getEvents().length).toEqual(2); - var ev = timeline.removeEvent(events[0].getId()); + let ev = timeline.removeEvent(events[0].getId()); expect(ev).toBe(events[0]); expect(timeline.getEvents().length).toEqual(1); @@ -359,7 +365,7 @@ describe("EventTimeline", function() { function() { timeline.addEvent(events[0], true); timeline.removeEvent(events[0].getId()); - var initialIndex = timeline.getBaseIndex(); + let initialIndex = timeline.getBaseIndex(); timeline.addEvent(events[1], false); timeline.addEvent(events[2], false); expect(timeline.getBaseIndex()).toEqual(initialIndex); diff --git a/spec/unit/filter.spec.js b/spec/unit/filter.spec.js index 909d87c20..527db651f 100644 --- a/spec/unit/filter.spec.js +++ b/spec/unit/filter.spec.js @@ -1,12 +1,12 @@ "use strict"; -var sdk = require("../.."); -var Filter = sdk.Filter; -var utils = require("../test-utils"); +let sdk = require("../.."); +let Filter = sdk.Filter; +let utils = require("../test-utils"); describe("Filter", function() { - var filterId = "f1lt3ring15g00d4ursoul"; - var userId = "@sir_arthur_david:humming.tiger"; - var filter; + let filterId = "f1lt3ring15g00d4ursoul"; + let userId = "@sir_arthur_david:humming.tiger"; + let filter; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -15,10 +15,10 @@ describe("Filter", function() { describe("fromJson", function() { it("create a new Filter from the provided values", function() { - var definition = { - event_fields: ["type", "content"] + let definition = { + event_fields: ["type", "content"], }; - var f = Filter.fromJson(userId, filterId, definition); + let f = Filter.fromJson(userId, filterId, definition); expect(f.getDefinition()).toEqual(definition); expect(f.userId).toEqual(userId); expect(f.filterId).toEqual(filterId); @@ -31,17 +31,17 @@ describe("Filter", function() { expect(filter.getDefinition()).toEqual({ room: { timeline: { - limit: 10 - } - } + limit: 10, + }, + }, }); }); }); describe("setDefinition/getDefinition", function() { it("should set and get the filter body", function() { - var definition = { - event_format: "client" + let definition = { + event_format: "client", }; filter.setDefinition(definition); expect(filter.getDefinition()).toEqual(definition); diff --git a/spec/unit/interactive-auth.spec.js b/spec/unit/interactive-auth.spec.js index 103c0bad9..b03dd0629 100644 --- a/spec/unit/interactive-auth.spec.js +++ b/spec/unit/interactive-auth.spec.js @@ -15,12 +15,12 @@ limitations under the License. */ "use strict"; -var q = require("q"); -var sdk = require("../.."); -var utils = require("../test-utils"); +let q = require("q"); +let sdk = require("../.."); +let utils = require("../test-utils"); -var InteractiveAuth = sdk.InteractiveAuth; -var MatrixError = sdk.MatrixError; +let InteractiveAuth = sdk.InteractiveAuth; +let MatrixError = sdk.MatrixError; describe("InteractiveAuth", function() { beforeEach(function() { @@ -28,10 +28,10 @@ describe("InteractiveAuth", function() { }); it("should start an auth stage and complete it", function(done) { - var doRequest = jasmine.createSpy('doRequest'); - var startAuthStage = jasmine.createSpy('startAuthStage'); + let doRequest = jasmine.createSpy('doRequest'); + let startAuthStage = jasmine.createSpy('startAuthStage'); - var ia = new InteractiveAuth({ + let ia = new InteractiveAuth({ doRequest: doRequest, startAuthStage: startAuthStage, authData: { @@ -60,7 +60,7 @@ describe("InteractiveAuth", function() { }); // .. which should trigger a call here - var requestRes = {"a": "b"}; + let requestRes = {"a": "b"}; doRequest.andCallFake(function(authData) { expect(authData).toEqual({ session: "sessionId", @@ -78,10 +78,10 @@ describe("InteractiveAuth", function() { }); it("should make a request if no authdata is provided", function(done) { - var doRequest = jasmine.createSpy('doRequest'); - var startAuthStage = jasmine.createSpy('startAuthStage'); + let doRequest = jasmine.createSpy('doRequest'); + let startAuthStage = jasmine.createSpy('startAuthStage'); - var ia = new InteractiveAuth({ + let ia = new InteractiveAuth({ doRequest: doRequest, startAuthStage: startAuthStage, }); @@ -93,7 +93,7 @@ describe("InteractiveAuth", function() { doRequest.andCallFake(function(authData) { console.log("request1", authData); expect(authData).toBe(null); - var err = new MatrixError({ + let err = new MatrixError({ session: "sessionId", flows: [ { stages: ["logintype"] }, @@ -107,7 +107,7 @@ describe("InteractiveAuth", function() { }); // .. which should be followed by a call to startAuthStage - var requestRes = {"a": "b"}; + let requestRes = {"a": "b"}; startAuthStage.andCallFake(function(stage) { expect(stage).toEqual("logintype"); expect(ia.getSessionId()).toEqual("sessionId"); diff --git a/spec/unit/matrix-client.spec.js b/spec/unit/matrix-client.spec.js index 77bb368bc..9e5c85b80 100644 --- a/spec/unit/matrix-client.spec.js +++ b/spec/unit/matrix-client.spec.js @@ -1,44 +1,44 @@ "use strict"; -var q = require("q"); -var sdk = require("../.."); -var MatrixClient = sdk.MatrixClient; -var utils = require("../test-utils"); +let q = require("q"); +let sdk = require("../.."); +let MatrixClient = sdk.MatrixClient; +let utils = require("../test-utils"); describe("MatrixClient", function() { - var userId = "@alice:bar"; - var identityServerUrl = "https://identity.server"; - var identityServerDomain = "identity.server"; - var client, store, scheduler; + let userId = "@alice:bar"; + let identityServerUrl = "https://identity.server"; + let identityServerDomain = "identity.server"; + let client, store, scheduler; - var KEEP_ALIVE_PATH = "/_matrix/client/versions"; + let KEEP_ALIVE_PATH = "/_matrix/client/versions"; - var PUSH_RULES_RESPONSE = { + let PUSH_RULES_RESPONSE = { method: "GET", path: "/pushrules/", - data: {} + data: {}, }; - var FILTER_PATH = "/user/" + encodeURIComponent(userId) + "/filter"; + let FILTER_PATH = "/user/" + encodeURIComponent(userId) + "/filter"; - var FILTER_RESPONSE = { + let FILTER_RESPONSE = { method: "POST", path: FILTER_PATH, - data: { filter_id: "f1lt3r" } + data: { filter_id: "f1lt3r" }, }; - var SYNC_DATA = { + let SYNC_DATA = { next_batch: "s_5_3", presence: { events: [] }, - rooms: {} + rooms: {}, }; - var SYNC_RESPONSE = { + let SYNC_RESPONSE = { method: "GET", path: "/sync", - data: SYNC_DATA + data: SYNC_DATA, }; - var httpLookups = [ + let httpLookups = [ // items are objects which look like: // { // method: "GET", @@ -51,14 +51,14 @@ describe("MatrixClient", function() { // } // items are popped off when processed and block if no items left. ]; - var accept_keepalives; - var pendingLookup = null; + let accept_keepalives; + let pendingLookup = null; function httpReq(cb, method, path, qp, data, prefix) { if (path === KEEP_ALIVE_PATH && accept_keepalives) { return q(); } - var next = httpLookups.shift(); - var logLine = ( + let next = httpLookups.shift(); + let logLine = ( "MatrixClient[UT] RECV " + method + " " + path + " " + "EXPECT " + (next ? next.method : next) + " " + (next ? next.path : next) ); @@ -79,7 +79,7 @@ describe("MatrixClient", function() { pendingLookup = { promise: q.defer().promise, method: method, - path: path + path: path, }; return pendingLookup.promise; } @@ -107,7 +107,7 @@ describe("MatrixClient", function() { httpStatus: next.error.httpStatus, name: next.error.errcode, message: "Expected testing error", - data: next.error + data: next.error, }); } return q(next.data); @@ -121,12 +121,12 @@ describe("MatrixClient", function() { jasmine.Clock.useMock(); scheduler = jasmine.createSpyObj("scheduler", [ "getQueueForEvent", "queueEvent", "removeEventFromQueue", - "setProcessFunction" + "setProcessFunction", ]); store = jasmine.createSpyObj("store", [ "getRoom", "getRooms", "getUser", "getSyncToken", "scrollback", "setSyncToken", "storeEvents", "storeRoom", "storeUser", - "getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter" + "getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter", ]); client = new MatrixClient({ baseUrl: "https://my.home.server", @@ -135,12 +135,12 @@ describe("MatrixClient", function() { request: function() {}, // NOP store: store, scheduler: scheduler, - userId: userId + userId: userId, }); // FIXME: We shouldn't be yanking _http like this. client._http = jasmine.createSpyObj("httpApi", [ "authedRequest", "authedRequestWithPrefix", "getContentUri", - "request", "requestWithPrefix", "uploadContent" + "request", "requestWithPrefix", "uploadContent", ]); client._http.authedRequest.andCallFake(httpReq); client._http.authedRequestWithPrefix.andCallFake(httpReq); @@ -174,9 +174,9 @@ describe("MatrixClient", function() { httpLookups = []; httpLookups.push(PUSH_RULES_RESPONSE); httpLookups.push(SYNC_RESPONSE); - var filterId = "ehfewf"; + let filterId = "ehfewf"; store.getFilterIdByName.andReturn(filterId); - var filter = new sdk.Filter(0, filterId); + let filter = new sdk.Filter(0, filterId); filter.setDefinition({"room": {"timeline": {"limit": 8}}}); store.getFilter.andReturn(filter); client.startClient(); @@ -191,7 +191,6 @@ describe("MatrixClient", function() { }); describe("getSyncState", function() { - it("should return null if the client isn't started", function() { expect(client.getSyncState()).toBeNull(); }); @@ -219,7 +218,7 @@ describe("MatrixClient", function() { // and they all need to be stored! return "FILTER_SYNC_" + userId + (suffix ? "_" + suffix : ""); } - var invalidFilterId = 'invalidF1lt3r'; + let invalidFilterId = 'invalidF1lt3r'; httpLookups = []; httpLookups.push({ method: "GET", @@ -229,15 +228,15 @@ describe("MatrixClient", function() { name: "M_UNKNOWN", message: "No row found", data: { errcode: "M_UNKNOWN", error: "No row found" }, - httpStatus: 404 - } + httpStatus: 404, + }, }); httpLookups.push(FILTER_RESPONSE); store.getFilterIdByName.andReturn(invalidFilterId); - var filterName = getFilterName(client.credentials.userId); + let filterName = getFilterName(client.credentials.userId); client.store.setFilterIdByName(filterName, invalidFilterId); - var filter = new sdk.Filter(client.credentials.userId); + let filter = new sdk.Filter(client.credentials.userId); client.getOrCreateFilter(filterName, filter).then(function(filterId) { expect(filterId).toEqual(FILTER_RESPONSE.data.filter_id); @@ -256,7 +255,7 @@ describe("MatrixClient", function() { httpLookups = []; httpLookups.push(PUSH_RULES_RESPONSE); httpLookups.push({ - method: "POST", path: FILTER_PATH, error: { errcode: "NOPE_NOPE_NOPE" } + method: "POST", path: FILTER_PATH, error: { errcode: "NOPE_NOPE_NOPE" }, }); httpLookups.push(FILTER_RESPONSE); httpLookups.push(SYNC_RESPONSE); @@ -279,10 +278,10 @@ describe("MatrixClient", function() { it("should work on /sync", function(done) { httpLookups.push({ - method: "GET", path: "/sync", error: { errcode: "NOPE_NOPE_NOPE" } + method: "GET", path: "/sync", error: { errcode: "NOPE_NOPE_NOPE" }, }); httpLookups.push({ - method: "GET", path: "/sync", data: SYNC_DATA + method: "GET", path: "/sync", data: SYNC_DATA, }); client.on("sync", function syncListener(state) { @@ -305,7 +304,7 @@ describe("MatrixClient", function() { it("should work on /pushrules", function(done) { httpLookups = []; httpLookups.push({ - method: "GET", path: "/pushrules/", error: { errcode: "NOPE_NOPE_NOPE" } + method: "GET", path: "/pushrules/", error: { errcode: "NOPE_NOPE_NOPE" }, }); httpLookups.push(PUSH_RULES_RESPONSE); httpLookups.push(FILTER_RESPONSE); @@ -329,10 +328,9 @@ describe("MatrixClient", function() { }); describe("emitted sync events", function() { - function syncChecker(expectedStates, done) { return function syncListener(state, old) { - var expected = expectedStates.shift(); + let expected = expectedStates.shift(); console.log( "'sync' curr=%s old=%s EXPECT=%s", state, old, expected ); @@ -352,18 +350,18 @@ describe("MatrixClient", function() { } it("should transition null -> PREPARED after the first /sync", function(done) { - var expectedStates = []; + let expectedStates = []; expectedStates.push(["PREPARED", null]); client.on("sync", syncChecker(expectedStates, done)); client.startClient(); }); it("should transition null -> ERROR after a failed /filter", function(done) { - var expectedStates = []; + let expectedStates = []; httpLookups = []; httpLookups.push(PUSH_RULES_RESPONSE); httpLookups.push({ - method: "POST", path: FILTER_PATH, error: { errcode: "NOPE_NOPE_NOPE" } + method: "POST", path: FILTER_PATH, error: { errcode: "NOPE_NOPE_NOPE" }, }); expectedStates.push(["ERROR", null]); client.on("sync", syncChecker(expectedStates, done)); @@ -372,22 +370,22 @@ describe("MatrixClient", function() { it("should transition ERROR -> PREPARED after /sync if prev failed", function(done) { - var expectedStates = []; + let expectedStates = []; accept_keepalives = false; httpLookups = []; httpLookups.push(PUSH_RULES_RESPONSE); httpLookups.push(FILTER_RESPONSE); httpLookups.push({ - method: "GET", path: "/sync", error: { errcode: "NOPE_NOPE_NOPE" } + method: "GET", path: "/sync", error: { errcode: "NOPE_NOPE_NOPE" }, }); httpLookups.push({ - method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" } + method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" }, }); httpLookups.push({ - method: "GET", path: KEEP_ALIVE_PATH, data: {} + method: "GET", path: KEEP_ALIVE_PATH, data: {}, }); httpLookups.push({ - method: "GET", path: "/sync", data: SYNC_DATA + method: "GET", path: "/sync", data: SYNC_DATA, }); expectedStates.push(["RECONNECTING", null]); @@ -398,7 +396,7 @@ describe("MatrixClient", function() { }); it("should transition PREPARED -> SYNCING after /sync", function(done) { - var expectedStates = []; + let expectedStates = []; expectedStates.push(["PREPARED", null]); expectedStates.push(["SYNCING", "PREPARED"]); client.on("sync", syncChecker(expectedStates, done)); @@ -407,12 +405,12 @@ describe("MatrixClient", function() { it("should transition SYNCING -> ERROR after a failed /sync", function(done) { accept_keepalives = false; - var expectedStates = []; + let expectedStates = []; httpLookups.push({ - method: "GET", path: "/sync", error: { errcode: "NONONONONO" } + method: "GET", path: "/sync", error: { errcode: "NONONONONO" }, }); httpLookups.push({ - method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" } + method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" }, }); expectedStates.push(["PREPARED", null]); @@ -425,9 +423,9 @@ describe("MatrixClient", function() { xit("should transition ERROR -> SYNCING after /sync if prev failed", function(done) { - var expectedStates = []; + let expectedStates = []; httpLookups.push({ - method: "GET", path: "/sync", error: { errcode: "NONONONONO" } + method: "GET", path: "/sync", error: { errcode: "NONONONONO" }, }); httpLookups.push(SYNC_RESPONSE); @@ -440,7 +438,7 @@ describe("MatrixClient", function() { it("should transition SYNCING -> SYNCING on subsequent /sync successes", function(done) { - var expectedStates = []; + let expectedStates = []; httpLookups.push(SYNC_RESPONSE); httpLookups.push(SYNC_RESPONSE); @@ -453,15 +451,15 @@ describe("MatrixClient", function() { it("should transition ERROR -> ERROR if keepalive keeps failing", function(done) { accept_keepalives = false; - var expectedStates = []; + let expectedStates = []; httpLookups.push({ - method: "GET", path: "/sync", error: { errcode: "NONONONONO" } + method: "GET", path: "/sync", error: { errcode: "NONONONONO" }, }); httpLookups.push({ - method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" } + method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" }, }); httpLookups.push({ - method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" } + method: "GET", path: KEEP_ALIVE_PATH, error: { errcode: "KEEPALIVE_FAIL" }, }); expectedStates.push(["PREPARED", null]); @@ -475,7 +473,7 @@ describe("MatrixClient", function() { }); describe("inviteByEmail", function() { - var roomId = "!foo:bar"; + let roomId = "!foo:bar"; it("should send an invite HTTP POST", function() { httpLookups = [{ @@ -485,17 +483,15 @@ describe("MatrixClient", function() { expectBody: { id_server: identityServerDomain, medium: "email", - address: "alice@gmail.com" - } + address: "alice@gmail.com", + }, }]; client.inviteByEmail(roomId, "alice@gmail.com"); expect(httpLookups.length).toEqual(0); }); - }); describe("guest rooms", function() { - it("should only do /sync calls (without filter/pushrules)", function(done) { httpLookups = []; // no /pushrules or /filter httpLookups.push({ @@ -504,7 +500,7 @@ describe("MatrixClient", function() { data: SYNC_DATA, thenCall: function() { done(); - } + }, }); client.setGuest(true); client.startClient(); diff --git a/spec/unit/pushprocessor.spec.js b/spec/unit/pushprocessor.spec.js index abb1a933d..5bdc10294 100644 --- a/spec/unit/pushprocessor.spec.js +++ b/spec/unit/pushprocessor.spec.js @@ -1,33 +1,33 @@ "use strict"; -var PushProcessor = require("../../lib/pushprocessor"); -var MatrixEvent = MatrixEvent; -var utils = require("../test-utils"); +let PushProcessor = require("../../lib/pushprocessor"); +let MatrixEvent = MatrixEvent; +let utils = require("../test-utils"); describe('NotificationService', function() { - var testUserId = "@ali:matrix.org"; - var testDisplayName = "Alice M"; - var testRoomId = "!fl1bb13:localhost"; + let testUserId = "@ali:matrix.org"; + let testDisplayName = "Alice M"; + let testRoomId = "!fl1bb13:localhost"; - var testEvent; + let testEvent; - var pushProcessor; + let pushProcessor; // These would be better if individual rules were configured in the tests themselves. - var matrixClient = { + let matrixClient = { getRoom: function() { return { currentState: { getMember: function() { return { - name: testDisplayName + name: testDisplayName, }; }, - members: {} - } + members: {}, + }, }; }, credentials: { - userId: testUserId + userId: testUserId, }, pushRules: { "device": {}, @@ -38,91 +38,91 @@ describe('NotificationService', function() { "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "enabled": true, "pattern": "ali", - "rule_id": ".m.rule.contains_user_name" + "rule_id": ".m.rule.contains_user_name", }, { "actions": [ "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "enabled": true, "pattern": "coffee", - "rule_id": "coffee" + "rule_id": "coffee", }, { "actions": [ "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "enabled": true, "pattern": "foo*bar", - "rule_id": "foobar" + "rule_id": "foobar", }, { "actions": [ "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "enabled": true, "pattern": "p[io]ng", - "rule_id": "pingpong" + "rule_id": "pingpong", }, { "actions": [ "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "enabled": true, "pattern": "I ate [0-9] pies", - "rule_id": "pies" + "rule_id": "pies", }, { "actions": [ "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "enabled": true, "pattern": "b[!ai]ke", - "rule_id": "bakebike" - } + "rule_id": "bakebike", + }, ], "override": [ { @@ -130,70 +130,70 @@ describe('NotificationService', function() { "notify", { "set_tweak": "sound", - "value": "default" + "value": "default", }, { - "set_tweak": "highlight" - } + "set_tweak": "highlight", + }, ], "conditions": [ { - "kind": "contains_display_name" - } + "kind": "contains_display_name", + }, ], "enabled": true, - "rule_id": ".m.rule.contains_display_name" + "rule_id": ".m.rule.contains_display_name", }, { "actions": [ "notify", { "set_tweak": "sound", - "value": "default" - } + "value": "default", + }, ], "conditions": [ { "is": "2", - "kind": "room_member_count" - } + "kind": "room_member_count", + }, ], "enabled": true, - "rule_id": ".m.rule.room_one_to_one" - } + "rule_id": ".m.rule.room_one_to_one", + }, ], "room": [], "sender": [], "underride": [ { "actions": [ - "dont-notify" + "dont-notify", ], "conditions": [ { "key": "content.msgtype", "kind": "event_match", - "pattern": "m.notice" - } + "pattern": "m.notice", + }, ], "enabled": true, - "rule_id": ".m.rule.suppress_notices" + "rule_id": ".m.rule.suppress_notices", }, { "actions": [ "notify", { "set_tweak": "highlight", - "value": false - } + "value": false, + }, ], "conditions": [], "enabled": true, - "rule_id": ".m.rule.fallback" - } - ] - } - } + "rule_id": ".m.rule.fallback", + }, + ], + }, + }, }; beforeEach(function() { @@ -204,8 +204,8 @@ describe('NotificationService', function() { event: true, content: { body: "", - msgtype: "m.text" - } + msgtype: "m.text", + }, }); pushProcessor = new PushProcessor(matrixClient); }); @@ -214,25 +214,25 @@ describe('NotificationService', function() { it('should bing on a user ID.', function() { testEvent.event.content.body = "Hello @ali:matrix.org, how are you?"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on a partial user ID with an @.', function() { testEvent.event.content.body = "Hello @ali, how are you?"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on a partial user ID without @.', function() { testEvent.event.content.body = "Hello ali, how are you?"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on a case-insensitive user ID.', function() { testEvent.event.content.body = "Hello @AlI:matrix.org, how are you?"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); @@ -240,13 +240,13 @@ describe('NotificationService', function() { it('should bing on a display name.', function() { testEvent.event.content.body = "Hello Alice M, how are you?"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on a case-insensitive display name.', function() { testEvent.event.content.body = "Hello ALICE M, how are you?"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); @@ -254,25 +254,25 @@ describe('NotificationService', function() { it('should bing on a bing word.', function() { testEvent.event.content.body = "I really like coffee"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on case-insensitive bing words.', function() { testEvent.event.content.body = "Coffee is great"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on wildcard (.*) bing words.', function() { testEvent.event.content.body = "It was foomahbar I think."; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on character group ([abc]) bing words.', function() { testEvent.event.content.body = "Ping!"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); testEvent.event.content.body = "Pong!"; actions = pushProcessor.actionsForEvent(testEvent); @@ -281,13 +281,13 @@ describe('NotificationService', function() { it('should bing on character range ([a-z]) bing words.', function() { testEvent.event.content.body = "I ate 6 pies"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); }); it('should bing on character negation ([!a]) bing words.', function() { testEvent.event.content.body = "boke"; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(true); testEvent.event.content.body = "bake"; actions = pushProcessor.actionsForEvent(testEvent); @@ -298,7 +298,7 @@ describe('NotificationService', function() { it('should gracefully handle bad input.', function() { testEvent.event.content.body = { "foo": "bar" }; - var actions = pushProcessor.actionsForEvent(testEvent); + let actions = pushProcessor.actionsForEvent(testEvent); expect(actions.tweaks.highlight).toEqual(false); }); }); diff --git a/spec/unit/realtime-callbacks.spec.js b/spec/unit/realtime-callbacks.spec.js index bec63bf0b..ddc5d5758 100644 --- a/spec/unit/realtime-callbacks.spec.js +++ b/spec/unit/realtime-callbacks.spec.js @@ -1,11 +1,11 @@ "use strict"; -var callbacks = require("../../lib/realtime-callbacks"); -var test_utils = require("../test-utils.js"); +let callbacks = require("../../lib/realtime-callbacks"); +let test_utils = require("../test-utils.js"); describe("realtime-callbacks", function() { - var clock = jasmine.Clock; - var fakeDate; + let clock = jasmine.Clock; + let fakeDate; function tick(millis) { // make sure we tick the fakedate first, otherwise nothing will happen! @@ -17,7 +17,9 @@ describe("realtime-callbacks", function() { test_utils.beforeEach(this); // eslint-disable-line no-invalid-this clock.useMock(); fakeDate = Date.now(); - callbacks.setNow(function() { return fakeDate; }); + callbacks.setNow(function() { + return fakeDate; +}); }); afterEach(function() { @@ -26,7 +28,7 @@ describe("realtime-callbacks", function() { describe("setTimeout", function() { it("should call the callback after the timeout", function() { - var callback = jasmine.createSpy(); + let callback = jasmine.createSpy(); callbacks.setTimeout(callback, 100); expect(callback).not.toHaveBeenCalled(); @@ -36,7 +38,7 @@ describe("realtime-callbacks", function() { it("should default to a zero timeout", function() { - var callback = jasmine.createSpy(); + let callback = jasmine.createSpy(); callbacks.setTimeout(callback); expect(callback).not.toHaveBeenCalled(); @@ -45,14 +47,14 @@ describe("realtime-callbacks", function() { }); it("should pass any parameters to the callback", function() { - var callback = jasmine.createSpy(); + let callback = jasmine.createSpy(); callbacks.setTimeout(callback, 0, "a", "b", "c"); tick(0); expect(callback).toHaveBeenCalledWith("a", "b", "c"); }); it("should set 'this' to the global object", function() { - var callback = jasmine.createSpy(); + let callback = jasmine.createSpy(); callback.andCallFake(function() { expect(this).toBe(global); // eslint-disable-line no-invalid-this expect(this.console).toBeDefined(); // eslint-disable-line no-invalid-this @@ -63,20 +65,20 @@ describe("realtime-callbacks", function() { }); it("should handle timeouts of several seconds", function() { - var callback = jasmine.createSpy(); + let callback = jasmine.createSpy(); callbacks.setTimeout(callback, 2000); expect(callback).not.toHaveBeenCalled(); - for (var i = 0; i < 4; i++) { + for (let i = 0; i < 4; i++) { tick(500); } expect(callback).toHaveBeenCalled(); }); it("should call multiple callbacks in the right order", function() { - var callback1 = jasmine.createSpy("callback1"); - var callback2 = jasmine.createSpy("callback2"); - var callback3 = jasmine.createSpy("callback3"); + let callback1 = jasmine.createSpy("callback1"); + let callback2 = jasmine.createSpy("callback2"); + let callback3 = jasmine.createSpy("callback3"); callbacks.setTimeout(callback2, 200); callbacks.setTimeout(callback1, 100); callbacks.setTimeout(callback3, 300); @@ -99,8 +101,8 @@ describe("realtime-callbacks", function() { }); it("should treat -ve timeouts the same as a zero timeout", function() { - var callback1 = jasmine.createSpy("callback1"); - var callback2 = jasmine.createSpy("callback2"); + let callback1 = jasmine.createSpy("callback1"); + let callback2 = jasmine.createSpy("callback2"); // check that cb1 is called before cb2 callback1.andCallFake(function() { @@ -118,8 +120,8 @@ describe("realtime-callbacks", function() { }); it("should not get confused by chained calls", function() { - var callback2 = jasmine.createSpy("callback2"); - var callback1 = jasmine.createSpy("callback1"); + let callback2 = jasmine.createSpy("callback2"); + let callback1 = jasmine.createSpy("callback1"); callback1.andCallFake(function() { callbacks.setTimeout(callback2, 0); expect(callback2).not.toHaveBeenCalled(); @@ -134,11 +136,11 @@ describe("realtime-callbacks", function() { }); it("should be immune to exceptions", function() { - var callback1 = jasmine.createSpy("callback1"); + let callback1 = jasmine.createSpy("callback1"); callback1.andCallFake(function() { throw new Error("prepare to die"); }); - var callback2 = jasmine.createSpy("callback2"); + let callback2 = jasmine.createSpy("callback2"); callbacks.setTimeout(callback1, 0); callbacks.setTimeout(callback2, 0); @@ -148,24 +150,23 @@ describe("realtime-callbacks", function() { expect(callback1).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled(); }); - }); describe("cancelTimeout", function() { it("should cancel a pending timeout", function() { - var callback = jasmine.createSpy(); - var k = callbacks.setTimeout(callback); + let callback = jasmine.createSpy(); + let k = callbacks.setTimeout(callback); callbacks.clearTimeout(k); tick(0); expect(callback).not.toHaveBeenCalled(); }); it("should not affect sooner timeouts", function() { - var callback1 = jasmine.createSpy("callback1"); - var callback2 = jasmine.createSpy("callback2"); + let callback1 = jasmine.createSpy("callback1"); + let callback2 = jasmine.createSpy("callback2"); callbacks.setTimeout(callback1, 100); - var k = callbacks.setTimeout(callback2, 200); + let k = callbacks.setTimeout(callback2, 200); callbacks.clearTimeout(k); tick(100); diff --git a/spec/unit/room-member.spec.js b/spec/unit/room-member.spec.js index 36a38932c..76abe2793 100644 --- a/spec/unit/room-member.spec.js +++ b/spec/unit/room-member.spec.js @@ -1,14 +1,14 @@ "use strict"; -var sdk = require("../.."); -var RoomMember = sdk.RoomMember; -var utils = require("../test-utils"); +let sdk = require("../.."); +let RoomMember = sdk.RoomMember; +let utils = require("../test-utils"); describe("RoomMember", function() { - var roomId = "!foo:bar"; - var userA = "@alice:bar"; - var userB = "@bertha:bar"; - var userC = "@clarissa:bar"; - var member; + let roomId = "!foo:bar"; + let userA = "@alice:bar"; + let userB = "@bertha:bar"; + let userC = "@clarissa:bar"; + let member; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -16,7 +16,7 @@ describe("RoomMember", function() { }); describe("getAvatarUrl", function() { - var hsUrl = "https://my.home.server"; + let hsUrl = "https://my.home.server"; it("should return the URL from m.room.member preferentially", function() { member.events.member = utils.mkEvent({ @@ -27,10 +27,10 @@ describe("RoomMember", function() { user: userA, content: { membership: "join", - avatar_url: "mxc://flibble/wibble" - } + avatar_url: "mxc://flibble/wibble", + }, }); - var url = member.getAvatarUrl(hsUrl); + let url = member.getAvatarUrl(hsUrl); // we don't care about how the mxc->http conversion is done, other // than it contains the mxc body. expect(url.indexOf("flibble/wibble")).not.toEqual(-1); @@ -38,20 +38,20 @@ describe("RoomMember", function() { it("should return an identicon HTTP URL if allowDefault was set and there " + "was no m.room.member event", function() { - var url = member.getAvatarUrl(hsUrl, 64, 64, "crop", true); + let url = member.getAvatarUrl(hsUrl, 64, 64, "crop", true); expect(url.indexOf("http")).toEqual(0); // don't care about form }); it("should return nothing if there is no m.room.member and allowDefault=false", function() { - var url = member.getAvatarUrl(hsUrl, 64, 64, "crop", false); + let url = member.getAvatarUrl(hsUrl, 64, 64, "crop", false); expect(url).toEqual(null); }); }); describe("setPowerLevelEvent", function() { it("should set 'powerLevel' and 'powerLevelNorm'.", function() { - var event = utils.mkEvent({ + let event = utils.mkEvent({ type: "m.room.power_levels", room: roomId, user: userA, @@ -59,16 +59,16 @@ describe("RoomMember", function() { users_default: 20, users: { "@bertha:bar": 200, - "@invalid:user": 10 // shouldn't barf on this. - } + "@invalid:user": 10, // shouldn't barf on this. + }, }, - event: true + event: true, }); member.setPowerLevelEvent(event); expect(member.powerLevel).toEqual(20); expect(member.powerLevelNorm).toEqual(10); - var memberB = new RoomMember(roomId, userB); + let memberB = new RoomMember(roomId, userB); memberB.setPowerLevelEvent(event); expect(memberB.powerLevel).toEqual(200); expect(memberB.powerLevelNorm).toEqual(100); @@ -76,7 +76,7 @@ describe("RoomMember", function() { it("should emit 'RoomMember.powerLevel' if the power level changes.", function() { - var event = utils.mkEvent({ + let event = utils.mkEvent({ type: "m.room.power_levels", room: roomId, user: userA, @@ -84,12 +84,12 @@ describe("RoomMember", function() { users_default: 20, users: { "@bertha:bar": 200, - "@invalid:user": 10 // shouldn't barf on this. - } + "@invalid:user": 10, // shouldn't barf on this. + }, }, - event: true + event: true, }); - var emitCount = 0; + let emitCount = 0; member.on("RoomMember.powerLevel", function(emitEvent, emitMember) { emitCount += 1; @@ -105,7 +105,7 @@ describe("RoomMember", function() { it("should honour power levels of zero.", function() { - var event = utils.mkEvent({ + let event = utils.mkEvent({ type: "m.room.power_levels", room: roomId, user: userA, @@ -113,11 +113,11 @@ describe("RoomMember", function() { users_default: 20, users: { "@alice:bar": 0, - } + }, }, - event: true + event: true, }); - var emitCount = 0; + let emitCount = 0; // set the power level to something other than zero or we // won't get an event @@ -138,21 +138,21 @@ describe("RoomMember", function() { describe("setTypingEvent", function() { it("should set 'typing'", function() { member.typing = false; - var memberB = new RoomMember(roomId, userB); + let memberB = new RoomMember(roomId, userB); memberB.typing = true; - var memberC = new RoomMember(roomId, userC); + let memberC = new RoomMember(roomId, userC); memberC.typing = true; - var event = utils.mkEvent({ + let event = utils.mkEvent({ type: "m.typing", user: userA, room: roomId, content: { user_ids: [ - userA, userC - ] + userA, userC, + ], }, - event: true + event: true, }); member.setTypingEvent(event); memberB.setTypingEvent(event); @@ -165,17 +165,17 @@ describe("RoomMember", function() { it("should emit 'RoomMember.typing' if the typing state changes", function() { - var event = utils.mkEvent({ + let event = utils.mkEvent({ type: "m.typing", room: roomId, content: { user_ids: [ - userA, userC - ] + userA, userC, + ], }, - event: true + event: true, }); - var emitCount = 0; + let emitCount = 0; member.on("RoomMember.typing", function(ev, mem) { expect(mem).toEqual(member); expect(ev).toEqual(event); @@ -190,20 +190,20 @@ describe("RoomMember", function() { }); describe("setMembershipEvent", function() { - var joinEvent = utils.mkMembership({ + let joinEvent = utils.mkMembership({ event: true, mship: "join", user: userA, room: roomId, - name: "Alice" + name: "Alice", }); - var inviteEvent = utils.mkMembership({ + let inviteEvent = utils.mkMembership({ event: true, mship: "invite", user: userB, skey: userA, - room: roomId + room: roomId, }); it("should set 'membership' and assign the event to 'events.member'.", @@ -218,24 +218,26 @@ describe("RoomMember", function() { it("should set 'name' based on user_id, displayname and room state", function() { - var roomState = { + let roomState = { getStateEvents: function(type) { - if (type !== "m.room.member") { return []; } + if (type !== "m.room.member") { + return []; +} return [ utils.mkMembership({ event: true, mship: "join", room: roomId, - user: userB + user: userB, }), utils.mkMembership({ event: true, mship: "join", room: roomId, - user: userC, name: "Alice" + user: userC, name: "Alice", }), - joinEvent + joinEvent, ]; }, getUserIdsWithDisplayName: function(displayName) { return [userA, userC]; - } + }, }; expect(member.name).toEqual(userA); // default = user_id member.setMembershipEvent(joinEvent); @@ -247,7 +249,7 @@ describe("RoomMember", function() { }); it("should emit 'RoomMember.membership' if the membership changes", function() { - var emitCount = 0; + let emitCount = 0; member.on("RoomMember.membership", function(ev, mem) { emitCount += 1; expect(mem).toEqual(member); @@ -260,7 +262,7 @@ describe("RoomMember", function() { }); it("should emit 'RoomMember.name' if the name changes", function() { - var emitCount = 0; + let emitCount = 0; member.on("RoomMember.name", function(ev, mem) { emitCount += 1; expect(mem).toEqual(member); @@ -271,8 +273,5 @@ describe("RoomMember", function() { member.setMembershipEvent(joinEvent); // no-op expect(emitCount).toEqual(1); }); - - }); - }); diff --git a/spec/unit/room-state.spec.js b/spec/unit/room-state.spec.js index 57c99b208..20903785a 100644 --- a/spec/unit/room-state.spec.js +++ b/spec/unit/room-state.spec.js @@ -1,35 +1,35 @@ "use strict"; -var sdk = require("../.."); -var RoomState = sdk.RoomState; -var RoomMember = sdk.RoomMember; -var utils = require("../test-utils"); +let sdk = require("../.."); +let RoomState = sdk.RoomState; +let RoomMember = sdk.RoomMember; +let utils = require("../test-utils"); describe("RoomState", function() { - var roomId = "!foo:bar"; - var userA = "@alice:bar"; - var userB = "@bob:bar"; - var state; + let roomId = "!foo:bar"; + let userA = "@alice:bar"; + let userB = "@bob:bar"; + let state; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this state = new RoomState(roomId); state.setStateEvents([ utils.mkMembership({ // userA joined - event: true, mship: "join", user: userA, room: roomId + event: true, mship: "join", user: userA, room: roomId, }), utils.mkMembership({ // userB joined - event: true, mship: "join", user: userB, room: roomId + event: true, mship: "join", user: userB, room: roomId, }), utils.mkEvent({ // Room name is "Room name goes here" type: "m.room.name", user: userA, room: roomId, event: true, content: { - name: "Room name goes here" - } + name: "Room name goes here", + }, }), utils.mkEvent({ // Room creation type: "m.room.create", user: userA, room: roomId, event: true, content: { - creator: userA - } - }) + creator: userA, + }, + }), ]); }); @@ -40,7 +40,7 @@ describe("RoomState", function() { }); it("should return a member for each m.room.member event", function() { - var members = state.getMembers(); + let members = state.getMembers(); expect(members.length).toEqual(2); // ordering unimportant expect([userA, userB].indexOf(members[0].userId)).not.toEqual(-1); @@ -58,15 +58,15 @@ describe("RoomState", function() { }); it("should return a member which changes as state changes", function() { - var member = state.getMember(userB); + let member = state.getMember(userB); expect(member.membership).toEqual("join"); expect(member.name).toEqual(userB); state.setStateEvents([ utils.mkMembership({ room: roomId, user: userB, mship: "leave", event: true, - name: "BobGone" - }) + name: "BobGone", + }), ]); expect(member.membership).toEqual("leave"); @@ -81,14 +81,14 @@ describe("RoomState", function() { it("should return a member which doesn't change when the state is updated", function() { - var preLeaveUser = state.getSentinelMember(userA); + let preLeaveUser = state.getSentinelMember(userA); state.setStateEvents([ utils.mkMembership({ room: roomId, user: userA, mship: "leave", event: true, - name: "AliceIsGone" - }) + name: "AliceIsGone", + }), ]); - var postLeaveUser = state.getSentinelMember(userA); + let postLeaveUser = state.getSentinelMember(userA); expect(preLeaveUser.membership).toEqual("join"); expect(preLeaveUser.name).toEqual(userA); @@ -111,7 +111,7 @@ describe("RoomState", function() { it("should return a list of matching events if no state_key was specified", function() { - var events = state.getStateEvents("m.room.member"); + let events = state.getStateEvents("m.room.member"); expect(events.length).toEqual(2); // ordering unimportant expect([userA, userB].indexOf(events[0].getStateKey())).not.toEqual(-1); @@ -120,24 +120,24 @@ describe("RoomState", function() { it("should return a single MatrixEvent if a state_key was specified", function() { - var event = state.getStateEvents("m.room.member", userA); + let event = state.getStateEvents("m.room.member", userA); expect(event.getContent()).toEqual({ - membership: "join" + membership: "join", }); }); }); describe("setStateEvents", function() { it("should emit 'RoomState.members' for each m.room.member event", function() { - var memberEvents = [ + let memberEvents = [ utils.mkMembership({ - user: "@cleo:bar", mship: "invite", room: roomId, event: true + user: "@cleo:bar", mship: "invite", room: roomId, event: true, }), utils.mkMembership({ - user: "@daisy:bar", mship: "join", room: roomId, event: true - }) + user: "@daisy:bar", mship: "join", room: roomId, event: true, + }), ]; - var emitCount = 0; + let emitCount = 0; state.on("RoomState.members", function(ev, st, mem) { expect(ev).toEqual(memberEvents[emitCount]); expect(st).toEqual(state); @@ -149,15 +149,15 @@ describe("RoomState", function() { }); it("should emit 'RoomState.newMember' for each new member added", function() { - var memberEvents = [ + let memberEvents = [ utils.mkMembership({ - user: "@cleo:bar", mship: "invite", room: roomId, event: true + user: "@cleo:bar", mship: "invite", room: roomId, event: true, }), utils.mkMembership({ - user: "@daisy:bar", mship: "join", room: roomId, event: true - }) + user: "@daisy:bar", mship: "join", room: roomId, event: true, + }), ]; - var emitCount = 0; + let emitCount = 0; state.on("RoomState.newMember", function(ev, st, mem) { expect(mem.userId).toEqual(memberEvents[emitCount].getSender()); expect(mem.membership).toBeFalsy(); // not defined yet @@ -168,21 +168,21 @@ describe("RoomState", function() { }); it("should emit 'RoomState.events' for each state event", function() { - var events = [ + let events = [ utils.mkMembership({ - user: "@cleo:bar", mship: "invite", room: roomId, event: true + user: "@cleo:bar", mship: "invite", room: roomId, event: true, }), utils.mkEvent({ user: userB, room: roomId, type: "m.room.topic", event: true, content: { - topic: "boo!" - } + topic: "boo!", + }, }), utils.mkMessage({ // Not a state event - user: userA, room: roomId, event: true - }) + user: userA, room: roomId, event: true, + }), ]; - var emitCount = 0; + let emitCount = 0; state.on("RoomState.events", function(ev, st) { expect(ev).toEqual(events[emitCount]); expect(st).toEqual(state); @@ -198,13 +198,13 @@ describe("RoomState", function() { state.members[userA] = utils.mock(RoomMember); state.members[userB] = utils.mock(RoomMember); - var powerLevelEvent = utils.mkEvent({ + let powerLevelEvent = utils.mkEvent({ type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { users_default: 10, state_default: 50, - events_default: 25 - } + events_default: 25, + }, }); state.setStateEvents([powerLevelEvent]); @@ -219,18 +219,18 @@ describe("RoomState", function() { it("should call setPowerLevelEvent on a new RoomMember if power levels exist", function() { - var userC = "@cleo:bar"; - var memberEvent = utils.mkMembership({ - mship: "join", user: userC, room: roomId, event: true + let userC = "@cleo:bar"; + let memberEvent = utils.mkMembership({ + mship: "join", user: userC, room: roomId, event: true, }); - var powerLevelEvent = utils.mkEvent({ + let powerLevelEvent = utils.mkEvent({ type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { users_default: 10, state_default: 50, events_default: 25, - users: {} - } + users: {}, + }, }); state.setStateEvents([powerLevelEvent]); @@ -247,8 +247,8 @@ describe("RoomState", function() { state.members[userA] = utils.mock(RoomMember); state.members[userB] = utils.mock(RoomMember); - var memberEvent = utils.mkMembership({ - user: userB, mship: "leave", room: roomId, event: true + let memberEvent = utils.mkMembership({ + user: userB, mship: "leave", room: roomId, event: true, }); state.setStateEvents([memberEvent]); @@ -261,10 +261,10 @@ describe("RoomState", function() { describe("setTypingEvent", function() { it("should call setTypingEvent on each RoomMember", function() { - var typingEvent = utils.mkEvent({ + let typingEvent = utils.mkEvent({ type: "m.typing", room: roomId, event: true, content: { - user_ids: [userA] - } + user_ids: [userA], + }, }); // mock up the room members state.members[userA] = utils.mock(RoomMember); @@ -296,15 +296,15 @@ describe("RoomState", function() { it("should say members with power >=50 may send state with power level event " + "but no state default", function() { - var powerLevelEvent = { + let powerLevelEvent = { type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { users_default: 10, // state_default: 50, "intentionally left blank" events_default: 25, users: { - } - } + }, + }, }; powerLevelEvent.content.users[userA] = 50; @@ -316,15 +316,15 @@ describe("RoomState", function() { it("should obey state_default", function() { - var powerLevelEvent = { + let powerLevelEvent = { type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { users_default: 10, state_default: 30, events_default: 25, users: { - } - } + }, + }, }; powerLevelEvent.content.users[userA] = 30; powerLevelEvent.content.users[userB] = 29; @@ -337,18 +337,18 @@ describe("RoomState", function() { it("should honour explicit event power levels in the power_levels event", function() { - var powerLevelEvent = { + let powerLevelEvent = { type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { events: { - "m.room.other_thing": 76 + "m.room.other_thing": 76, }, users_default: 10, state_default: 50, events_default: 25, users: { - } - } + }, + }, }; powerLevelEvent.content.users[userA] = 80; powerLevelEvent.content.users[userB] = 50; @@ -380,15 +380,15 @@ describe("RoomState", function() { it("should obey events_default", function() { - var powerLevelEvent = { + let powerLevelEvent = { type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { users_default: 10, state_default: 30, events_default: 25, users: { - } - } + }, + }, }; powerLevelEvent.content.users[userA] = 26; powerLevelEvent.content.users[userB] = 24; @@ -404,18 +404,18 @@ describe("RoomState", function() { it("should honour explicit event power levels in the power_levels event", function() { - var powerLevelEvent = { + let powerLevelEvent = { type: "m.room.power_levels", room: roomId, user: userA, event: true, content: { events: { - "m.room.other_thing": 33 + "m.room.other_thing": 33, }, users_default: 10, state_default: 50, events_default: 25, users: { - } - } + }, + }, }; powerLevelEvent.content.users[userA] = 40; powerLevelEvent.content.users[userB] = 30; diff --git a/spec/unit/room.spec.js b/spec/unit/room.spec.js index 74882a082..1d5d2e216 100644 --- a/spec/unit/room.spec.js +++ b/spec/unit/room.spec.js @@ -1,19 +1,19 @@ "use strict"; -var sdk = require("../.."); -var Room = sdk.Room; -var RoomState = sdk.RoomState; -var MatrixEvent = sdk.MatrixEvent; -var EventStatus = sdk.EventStatus; -var EventTimeline = sdk.EventTimeline; -var utils = require("../test-utils"); +let sdk = require("../.."); +let Room = sdk.Room; +let RoomState = sdk.RoomState; +let MatrixEvent = sdk.MatrixEvent; +let EventStatus = sdk.EventStatus; +let EventTimeline = sdk.EventTimeline; +let utils = require("../test-utils"); describe("Room", function() { - var roomId = "!foo:bar"; - var userA = "@alice:bar"; - var userB = "@bertha:bar"; - var userC = "@clarissa:bar"; - var userD = "@dorothy:bar"; - var room; + let roomId = "!foo:bar"; + let userA = "@alice:bar"; + let userB = "@bertha:bar"; + let userC = "@clarissa:bar"; + let userD = "@dorothy:bar"; + let room; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -26,7 +26,7 @@ describe("Room", function() { }); describe("getAvatarUrl", function() { - var hsUrl = "https://my.home.server"; + let hsUrl = "https://my.home.server"; it("should return the URL from m.room.avatar preferentially", function() { room.currentState.getStateEvents.andCallFake(function(type, key) { @@ -38,12 +38,12 @@ describe("Room", function() { room: roomId, user: userA, content: { - url: "mxc://flibble/wibble" - } + url: "mxc://flibble/wibble", + }, }); } }); - var url = room.getAvatarUrl(hsUrl); + let url = room.getAvatarUrl(hsUrl); // we don't care about how the mxc->http conversion is done, other // than it contains the mxc body. expect(url.indexOf("flibble/wibble")).not.toEqual(-1); @@ -51,13 +51,13 @@ describe("Room", function() { it("should return an identicon HTTP URL if allowDefault was set and there " + "was no m.room.avatar event", function() { - var url = room.getAvatarUrl(hsUrl, 64, 64, "crop", true); + let url = room.getAvatarUrl(hsUrl, 64, 64, "crop", true); expect(url.indexOf("http")).toEqual(0); // don't care about form }); it("should return nothing if there is no m.room.avatar and allowDefault=false", function() { - var url = room.getAvatarUrl(hsUrl, 64, 64, "crop", false); + let url = room.getAvatarUrl(hsUrl, 64, 64, "crop", false); expect(url).toEqual(null); }); }); @@ -68,8 +68,8 @@ describe("Room", function() { room.currentState.members = { "@alice:bar": { userId: userA, - roomId: roomId - } + roomId: roomId, + }, }; }); @@ -83,35 +83,37 @@ describe("Room", function() { }); describe("addLiveEvents", function() { - var events = [ + let events = [ utils.mkMessage({ - room: roomId, user: userA, msg: "changing room name", event: true + room: roomId, user: userA, msg: "changing room name", event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "New Room Name" } - }) + content: { name: "New Room Name" }, + }), ]; it("should call RoomState.setTypingEvent on m.typing events", function() { room.currentState = utils.mock(RoomState); - var typing = utils.mkEvent({ + let typing = utils.mkEvent({ room: roomId, type: "m.typing", event: true, content: { - user_ids: [userA] - } + user_ids: [userA], + }, }); room.addLiveEvents([typing]); expect(room.currentState.setTypingEvent).toHaveBeenCalledWith(typing); }); it("should throw if duplicateStrategy isn't 'replace' or 'ignore'", function() { - expect(function() { room.addLiveEvents(events, "foo"); }).toThrow(); + expect(function() { + room.addLiveEvents(events, "foo"); +}).toThrow(); }); it("should replace a timeline event if dupe strategy is 'replace'", function() { // make a duplicate - var dupe = utils.mkMessage({ - room: roomId, user: userA, msg: "dupe", event: true + let dupe = utils.mkMessage({ + room: roomId, user: userA, msg: "dupe", event: true, }); dupe.event.event_id = events[0].getId(); room.addLiveEvents(events); @@ -122,8 +124,8 @@ describe("Room", function() { it("should ignore a given dupe event if dupe strategy is 'ignore'", function() { // make a duplicate - var dupe = utils.mkMessage({ - room: roomId, user: userA, msg: "dupe", event: true + let dupe = utils.mkMessage({ + room: roomId, user: userA, msg: "dupe", event: true, }); dupe.event.event_id = events[0].getId(); room.addLiveEvents(events); @@ -134,7 +136,7 @@ describe("Room", function() { it("should emit 'Room.timeline' events", function() { - var callCount = 0; + let callCount = 0; room.on("Room.timeline", function(event, emitRoom, toStart) { callCount += 1; expect(room.timeline.length).toEqual(callCount); @@ -148,16 +150,16 @@ describe("Room", function() { it("should call setStateEvents on the right RoomState with the right " + "forwardLooking value for new events", function() { - var events = [ + let events = [ utils.mkMembership({ - room: roomId, mship: "invite", user: userB, skey: userA, event: true + room: roomId, mship: "invite", user: userB, skey: userA, event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userB, event: true, content: { - name: "New room" - } - }) + name: "New room", + }, + }), ]; room.addLiveEvents(events); expect(room.currentState.setStateEvents).toHaveBeenCalledWith( @@ -172,10 +174,10 @@ describe("Room", function() { }); it("should synthesize read receipts for the senders of events", function() { - var sentinel = { + let sentinel = { userId: userA, membership: "join", - name: "Alice" + name: "Alice", }; room.currentState.getSentinelMember.andCallFake(function(uid) { if (uid === userA) { @@ -188,19 +190,19 @@ describe("Room", function() { }); it("should emit Room.localEchoUpdated when a local echo is updated", function() { - var localEvent = utils.mkMessage({ + let localEvent = utils.mkMessage({ room: roomId, user: userA, event: true, }); localEvent.status = EventStatus.SENDING; - var localEventId = localEvent.getId(); + let localEventId = localEvent.getId(); - var remoteEvent = utils.mkMessage({ + let remoteEvent = utils.mkMessage({ room: roomId, user: userA, event: true, }); remoteEvent.event.unsigned = {transaction_id: "TXN_ID"}; - var remoteEventId = remoteEvent.getId(); + let remoteEventId = remoteEvent.getId(); - var callCount = 0; + let callCount = 0; room.on("Room.localEchoUpdated", function(event, emitRoom, oldEventId, oldStatus) { switch (callCount) { @@ -236,14 +238,14 @@ describe("Room", function() { }); describe("addEventsToTimeline", function() { - var events = [ + let events = [ utils.mkMessage({ - room: roomId, user: userA, msg: "changing room name", event: true + room: roomId, user: userA, msg: "changing room name", event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "New Room Name" } - }) + content: { name: "New Room Name" }, + }), ]; it("should not be able to add events to the end", function() { @@ -261,7 +263,7 @@ describe("Room", function() { it("should emit 'Room.timeline' events when added to the start", function() { - var callCount = 0; + let callCount = 0; room.on("Room.timeline", function(event, emitRoom, toStart) { callCount += 1; expect(room.timeline.length).toEqual(callCount); @@ -276,15 +278,15 @@ describe("Room", function() { describe("event metadata handling", function() { it("should set event.sender for new and old events", function() { - var sentinel = { + let sentinel = { userId: userA, membership: "join", - name: "Alice" + name: "Alice", }; - var oldSentinel = { + let oldSentinel = { userId: userA, membership: "join", - name: "Old Alice" + name: "Old Alice", }; room.currentState.getSentinelMember.andCallFake(function(uid) { if (uid === userA) { @@ -299,13 +301,13 @@ describe("Room", function() { return null; }); - var newEv = utils.mkEvent({ + let newEv = utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "New Room Name" } + content: { name: "New Room Name" }, }); - var oldEv = utils.mkEvent({ + let oldEv = utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "Old Room Name" } + content: { name: "Old Room Name" }, }); room.addLiveEvents([newEv]); expect(newEv.sender).toEqual(sentinel); @@ -315,15 +317,15 @@ describe("Room", function() { it("should set event.target for new and old m.room.member events", function() { - var sentinel = { + let sentinel = { userId: userA, membership: "join", - name: "Alice" + name: "Alice", }; - var oldSentinel = { + let oldSentinel = { userId: userA, membership: "join", - name: "Old Alice" + name: "Old Alice", }; room.currentState.getSentinelMember.andCallFake(function(uid) { if (uid === userA) { @@ -338,11 +340,11 @@ describe("Room", function() { return null; }); - var newEv = utils.mkMembership({ - room: roomId, mship: "invite", user: userB, skey: userA, event: true + let newEv = utils.mkMembership({ + room: roomId, mship: "invite", user: userB, skey: userA, event: true, }); - var oldEv = utils.mkMembership({ - room: roomId, mship: "ban", user: userB, skey: userA, event: true + let oldEv = utils.mkMembership({ + room: roomId, mship: "ban", user: userB, skey: userA, event: true, }); room.addLiveEvents([newEv]); expect(newEv.target).toEqual(sentinel); @@ -352,16 +354,16 @@ describe("Room", function() { it("should call setStateEvents on the right RoomState with the right " + "forwardLooking value for old events", function() { - var events = [ + let events = [ utils.mkMembership({ - room: roomId, mship: "invite", user: userB, skey: userA, event: true + room: roomId, mship: "invite", user: userB, skey: userA, event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userB, event: true, content: { - name: "New room" - } - }) + name: "New room", + }, + }), ]; room.addEventsToTimeline(events, true, room.getLiveTimeline()); @@ -377,18 +379,18 @@ describe("Room", function() { }); }); - var resetTimelineTests = function(timelineSupport) { - var events = [ + let resetTimelineTests = function(timelineSupport) { + let events = [ utils.mkMessage({ - room: roomId, user: userA, msg: "A message", event: true + room: roomId, user: userA, msg: "A message", event: true, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "New Room Name" } + content: { name: "New Room Name" }, }), utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, event: true, - content: { name: "Another New Name" } + content: { name: "Another New Name" }, }), ]; @@ -402,8 +404,8 @@ describe("Room", function() { room.resetLiveTimeline(); room.addLiveEvents([events[2]]); - var oldState = room.getLiveTimeline().getState(EventTimeline.BACKWARDS); - var newState = room.getLiveTimeline().getState(EventTimeline.FORWARDS); + let oldState = room.getLiveTimeline().getState(EventTimeline.BACKWARDS); + let newState = room.getLiveTimeline().getState(EventTimeline.FORWARDS); expect(room.getLiveTimeline().getEvents().length).toEqual(1); expect(oldState.getStateEvents("m.room.name", "")).toEqual(events[1]); expect(newState.getStateEvents("m.room.name", "")).toEqual(events[2]); @@ -415,7 +417,7 @@ describe("Room", function() { room.resetLiveTimeline(); room.addLiveEvents([events[2]]); - var newLiveTimeline = room.getLiveTimeline(); + let newLiveTimeline = room.getLiveTimeline(); expect(room.timeline).toEqual(newLiveTimeline.getEvents()); expect(room.oldState).toEqual( newLiveTimeline.getState(EventTimeline.BACKWARDS)); @@ -425,14 +427,14 @@ describe("Room", function() { it("should emit Room.timelineReset event and set the correct " + "pagination token", function() { - var callCount = 0; + let callCount = 0; room.on("Room.timelineReset", function(emitRoom) { callCount += 1; expect(emitRoom).toEqual(room); // make sure that the pagination token has been set before the // event is emitted. - var tok = emitRoom.getLiveTimeline() + let tok = emitRoom.getLiveTimeline() .getPaginationToken(EventTimeline.BACKWARDS); expect(tok).toEqual("pagToken"); @@ -445,13 +447,12 @@ describe("Room", function() { " old timelines", function() { room.addLiveEvents([events[0]]); expect(room.timeline.length).toEqual(1); - var firstLiveTimeline = room.getLiveTimeline(); + let firstLiveTimeline = room.getLiveTimeline(); room.resetLiveTimeline(); - var tl = room.getTimelineForEvent(events[0].getId()); + let tl = room.getTimelineForEvent(events[0].getId()); expect(tl).toBe(timelineSupport ? firstLiveTimeline : null); }); - }; describe("resetLiveTimeline with timelinesupport enabled", @@ -464,15 +465,15 @@ describe("Room", function() { room = new Room(roomId, {timelineSupport: true}); }); - var events = [ + let events = [ utils.mkMessage({ - room: roomId, user: userA, msg: "1111", event: true + room: roomId, user: userA, msg: "1111", event: true, }), utils.mkMessage({ - room: roomId, user: userA, msg: "2222", event: true + room: roomId, user: userA, msg: "2222", event: true, }), utils.mkMessage({ - room: roomId, user: userA, msg: "3333", event: true + room: roomId, user: userA, msg: "3333", event: true, }), ]; @@ -491,7 +492,7 @@ describe("Room", function() { }); it("should handle events in adjacent timelines", function() { - var oldTimeline = room.addTimeline(); + let oldTimeline = room.addTimeline(); oldTimeline.setNeighbouringTimeline(room.getLiveTimeline(), 'f'); room.getLiveTimeline().setNeighbouringTimeline(oldTimeline, 'b'); @@ -507,7 +508,7 @@ describe("Room", function() { }); it("should return null for events in non-adjacent timelines", function() { - var oldTimeline = room.addTimeline(); + let oldTimeline = room.addTimeline(); room.addEventsToTimeline([events[0]], false, oldTimeline); room.addLiveEvents([events[1]]); @@ -536,16 +537,15 @@ describe("Room", function() { }); describe("getJoinedMembers", function() { - it("should return members whose membership is 'join'", function() { room.currentState.getMembers.andCallFake(function() { return [ { userId: "@alice:bar", membership: "join" }, { userId: "@bob:bar", membership: "invite" }, - { userId: "@cleo:bar", membership: "leave" } + { userId: "@cleo:bar", membership: "leave" }, ]; }); - var res = room.getJoinedMembers(); + let res = room.getJoinedMembers(); expect(res.length).toEqual(1); expect(res[0].userId).toEqual("@alice:bar"); }); @@ -553,21 +553,20 @@ describe("Room", function() { it("should return an empty list if no membership is 'join'", function() { room.currentState.getMembers.andCallFake(function() { return [ - { userId: "@bob:bar", membership: "invite" } + { userId: "@bob:bar", membership: "invite" }, ]; }); - var res = room.getJoinedMembers(); + let res = room.getJoinedMembers(); expect(res.length).toEqual(0); }); }); describe("hasMembershipState", function() { - it("should return true for a matching userId and membership", function() { room.currentState.members = { "@alice:bar": { userId: "@alice:bar", membership: "join" }, - "@bob:bar": { userId: "@bob:bar", membership: "invite" } + "@bob:bar": { userId: "@bob:bar", membership: "invite" }, }; expect(room.hasMembershipState("@bob:bar", "invite")).toBe(true); }); @@ -575,7 +574,7 @@ describe("Room", function() { it("should return false if match membership but no match userId", function() { room.currentState.members = { - "@alice:bar": { userId: "@alice:bar", membership: "join" } + "@alice:bar": { userId: "@alice:bar", membership: "join" }, }; expect(room.hasMembershipState("@bob:bar", "join")).toBe(false); }); @@ -583,7 +582,7 @@ describe("Room", function() { it("should return false if match userId but no match membership", function() { room.currentState.members = { - "@alice:bar": { userId: "@alice:bar", membership: "join" } + "@alice:bar": { userId: "@alice:bar", membership: "join" }, }; expect(room.hasMembershipState("@alice:bar", "ban")).toBe(false); }); @@ -591,7 +590,7 @@ describe("Room", function() { it("should return false if no match membership or userId", function() { room.currentState.members = { - "@alice:bar": { userId: "@alice:bar", membership: "join" } + "@alice:bar": { userId: "@alice:bar", membership: "join" }, }; expect(room.hasMembershipState("@bob:bar", "invite")).toBe(false); }); @@ -604,34 +603,38 @@ describe("Room", function() { }); describe("recalculate", function() { - var stateLookup = { + let stateLookup = { // event.type + "$" event.state_key : MatrixEvent }; - var setJoinRule = function(rule) { + let setJoinRule = function(rule) { stateLookup["m.room.join_rules$"] = utils.mkEvent({ type: "m.room.join_rules", room: roomId, user: userA, content: { - join_rule: rule - }, event: true + join_rule: rule, + }, event: true, }); }; - var setAliases = function(aliases, stateKey) { - if (!stateKey) { stateKey = "flibble"; } + let setAliases = function(aliases, stateKey) { + if (!stateKey) { + stateKey = "flibble"; +} stateLookup["m.room.aliases$" + stateKey] = utils.mkEvent({ type: "m.room.aliases", room: roomId, skey: stateKey, content: { - aliases: aliases - }, event: true + aliases: aliases, + }, event: true, }); }; - var setRoomName = function(name) { + let setRoomName = function(name) { stateLookup["m.room.name$"] = utils.mkEvent({ type: "m.room.name", room: roomId, user: userA, content: { - name: name - }, event: true + name: name, + }, event: true, }); }; - var addMember = function(userId, state, opts) { - if (!state) { state = "join"; } + let addMember = function(userId, state, opts) { + if (!state) { + state = "join"; +} opts = opts || {}; opts.room = roomId; opts.mship = state; @@ -645,37 +648,38 @@ describe("Room", function() { stateLookup = {}; room.currentState.getStateEvents.andCallFake(function(type, key) { if (key === undefined) { - var prefix = type + "$"; - var list = []; - for (var stateBlob in stateLookup) { - if (!stateLookup.hasOwnProperty(stateBlob)) { continue; } + let prefix = type + "$"; + let list = []; + for (let stateBlob in stateLookup) { + if (!stateLookup.hasOwnProperty(stateBlob)) { + continue; +} if (stateBlob.indexOf(prefix) === 0) { list.push(stateLookup[stateBlob]); } } return list; - } - else { + } else { return stateLookup[type + "$" + key]; } }); room.currentState.getMembers.andCallFake(function() { - var memberEvents = room.currentState.getStateEvents("m.room.member"); - var members = []; - for (var i = 0; i < memberEvents.length; i++) { + let memberEvents = room.currentState.getStateEvents("m.room.member"); + let members = []; + for (let i = 0; i < memberEvents.length; i++) { members.push({ name: memberEvents[i].event.content && memberEvents[i].event.content.displayname ? memberEvents[i].event.content.displayname : memberEvents[i].getStateKey(), userId: memberEvents[i].getStateKey(), - events: { member: memberEvents[i] } + events: { member: memberEvents[i] }, }); } return members; }); room.currentState.getMember.andCallFake(function(userId) { - var memberEvent = room.currentState.getStateEvents( + let memberEvent = room.currentState.getStateEvents( "m.room.member", userId ); return { @@ -684,7 +688,7 @@ describe("Room", function() { memberEvent.event.content.displayname : memberEvent.getStateKey(), userId: memberEvent.getStateKey(), - events: { member: memberEvent } + events: { member: memberEvent }, }; }); }); @@ -692,7 +696,7 @@ describe("Room", function() { describe("Room.recalculate => Stripped State Events", function() { it("should set stripped state events as actual state events if the " + "room is an invite room", function() { - var roomName = "flibble"; + let roomName = "flibble"; addMember(userA, "invite"); stateLookup["m.room.member$" + userA].event.invite_room_state = [ @@ -700,17 +704,17 @@ describe("Room", function() { type: "m.room.name", state_key: "", content: { - name: roomName - } - } + name: roomName, + }, + }, ]; room.recalculate(userA); expect(room.currentState.setStateEvents).toHaveBeenCalled(); // first call, first arg (which is an array), first element in array - var fakeEvent = room.currentState.setStateEvents.calls[0].args[0][0]; + let fakeEvent = room.currentState.setStateEvents.calls[0].args[0][0]; expect(fakeEvent.getContent()).toEqual({ - name: roomName + name: roomName, }); }); @@ -721,9 +725,9 @@ describe("Room", function() { type: "m.room.name", state_key: "", content: { - name: "flibble" - } - } + name: "flibble", + }, + }, ]; room.recalculate(userA); @@ -732,7 +736,6 @@ describe("Room", function() { }); describe("Room.recalculate => Room Name", function() { - it("should return the names of members in a private (invite join_rules)" + " room if a room name and alias don't exist and there are >3 members.", function() { @@ -742,11 +745,11 @@ describe("Room", function() { addMember(userC); addMember(userD); room.recalculate(userA); - var name = room.name; + let name = room.name; // we expect at least 1 member to be mentioned - var others = [userB, userC, userD]; - var found = false; - for (var i = 0; i < others.length; i++) { + let others = [userB, userC, userD]; + let found = false; + for (let i = 0; i < others.length; i++) { if (name.indexOf(others[i]) !== -1) { found = true; break; @@ -763,7 +766,7 @@ describe("Room", function() { addMember(userB); addMember(userC); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userC)).not.toEqual(-1, name); }); @@ -776,7 +779,7 @@ describe("Room", function() { addMember(userB); addMember(userC); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name.indexOf(userB)).not.toEqual(-1, name); expect(name.indexOf(userC)).not.toEqual(-1, name); }); @@ -788,7 +791,7 @@ describe("Room", function() { addMember(userA); addMember(userB); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name.indexOf(userB)).not.toEqual(-1, name); }); @@ -799,7 +802,7 @@ describe("Room", function() { addMember(userA); addMember(userB); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name.indexOf(userB)).not.toEqual(-1, name); }); @@ -809,47 +812,47 @@ describe("Room", function() { addMember(userA, "invite", {user: userB}); addMember(userB); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name.indexOf(userB)).not.toEqual(-1, name); }); it("should show the room alias if one exists for private " + "(invite join_rules) rooms if a room name doesn't exist.", function() { - var alias = "#room_alias:here"; + let alias = "#room_alias:here"; setJoinRule("invite"); setAliases([alias, "#another:one"]); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual(alias); }); it("should show the room alias if one exists for public " + "(public join_rules) rooms if a room name doesn't exist.", function() { - var alias = "#room_alias:here"; + let alias = "#room_alias:here"; setJoinRule("public"); setAliases([alias, "#another:one"]); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual(alias); }); it("should show the room name if one exists for private " + "(invite join_rules) rooms.", function() { - var roomName = "A mighty name indeed"; + let roomName = "A mighty name indeed"; setJoinRule("invite"); setRoomName(roomName); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual(roomName); }); it("should show the room name if one exists for public " + "(public join_rules) rooms.", function() { - var roomName = "A mighty name indeed"; + let roomName = "A mighty name indeed"; setJoinRule("public"); setRoomName(roomName); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual(roomName); }); @@ -858,7 +861,7 @@ describe("Room", function() { setJoinRule("invite"); addMember(userA); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual("Empty room"); }); @@ -867,7 +870,7 @@ describe("Room", function() { setJoinRule("public"); addMember(userA); room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual("Empty room"); }); @@ -875,7 +878,7 @@ describe("Room", function() { "alias or members in the room.", function() { room.recalculate(userA); - var name = room.name; + let name = room.name; expect(name).toEqual("Empty room"); }); @@ -886,7 +889,7 @@ describe("Room", function() { addMember(userA, 'join', {name: "Alice"}); addMember(userB, "invite", {user: userA}); room.recalculate(userB); - var name = room.name; + let name = room.name; expect(name).toEqual("Invite from Alice"); }); @@ -896,33 +899,35 @@ describe("Room", function() { addMember(userA); addMember(userB, "invite", {user: userA}); room.recalculate(userB); - var name = room.name; + let name = room.name; expect(name).toEqual("Invite from " + userA); }); - }); }); describe("receipts", function() { - - var eventToAck = utils.mkMessage({ + let eventToAck = utils.mkMessage({ room: roomId, user: userA, msg: "PLEASE ACKNOWLEDGE MY EXISTENCE", - event: true + event: true, }); function mkReceipt(roomId, records) { - var content = {}; + let content = {}; records.forEach(function(r) { - if (!content[r.eventId]) { content[r.eventId] = {}; } - if (!content[r.eventId][r.type]) { content[r.eventId][r.type] = {}; } + if (!content[r.eventId]) { + content[r.eventId] = {}; +} + if (!content[r.eventId][r.type]) { + content[r.eventId][r.type] = {}; +} content[r.eventId][r.type][r.userId] = { - ts: r.ts + ts: r.ts, }; }); return new MatrixEvent({ content: content, room_id: roomId, - type: "m.receipt" + type: "m.receipt", }); } @@ -932,36 +937,35 @@ describe("Room", function() { eventId: eventId, type: type, userId: userId, - ts: ts + ts: ts, }; } describe("addReceipt", function() { - it("should store the receipt so it can be obtained via getReceiptsForEvent", function() { - var ts = 13787898424; + let ts = 13787898424; room.addReceipt(mkReceipt(roomId, [ - mkRecord(eventToAck.getId(), "m.read", userB, ts) + mkRecord(eventToAck.getId(), "m.read", userB, ts), ])); expect(room.getReceiptsForEvent(eventToAck)).toEqual([{ type: "m.read", userId: userB, data: { - ts: ts - } + ts: ts, + }, }]); }); it("should emit an event when a receipt is added", function() { - var listener = jasmine.createSpy('spy'); + let listener = jasmine.createSpy('spy'); room.on("Room.receipt", listener); - var ts = 13787898424; + let ts = 13787898424; - var receiptEvent = mkReceipt(roomId, [ - mkRecord(eventToAck.getId(), "m.read", userB, ts) + let receiptEvent = mkReceipt(roomId, [ + mkRecord(eventToAck.getId(), "m.read", userB, ts), ]); room.addReceipt(receiptEvent); @@ -969,34 +973,34 @@ describe("Room", function() { }); it("should clobber receipts based on type and user ID", function() { - var nextEventToAck = utils.mkMessage({ + let nextEventToAck = utils.mkMessage({ room: roomId, user: userA, msg: "I AM HERE YOU KNOW", - event: true + event: true, }); - var ts = 13787898424; + let ts = 13787898424; room.addReceipt(mkReceipt(roomId, [ - mkRecord(eventToAck.getId(), "m.read", userB, ts) + mkRecord(eventToAck.getId(), "m.read", userB, ts), ])); - var ts2 = 13787899999; + let ts2 = 13787899999; room.addReceipt(mkReceipt(roomId, [ - mkRecord(nextEventToAck.getId(), "m.read", userB, ts2) + mkRecord(nextEventToAck.getId(), "m.read", userB, ts2), ])); expect(room.getReceiptsForEvent(eventToAck)).toEqual([]); expect(room.getReceiptsForEvent(nextEventToAck)).toEqual([{ type: "m.read", userId: userB, data: { - ts: ts2 - } + ts: ts2, + }, }]); }); it("should persist multiple receipts for a single event ID", function() { - var ts = 13787898424; + let ts = 13787898424; room.addReceipt(mkReceipt(roomId, [ mkRecord(eventToAck.getId(), "m.read", userB, ts), mkRecord(eventToAck.getId(), "m.read", userC, ts), - mkRecord(eventToAck.getId(), "m.read", userD, ts) + mkRecord(eventToAck.getId(), "m.read", userD, ts), ])); expect(room.getUsersReadUpTo(eventToAck)).toEqual( [userB, userC, userD] @@ -1004,19 +1008,19 @@ describe("Room", function() { }); it("should persist multiple receipts for a single receipt type", function() { - var eventTwo = utils.mkMessage({ + let eventTwo = utils.mkMessage({ room: roomId, user: userA, msg: "2222", - event: true + event: true, }); - var eventThree = utils.mkMessage({ + let eventThree = utils.mkMessage({ room: roomId, user: userA, msg: "3333", - event: true + event: true, }); - var ts = 13787898424; + let ts = 13787898424; room.addReceipt(mkReceipt(roomId, [ mkRecord(eventToAck.getId(), "m.read", userB, ts), mkRecord(eventTwo.getId(), "m.read", userC, ts), - mkRecord(eventThree.getId(), "m.read", userD, ts) + mkRecord(eventThree.getId(), "m.read", userD, ts), ])); expect(room.getUsersReadUpTo(eventToAck)).toEqual([userB]); expect(room.getUsersReadUpTo(eventTwo)).toEqual([userC]); @@ -1034,44 +1038,44 @@ describe("Room", function() { type: "m.delivered", userId: userB, data: { - ts: 13787898424 - } + ts: 13787898424, + }, }, { type: "m.read", userId: userB, data: { - ts: 22222222 - } + ts: 22222222, + }, }, { type: "m.seen", userId: userB, data: { - ts: 33333333 - } - } + ts: 33333333, + }, + }, ]); }); it("should prioritise the most recent event", function() { - var events = [ + let events = [ utils.mkMessage({ room: roomId, user: userA, msg: "1111", - event: true + event: true, }), utils.mkMessage({ room: roomId, user: userA, msg: "2222", - event: true + event: true, }), utils.mkMessage({ room: roomId, user: userA, msg: "3333", - event: true + event: true, }), ]; room.addLiveEvents(events); - var ts = 13787898424; + let ts = 13787898424; // check it initialises correctly room.addReceipt(mkReceipt(roomId, [ @@ -1094,36 +1098,31 @@ describe("Room", function() { }); describe("getUsersReadUpTo", function() { - it("should return user IDs read up to the given event", function() { - var ts = 13787898424; + let ts = 13787898424; room.addReceipt(mkReceipt(roomId, [ - mkRecord(eventToAck.getId(), "m.read", userB, ts) + mkRecord(eventToAck.getId(), "m.read", userB, ts), ])); expect(room.getUsersReadUpTo(eventToAck)).toEqual([userB]); }); - }); - }); describe("tags", function() { - function mkTags(roomId, tags) { - var content = { "tags": tags }; + let content = { "tags": tags }; return new MatrixEvent({ content: content, room_id: roomId, - type: "m.tag" + type: "m.tag", }); } describe("addTag", function() { - it("should set tags on rooms from event stream so " + "they can be obtained by the tags property", function() { - var tags = { "m.foo": { "order": 0.5 } }; + let tags = { "m.foo": { "order": 0.5 } }; room.addTags(mkTags(roomId, tags)); expect(room.tags).toEqual(tags); }); @@ -1131,11 +1130,11 @@ describe("Room", function() { it("should emit Room.tags event when new tags are " + "received on the event stream", function() { - var listener = jasmine.createSpy('spy'); + let listener = jasmine.createSpy('spy'); room.on("Room.tags", listener); - var tags = { "m.foo": { "order": 0.5 } }; - var event = mkTags(roomId, tags); + let tags = { "m.foo": { "order": 0.5 } }; + let event = mkTags(roomId, tags); room.addTags(event); expect(listener).toHaveBeenCalledWith(event, room); }); @@ -1148,18 +1147,18 @@ describe("Room", function() { describe("addPendingEvent", function() { it("should add pending events to the pendingEventList if " + "pendingEventOrdering == 'detached'", function() { - var room = new Room(roomId, { - pendingEventOrdering: "detached" + let room = new Room(roomId, { + pendingEventOrdering: "detached", }); - var eventA = utils.mkMessage({ - room: roomId, user: userA, msg: "remote 1", event: true + let eventA = utils.mkMessage({ + room: roomId, user: userA, msg: "remote 1", event: true, }); - var eventB = utils.mkMessage({ - room: roomId, user: userA, msg: "local 1", event: true + let eventB = utils.mkMessage({ + room: roomId, user: userA, msg: "local 1", event: true, }); eventB.status = EventStatus.SENDING; - var eventC = utils.mkMessage({ - room: roomId, user: userA, msg: "remote 2", event: true + let eventC = utils.mkMessage({ + room: roomId, user: userA, msg: "remote 2", event: true, }); room.addLiveEvents([eventA]); room.addPendingEvent(eventB, "TXN1"); @@ -1175,17 +1174,17 @@ describe("Room", function() { it("should add pending events to the timeline if " + "pendingEventOrdering == 'chronological'", function() { room = new Room(roomId, { - pendingEventOrdering: "chronological" + pendingEventOrdering: "chronological", }); - var eventA = utils.mkMessage({ - room: roomId, user: userA, msg: "remote 1", event: true + let eventA = utils.mkMessage({ + room: roomId, user: userA, msg: "remote 1", event: true, }); - var eventB = utils.mkMessage({ - room: roomId, user: userA, msg: "local 1", event: true + let eventB = utils.mkMessage({ + room: roomId, user: userA, msg: "local 1", event: true, }); eventB.status = EventStatus.SENDING; - var eventC = utils.mkMessage({ - room: roomId, user: userA, msg: "remote 2", event: true + let eventC = utils.mkMessage({ + room: roomId, user: userA, msg: "remote 2", event: true, }); room.addLiveEvents([eventA]); room.addPendingEvent(eventB, "TXN1"); @@ -1198,14 +1197,14 @@ describe("Room", function() { describe("updatePendingEvent", function() { it("should remove cancelled events from the pending list", function() { - var room = new Room(roomId, { - pendingEventOrdering: "detached" + let room = new Room(roomId, { + pendingEventOrdering: "detached", }); - var eventA = utils.mkMessage({ - room: roomId, user: userA, event: true + let eventA = utils.mkMessage({ + room: roomId, user: userA, event: true, }); eventA.status = EventStatus.SENDING; - var eventId = eventA.getId(); + let eventId = eventA.getId(); room.addPendingEvent(eventA, "TXN1"); expect(room.getPendingEvents()).toEqual( @@ -1216,7 +1215,7 @@ describe("Room", function() { // cancelled room.updatePendingEvent(eventA, EventStatus.NOT_SENT); - var callCount = 0; + let callCount = 0; room.on("Room.localEchoUpdated", function(event, emitRoom, oldEventId, oldStatus) { expect(event).toEqual(eventA); @@ -1234,12 +1233,12 @@ describe("Room", function() { it("should remove cancelled events from the timeline", function() { - var room = new Room(roomId); - var eventA = utils.mkMessage({ - room: roomId, user: userA, event: true + let room = new Room(roomId); + let eventA = utils.mkMessage({ + room: roomId, user: userA, event: true, }); eventA.status = EventStatus.SENDING; - var eventId = eventA.getId(); + let eventId = eventA.getId(); room.addPendingEvent(eventA, "TXN1"); expect(room.getLiveTimeline().getEvents()).toEqual( @@ -1250,7 +1249,7 @@ describe("Room", function() { // cancelled room.updatePendingEvent(eventA, EventStatus.NOT_SENT); - var callCount = 0; + let callCount = 0; room.on("Room.localEchoUpdated", function(event, emitRoom, oldEventId, oldStatus) { expect(event).toEqual(eventA); @@ -1265,6 +1264,5 @@ describe("Room", function() { expect(room.getLiveTimeline().getEvents()).toEqual([]); expect(callCount).toEqual(1); }); - }); }); diff --git a/spec/unit/scheduler.spec.js b/spec/unit/scheduler.spec.js index 68fb4581e..6c4ab34cc 100644 --- a/spec/unit/scheduler.spec.js +++ b/spec/unit/scheduler.spec.js @@ -1,22 +1,22 @@ // This file had a function whose name is all caps, which displeases eslint /* eslint new-cap: "off" */ -var q = require("q"); -var sdk = require("../.."); -var MatrixScheduler = sdk.MatrixScheduler; -var MatrixError = sdk.MatrixError; -var utils = require("../test-utils"); +let q = require("q"); +let sdk = require("../.."); +let MatrixScheduler = sdk.MatrixScheduler; +let MatrixError = sdk.MatrixError; +let utils = require("../test-utils"); describe("MatrixScheduler", function() { - var scheduler; - var retryFn, queueFn; - var defer; - var roomId = "!foo:bar"; - var eventA = utils.mkMessage({ - user: "@alice:bar", room: roomId, event: true + let scheduler; + let retryFn, queueFn; + let defer; + let roomId = "!foo:bar"; + let eventA = utils.mkMessage({ + user: "@alice:bar", room: roomId, event: true, }); - var eventB = utils.mkMessage({ - user: "@alice:bar", room: roomId, event: true + let eventB = utils.mkMessage({ + user: "@alice:bar", room: roomId, event: true, }); beforeEach(function() { @@ -45,15 +45,14 @@ describe("MatrixScheduler", function() { queueFn = function() { return "one_big_queue"; }; - var deferA = q.defer(); - var deferB = q.defer(); - var resolvedA = false; + let deferA = q.defer(); + let deferB = q.defer(); + let resolvedA = false; scheduler.setProcessFunction(function(event) { if (resolvedA) { expect(event).toEqual(eventB); return deferB.promise; - } - else { + } else { expect(event).toEqual(eventA); return deferA.promise; } @@ -70,22 +69,23 @@ describe("MatrixScheduler", function() { it("should invoke the retryFn on failure and wait the amount of time specified", function(done) { - var waitTimeMs = 1500; - var retryDefer = q.defer(); + let waitTimeMs = 1500; + let retryDefer = q.defer(); retryFn = function() { retryDefer.resolve(); return waitTimeMs; }; - queueFn = function() { return "yep"; }; + queueFn = function() { + return "yep"; +}; - var procCount = 0; + let procCount = 0; scheduler.setProcessFunction(function(ev) { procCount += 1; if (procCount === 1) { expect(ev).toEqual(eventA); return defer.promise; - } - else if (procCount === 2) { + } else if (procCount === 2) { // don't care about this defer return q.defer().promise; } @@ -111,25 +111,26 @@ describe("MatrixScheduler", function() { retryFn = function() { return -1; }; - queueFn = function() { return "yep"; }; + queueFn = function() { + return "yep"; +}; - var deferA = q.defer(); - var deferB = q.defer(); - var procCount = 0; + let deferA = q.defer(); + let deferB = q.defer(); + let procCount = 0; scheduler.setProcessFunction(function(ev) { procCount += 1; if (procCount === 1) { expect(ev).toEqual(eventA); return deferA.promise; - } - else if (procCount === 2) { + } else if (procCount === 2) { expect(ev).toEqual(eventB); return deferB.promise; } expect(procCount).toBeLessThan(3); }); - var globalA = scheduler.queueEvent(eventA); + let globalA = scheduler.queueEvent(eventA); scheduler.queueEvent(eventB); expect(procCount).toEqual(1); @@ -147,10 +148,10 @@ describe("MatrixScheduler", function() { // Expect to have processFn invoked for A&B. // Resolve A. // Expect to have processFn invoked for D. - var eventC = utils.mkMessage({user: "@a:bar", room: roomId, event: true}); - var eventD = utils.mkMessage({user: "@b:bar", room: roomId, event: true}); + let eventC = utils.mkMessage({user: "@a:bar", room: roomId, event: true}); + let eventD = utils.mkMessage({user: "@b:bar", room: roomId, event: true}); - var buckets = {}; + let buckets = {}; buckets[eventA.getId()] = "queue_A"; buckets[eventD.getId()] = "queue_A"; buckets[eventB.getId()] = "queue_B"; @@ -163,12 +164,12 @@ describe("MatrixScheduler", function() { return buckets[event.getId()]; }; - var expectOrder = [ - eventA.getId(), eventB.getId(), eventD.getId() + let expectOrder = [ + eventA.getId(), eventB.getId(), eventD.getId(), ]; - var deferA = q.defer(); + let deferA = q.defer(); scheduler.setProcessFunction(function(event) { - var id = expectOrder.shift(); + let id = expectOrder.shift(); expect(id).toEqual(event.getId()); if (expectOrder.length === 0) { done(); @@ -199,7 +200,7 @@ describe("MatrixScheduler", function() { queueFn = function() { return "yep"; }; - var prom = scheduler.queueEvent(eventA); + let prom = scheduler.queueEvent(eventA); expect(prom).toBeDefined(); expect(prom.then).toBeDefined(); }); @@ -227,15 +228,15 @@ describe("MatrixScheduler", function() { }; scheduler.queueEvent(eventA); scheduler.queueEvent(eventB); - var queue = scheduler.getQueueForEvent(eventA); + let queue = scheduler.getQueueForEvent(eventA); expect(queue.length).toEqual(2); expect(queue).toEqual([eventA, eventB]); // modify the queue - var eventC = utils.mkMessage( + let eventC = utils.mkMessage( {user: "@a:bar", room: roomId, event: true} ); queue.push(eventC); - var queueAgain = scheduler.getQueueForEvent(eventA); + let queueAgain = scheduler.getQueueForEvent(eventA); expect(queueAgain.length).toEqual(2); }); @@ -246,9 +247,9 @@ describe("MatrixScheduler", function() { }; scheduler.queueEvent(eventA); scheduler.queueEvent(eventB); - var queue = scheduler.getQueueForEvent(eventA); + let queue = scheduler.getQueueForEvent(eventA); queue[1].event.content.body = "foo"; - var queueAgain = scheduler.getQueueForEvent(eventA); + let queueAgain = scheduler.getQueueForEvent(eventA); expect(queueAgain[1].event.content.body).toEqual("foo"); }); }); @@ -282,7 +283,7 @@ describe("MatrixScheduler", function() { queueFn = function() { return "yep"; }; - var procCount = 0; + let procCount = 0; scheduler.queueEvent(eventA); scheduler.setProcessFunction(function(ev) { procCount += 1; @@ -296,7 +297,7 @@ describe("MatrixScheduler", function() { queueFn = function() { return "yep"; }; - var procCount = 0; + let procCount = 0; scheduler.setProcessFunction(function(ev) { procCount += 1; return defer.promise; @@ -310,7 +311,7 @@ describe("MatrixScheduler", function() { expect(MatrixScheduler.QUEUE_MESSAGES(eventA)).toEqual("message"); expect(MatrixScheduler.QUEUE_MESSAGES( utils.mkMembership({ - user: "@alice:bar", room: roomId, mship: "join", event: true + user: "@alice:bar", room: roomId, mship: "join", event: true, }) )).toEqual(null); }); @@ -318,16 +319,16 @@ describe("MatrixScheduler", function() { describe("RETRY_BACKOFF_RATELIMIT", function() { it("should wait at least the time given on M_LIMIT_EXCEEDED", function() { - var res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT( + let res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT( eventA, 1, new MatrixError({ - errcode: "M_LIMIT_EXCEEDED", retry_after_ms: 5000 + errcode: "M_LIMIT_EXCEEDED", retry_after_ms: 5000, }) ); expect(res >= 500).toBe(true, "Didn't wait long enough."); }); it("should give up after 5 attempts", function() { - var res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT( + let res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT( eventA, 5, {} ); expect(res).toBe(-1, "Didn't give up."); diff --git a/spec/unit/timeline-window.spec.js b/spec/unit/timeline-window.spec.js index ecdb2eaae..5e5ca862c 100644 --- a/spec/unit/timeline-window.spec.js +++ b/spec/unit/timeline-window.spec.js @@ -1,28 +1,34 @@ "use strict"; -var q = require("q"); -var sdk = require("../.."); -var EventTimeline = sdk.EventTimeline; -var TimelineWindow = sdk.TimelineWindow; -var TimelineIndex = require("../../lib/timeline-window").TimelineIndex; +let q = require("q"); +let sdk = require("../.."); +let EventTimeline = sdk.EventTimeline; +let TimelineWindow = sdk.TimelineWindow; +let TimelineIndex = require("../../lib/timeline-window").TimelineIndex; -var utils = require("../test-utils"); +let utils = require("../test-utils"); -var ROOM_ID = "roomId"; -var USER_ID = "userId"; +let ROOM_ID = "roomId"; +let USER_ID = "userId"; /* * create a timeline with a bunch (default 3) events. * baseIndex is 1 by default. */ function createTimeline(numEvents, baseIndex) { - if (numEvents === undefined) { numEvents = 3; } - if (baseIndex === undefined) { baseIndex = 1; } + if (numEvents === undefined) { + numEvents = 3; +} + if (baseIndex === undefined) { + baseIndex = 1; +} // XXX: this is a horrid hack - var timelineSet = { room: { roomId: ROOM_ID }}; - timelineSet.room.getUnfilteredTimelineSet = function() { return timelineSet; }; + let timelineSet = { room: { roomId: ROOM_ID }}; + timelineSet.room.getUnfilteredTimelineSet = function() { + return timelineSet; +}; - var timeline = new EventTimeline(timelineSet); + let timeline = new EventTimeline(timelineSet); // add the events after the baseIndex first addEventsToTimeline(timeline, numEvents - baseIndex, false); @@ -35,7 +41,7 @@ function createTimeline(numEvents, baseIndex) { } function addEventsToTimeline(timeline, numEvents, atStart) { - for (var i = 0; i < numEvents; i++) { + for (let i = 0; i < numEvents; i++) { timeline.addEvent( utils.mkMessage({ room: ROOM_ID, user: USER_ID, @@ -50,8 +56,8 @@ function addEventsToTimeline(timeline, numEvents, atStart) { * create a pair of linked timelines */ function createLinkedTimelines() { - var tl1 = createTimeline(); - var tl2 = createTimeline(); + let tl1 = createTimeline(); + let tl2 = createTimeline(); tl1.setNeighbouringTimeline(tl2, EventTimeline.FORWARDS); tl2.setNeighbouringTimeline(tl1, EventTimeline.BACKWARDS); return [tl1, tl2]; @@ -65,41 +71,41 @@ describe("TimelineIndex", function() { describe("minIndex", function() { it("should return the min index relative to BaseIndex", function() { - var timelineIndex = new TimelineIndex(createTimeline(), 0); + let timelineIndex = new TimelineIndex(createTimeline(), 0); expect(timelineIndex.minIndex()).toEqual(-1); }); }); describe("maxIndex", function() { it("should return the max index relative to BaseIndex", function() { - var timelineIndex = new TimelineIndex(createTimeline(), 0); + let timelineIndex = new TimelineIndex(createTimeline(), 0); expect(timelineIndex.maxIndex()).toEqual(2); }); }); describe("advance", function() { it("should advance up to the end of the timeline", function() { - var timelineIndex = new TimelineIndex(createTimeline(), 0); - var result = timelineIndex.advance(3); + let timelineIndex = new TimelineIndex(createTimeline(), 0); + let result = timelineIndex.advance(3); expect(result).toEqual(2); expect(timelineIndex.index).toEqual(2); }); it("should retreat back to the start of the timeline", function() { - var timelineIndex = new TimelineIndex(createTimeline(), 0); - var result = timelineIndex.advance(-2); + let timelineIndex = new TimelineIndex(createTimeline(), 0); + let result = timelineIndex.advance(-2); expect(result).toEqual(-1); expect(timelineIndex.index).toEqual(-1); }); it("should advance into the next timeline", function() { - var timelines = createLinkedTimelines(); - var tl1 = timelines[0], tl2 = timelines[1]; + let timelines = createLinkedTimelines(); + let tl1 = timelines[0], tl2 = timelines[1]; // initialise the index pointing at the end of the first timeline - var timelineIndex = new TimelineIndex(tl1, 2); + let timelineIndex = new TimelineIndex(tl1, 2); - var result = timelineIndex.advance(1); + let result = timelineIndex.advance(1); expect(result).toEqual(1); expect(timelineIndex.timeline).toBe(tl2); @@ -110,14 +116,14 @@ describe("TimelineIndex", function() { }); it("should retreat into the previous timeline", function() { - var timelines = createLinkedTimelines(); - var tl1 = timelines[0], tl2 = timelines[1]; + let timelines = createLinkedTimelines(); + let tl1 = timelines[0], tl2 = timelines[1]; // initialise the index pointing at the start of the second // timeline - var timelineIndex = new TimelineIndex(tl2, -1); + let timelineIndex = new TimelineIndex(tl2, -1); - var result = timelineIndex.advance(-1); + let result = timelineIndex.advance(-1); expect(result).toEqual(-1); expect(timelineIndex.timeline).toBe(tl1); expect(timelineIndex.index).toEqual(1); @@ -126,8 +132,8 @@ describe("TimelineIndex", function() { describe("retreat", function() { it("should retreat up to the start of the timeline", function() { - var timelineIndex = new TimelineIndex(createTimeline(), 0); - var result = timelineIndex.retreat(2); + let timelineIndex = new TimelineIndex(createTimeline(), 0); + let result = timelineIndex.retreat(2); expect(result).toEqual(1); expect(timelineIndex.index).toEqual(-1); }); @@ -140,7 +146,7 @@ describe("TimelineWindow", function() { * create a dummy eventTimelineSet and client, and a TimelineWindow * attached to them. */ - var timelineSet, client; + let timelineSet, client; function createWindow(timeline, opts) { timelineSet = {}; client = {}; @@ -158,48 +164,50 @@ describe("TimelineWindow", function() { describe("load", function() { it("should initialise from the live timeline", function(done) { - var liveTimeline = createTimeline(); - var room = {}; - room.getLiveTimeline = function() { return liveTimeline; }; + let liveTimeline = createTimeline(); + let room = {}; + room.getLiveTimeline = function() { + return liveTimeline; +}; - var timelineWindow = new TimelineWindow(undefined, room); + let timelineWindow = new TimelineWindow(undefined, room); timelineWindow.load(undefined, 2).then(function() { - var expectedEvents = liveTimeline.getEvents().slice(1); + let expectedEvents = liveTimeline.getEvents().slice(1); expect(timelineWindow.getEvents()).toEqual(expectedEvents); }).catch(utils.failTest).done(done); }); it("should initialise from a specific event", function(done) { - var timeline = createTimeline(); - var eventId = timeline.getEvents()[1].getId(); + let timeline = createTimeline(); + let eventId = timeline.getEvents()[1].getId(); - var timelineSet = {}; - var client = {}; + let timelineSet = {}; + let client = {}; client.getEventTimeline = function(timelineSet0, eventId0) { expect(timelineSet0).toBe(timelineSet); expect(eventId0).toEqual(eventId); return q(timeline); }; - var timelineWindow = new TimelineWindow(client, timelineSet); + let timelineWindow = new TimelineWindow(client, timelineSet); timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = timeline.getEvents(); + let expectedEvents = timeline.getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); }).catch(utils.failTest).done(done); }); it("canPaginate should return false until load has returned", function(done) { - var timeline = createTimeline(); + let timeline = createTimeline(); timeline.setPaginationToken("toktok1", EventTimeline.BACKWARDS); timeline.setPaginationToken("toktok2", EventTimeline.FORWARDS); - var eventId = timeline.getEvents()[1].getId(); + let eventId = timeline.getEvents()[1].getId(); - var timelineSet = {}; - var client = {}; + let timelineSet = {}; + let client = {}; - var timelineWindow = new TimelineWindow(client, timelineSet); + let timelineWindow = new TimelineWindow(client, timelineSet); client.getEventTimeline = function(timelineSet0, eventId0) { expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -210,7 +218,7 @@ describe("TimelineWindow", function() { }; timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = timeline.getEvents(); + let expectedEvents = timeline.getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) .toBe(true); @@ -223,12 +231,12 @@ describe("TimelineWindow", function() { describe("pagination", function() { it("should be able to advance across the initial timeline", function(done) { - var timeline = createTimeline(); - var eventId = timeline.getEvents()[1].getId(); - var timelineWindow = createWindow(timeline); + let timeline = createTimeline(); + let eventId = timeline.getEvents()[1].getId(); + let timelineWindow = createWindow(timeline); timelineWindow.load(eventId, 1).then(function() { - var expectedEvents = [timeline.getEvents()[1]]; + let expectedEvents = [timeline.getEvents()[1]]; expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -239,7 +247,7 @@ describe("TimelineWindow", function() { return timelineWindow.paginate(EventTimeline.FORWARDS, 2); }).then(function(success) { expect(success).toBe(true); - var expectedEvents = timeline.getEvents().slice(1); + let expectedEvents = timeline.getEvents().slice(1); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -254,7 +262,7 @@ describe("TimelineWindow", function() { return timelineWindow.paginate(EventTimeline.BACKWARDS, 2); }).then(function(success) { expect(success).toBe(true); - var expectedEvents = timeline.getEvents(); + let expectedEvents = timeline.getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -268,12 +276,12 @@ describe("TimelineWindow", function() { }); it("should advance into next timeline", function(done) { - var tls = createLinkedTimelines(); - var eventId = tls[0].getEvents()[1].getId(); - var timelineWindow = createWindow(tls[0], {windowLimit: 5}); + let tls = createLinkedTimelines(); + let eventId = tls[0].getEvents()[1].getId(); + let timelineWindow = createWindow(tls[0], {windowLimit: 5}); timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = tls[0].getEvents(); + let expectedEvents = tls[0].getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -284,7 +292,7 @@ describe("TimelineWindow", function() { return timelineWindow.paginate(EventTimeline.FORWARDS, 2); }).then(function(success) { expect(success).toBe(true); - var expectedEvents = tls[0].getEvents() + let expectedEvents = tls[0].getEvents() .concat(tls[1].getEvents().slice(0, 2)); expect(timelineWindow.getEvents()).toEqual(expectedEvents); @@ -298,7 +306,7 @@ describe("TimelineWindow", function() { expect(success).toBe(true); // the windowLimit should have made us drop an event from // tls[0] - var expectedEvents = tls[0].getEvents().slice(1) + let expectedEvents = tls[0].getEvents().slice(1) .concat(tls[1].getEvents()); expect(timelineWindow.getEvents()).toEqual(expectedEvents); @@ -313,12 +321,12 @@ describe("TimelineWindow", function() { }); it("should retreat into previous timeline", function(done) { - var tls = createLinkedTimelines(); - var eventId = tls[1].getEvents()[1].getId(); - var timelineWindow = createWindow(tls[1], {windowLimit: 5}); + let tls = createLinkedTimelines(); + let eventId = tls[1].getEvents()[1].getId(); + let timelineWindow = createWindow(tls[1], {windowLimit: 5}); timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = tls[1].getEvents(); + let expectedEvents = tls[1].getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -329,7 +337,7 @@ describe("TimelineWindow", function() { return timelineWindow.paginate(EventTimeline.BACKWARDS, 2); }).then(function(success) { expect(success).toBe(true); - var expectedEvents = tls[0].getEvents().slice(1, 3) + let expectedEvents = tls[0].getEvents().slice(1, 3) .concat(tls[1].getEvents()); expect(timelineWindow.getEvents()).toEqual(expectedEvents); @@ -343,7 +351,7 @@ describe("TimelineWindow", function() { expect(success).toBe(true); // the windowLimit should have made us drop an event from // tls[1] - var expectedEvents = tls[0].getEvents() + let expectedEvents = tls[0].getEvents() .concat(tls[1].getEvents().slice(0, 2)); expect(timelineWindow.getEvents()).toEqual(expectedEvents); @@ -358,11 +366,11 @@ describe("TimelineWindow", function() { }); it("should make forward pagination requests", function(done) { - var timeline = createTimeline(); + let timeline = createTimeline(); timeline.setPaginationToken("toktok", EventTimeline.FORWARDS); - var timelineWindow = createWindow(timeline, {windowLimit: 5}); - var eventId = timeline.getEvents()[1].getId(); + let timelineWindow = createWindow(timeline, {windowLimit: 5}); + let eventId = timeline.getEvents()[1].getId(); client.paginateEventTimeline = function(timeline0, opts) { expect(timeline0).toBe(timeline); @@ -374,7 +382,7 @@ describe("TimelineWindow", function() { }; timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = timeline.getEvents(); + let expectedEvents = timeline.getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -384,18 +392,18 @@ describe("TimelineWindow", function() { return timelineWindow.paginate(EventTimeline.FORWARDS, 2); }).then(function(success) { expect(success).toBe(true); - var expectedEvents = timeline.getEvents().slice(0, 5); + let expectedEvents = timeline.getEvents().slice(0, 5); expect(timelineWindow.getEvents()).toEqual(expectedEvents); }).catch(utils.failTest).done(done); }); it("should make backward pagination requests", function(done) { - var timeline = createTimeline(); + let timeline = createTimeline(); timeline.setPaginationToken("toktok", EventTimeline.BACKWARDS); - var timelineWindow = createWindow(timeline, {windowLimit: 5}); - var eventId = timeline.getEvents()[1].getId(); + let timelineWindow = createWindow(timeline, {windowLimit: 5}); + let eventId = timeline.getEvents()[1].getId(); client.paginateEventTimeline = function(timeline0, opts) { expect(timeline0).toBe(timeline); @@ -407,7 +415,7 @@ describe("TimelineWindow", function() { }; timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = timeline.getEvents(); + let expectedEvents = timeline.getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -417,20 +425,20 @@ describe("TimelineWindow", function() { return timelineWindow.paginate(EventTimeline.BACKWARDS, 2); }).then(function(success) { expect(success).toBe(true); - var expectedEvents = timeline.getEvents().slice(1, 6); + let expectedEvents = timeline.getEvents().slice(1, 6); expect(timelineWindow.getEvents()).toEqual(expectedEvents); }).catch(utils.failTest).done(done); }); it("should limit the number of unsuccessful pagination requests", function(done) { - var timeline = createTimeline(); + let timeline = createTimeline(); timeline.setPaginationToken("toktok", EventTimeline.FORWARDS); - var timelineWindow = createWindow(timeline, {windowLimit: 5}); - var eventId = timeline.getEvents()[1].getId(); + let timelineWindow = createWindow(timeline, {windowLimit: 5}); + let eventId = timeline.getEvents()[1].getId(); - var paginateCount = 0; + let paginateCount = 0; client.paginateEventTimeline = function(timeline0, opts) { expect(timeline0).toBe(timeline); expect(opts.backwards).toBe(false); @@ -440,7 +448,7 @@ describe("TimelineWindow", function() { }; timelineWindow.load(eventId, 3).then(function() { - var expectedEvents = timeline.getEvents(); + let expectedEvents = timeline.getEvents(); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) @@ -451,7 +459,7 @@ describe("TimelineWindow", function() { }).then(function(success) { expect(success).toBe(false); expect(paginateCount).toEqual(3); - var expectedEvents = timeline.getEvents().slice(0, 3); + let expectedEvents = timeline.getEvents().slice(0, 3); expect(timelineWindow.getEvents()).toEqual(expectedEvents); expect(timelineWindow.canPaginate(EventTimeline.BACKWARDS)) diff --git a/spec/unit/user.spec.js b/spec/unit/user.spec.js index e4df82010..1ed0a0206 100644 --- a/spec/unit/user.spec.js +++ b/spec/unit/user.spec.js @@ -1,11 +1,11 @@ "use strict"; -var sdk = require("../.."); -var User = sdk.User; -var utils = require("../test-utils"); +let sdk = require("../.."); +let User = sdk.User; +let utils = require("../test-utils"); describe("User", function() { - var userId = "@alice:bar"; - var user; + let userId = "@alice:bar"; + let user; beforeEach(function() { utils.beforeEach(this); // eslint-disable-line no-invalid-this @@ -13,18 +13,18 @@ describe("User", function() { }); describe("setPresenceEvent", function() { - var event = utils.mkEvent({ + let event = utils.mkEvent({ type: "m.presence", content: { presence: "online", user_id: userId, displayname: "Alice", last_active_ago: 1085, - avatar_url: "mxc://foo/bar" - }, event: true + avatar_url: "mxc://foo/bar", + }, event: true, }); it("should emit 'User.displayName' if the display name changes", function() { - var emitCount = 0; + let emitCount = 0; user.on("User.displayName", function(ev, usr) { emitCount += 1; }); @@ -35,7 +35,7 @@ describe("User", function() { }); it("should emit 'User.avatarUrl' if the avatar URL changes", function() { - var emitCount = 0; + let emitCount = 0; user.on("User.avatarUrl", function(ev, usr) { emitCount += 1; }); @@ -46,7 +46,7 @@ describe("User", function() { }); it("should emit 'User.presence' if the presence changes", function() { - var emitCount = 0; + let emitCount = 0; user.on("User.presence", function(ev, usr) { emitCount += 1; }); diff --git a/spec/unit/utils.spec.js b/spec/unit/utils.spec.js index 49324c18a..55808b9e9 100644 --- a/spec/unit/utils.spec.js +++ b/spec/unit/utils.spec.js @@ -1,6 +1,6 @@ "use strict"; -var utils = require("../../lib/utils"); -var testUtils = require("../test-utils"); +let utils = require("../../lib/utils"); +let testUtils = require("../test-utils"); describe("utils", function() { beforeEach(function() { @@ -9,9 +9,9 @@ describe("utils", function() { describe("encodeParams", function() { it("should url encode and concat with &s", function() { - var params = { + let params = { foo: "bar", - baz: "beer@" + baz: "beer@", }; expect(utils.encodeParams(params)).toEqual( "foo=bar&baz=beer%40" @@ -21,10 +21,10 @@ describe("utils", function() { describe("encodeUri", function() { it("should replace based on object keys and url encode", function() { - var path = "foo/bar/%something/%here"; - var vals = { + let path = "foo/bar/%something/%here"; + let vals = { "%something": "baz", - "%here": "beer@" + "%here": "beer@", }; expect(utils.encodeUri(path, vals)).toEqual( "foo/bar/baz/beer%40" @@ -34,7 +34,7 @@ describe("utils", function() { describe("forEach", function() { it("should be invoked for each element", function() { - var arr = []; + let arr = []; utils.forEach([55, 66, 77], function(element) { arr.push(element); }); @@ -44,38 +44,50 @@ describe("utils", function() { describe("findElement", function() { it("should find only 1 element if there is a match", function() { - var matchFn = function() { return true; }; - var arr = [55, 66, 77]; + let matchFn = function() { + return true; +}; + let arr = [55, 66, 77]; expect(utils.findElement(arr, matchFn)).toEqual(55); }); it("should be able to find in reverse order", function() { - var matchFn = function() { return true; }; - var arr = [55, 66, 77]; + let matchFn = function() { + return true; +}; + let arr = [55, 66, 77]; expect(utils.findElement(arr, matchFn, true)).toEqual(77); }); it("should find nothing if the function never returns true", function() { - var matchFn = function() { return false; }; - var arr = [55, 66, 77]; + let matchFn = function() { + return false; +}; + let arr = [55, 66, 77]; expect(utils.findElement(arr, matchFn)).toBeFalsy(); }); }); describe("removeElement", function() { it("should remove only 1 element if there is a match", function() { - var matchFn = function() { return true; }; - var arr = [55, 66, 77]; + let matchFn = function() { + return true; +}; + let arr = [55, 66, 77]; utils.removeElement(arr, matchFn); expect(arr).toEqual([66, 77]); }); it("should be able to remove in reverse order", function() { - var matchFn = function() { return true; }; - var arr = [55, 66, 77]; + let matchFn = function() { + return true; +}; + let arr = [55, 66, 77]; utils.removeElement(arr, matchFn, true); expect(arr).toEqual([55, 66]); }); it("should remove nothing if the function never returns true", function() { - var matchFn = function() { return false; }; - var arr = [55, 66, 77]; + let matchFn = function() { + return false; +}; + let arr = [55, 66, 77]; utils.removeElement(arr, matchFn); expect(arr).toEqual(arr); }); @@ -92,7 +104,7 @@ describe("utils", function() { expect(utils.isFunction(555)).toBe(false); expect(utils.isFunction(function() {})).toBe(true); - var s = { foo: function() {} }; + let s = { foo: function() {} }; expect(utils.isFunction(s.foo)).toBe(true); }); }); @@ -113,30 +125,42 @@ describe("utils", function() { describe("checkObjectHasKeys", function() { it("should throw for missing keys", function() { - expect(function() { utils.checkObjectHasKeys({}, ["foo"]); }).toThrow(); - expect(function() { utils.checkObjectHasKeys({ - foo: "bar" - }, ["foo"]); }).not.toThrow(); + expect(function() { + utils.checkObjectHasKeys({}, ["foo"]); +}).toThrow(); + expect(function() { + utils.checkObjectHasKeys({ + foo: "bar", + }, ["foo"]); +}).not.toThrow(); }); }); describe("checkObjectHasNoAdditionalKeys", function() { it("should throw for extra keys", function() { - expect(function() { utils.checkObjectHasNoAdditionalKeys({ + expect(function() { + utils.checkObjectHasNoAdditionalKeys({ foo: "bar", - baz: 4 - }, ["foo"]); }).toThrow(); + baz: 4, + }, ["foo"]); +}).toThrow(); - expect(function() { utils.checkObjectHasNoAdditionalKeys({ - foo: "bar" - }, ["foo"]); }).not.toThrow(); + expect(function() { + utils.checkObjectHasNoAdditionalKeys({ + foo: "bar", + }, ["foo"]); +}).not.toThrow(); }); }); describe("deepCompare", function() { - var assert = { - isTrue: function(x) { expect(x).toBe(true); }, - isFalse: function(x) { expect(x).toBe(false); }, + let assert = { + isTrue: function(x) { + expect(x).toBe(true); +}, + isFalse: function(x) { + expect(x).toBe(false); +}, }; it("should handle primitives", function() { @@ -150,7 +174,7 @@ describe("utils", function() { it("should handle regexps", function() { assert.isTrue(utils.deepCompare(/abc/, /abc/)); assert.isFalse(utils.deepCompare(/abc/, /123/)); - var r = /abc/; + let r = /abc/; assert.isTrue(utils.deepCompare(r, r)); }); @@ -192,8 +216,12 @@ describe("utils", function() { // no two different function is equal really, they capture their // context variables so even if they have same toString(), they // won't have same functionality - var func = function(x) { return true; }; - var func2 = function(x) { return true; }; + let func = function(x) { + return true; +}; + let func2 = function(x) { + return true; +}; assert.isTrue(utils.deepCompare(func, func)); assert.isFalse(utils.deepCompare(func, func2)); assert.isTrue(utils.deepCompare({ a: { b: func } }, { a: { b: func } })); @@ -203,17 +231,17 @@ describe("utils", function() { describe("extend", function() { - var SOURCE = { "prop2": 1, "string2": "x", "newprop": "new" }; + let SOURCE = { "prop2": 1, "string2": "x", "newprop": "new" }; it("should extend", function() { - var target = { + let target = { "prop1": 5, "prop2": 7, "string1": "baz", "string2": "foo", }; - var merged = { + let merged = { "prop1": 5, "prop2": 1, "string1": "baz", "string2": "x", "newprop": "new", }; - var source_orig = JSON.stringify(SOURCE); + let source_orig = JSON.stringify(SOURCE); utils.extend(target, SOURCE); expect(JSON.stringify(target)).toEqual(JSON.stringify(merged)); @@ -223,14 +251,14 @@ describe("utils", function() { }); it("should ignore null", function() { - var target = { + let target = { "prop1": 5, "prop2": 7, "string1": "baz", "string2": "foo", }; - var merged = { + let merged = { "prop1": 5, "prop2": 1, "string1": "baz", "string2": "x", "newprop": "new", }; - var source_orig = JSON.stringify(SOURCE); + let source_orig = JSON.stringify(SOURCE); utils.extend(target, null, SOURCE); expect(JSON.stringify(target)).toEqual(JSON.stringify(merged)); @@ -240,21 +268,21 @@ describe("utils", function() { }); it("should handle properties created with defineProperties", function() { - var source = Object.defineProperties({}, { + let source = Object.defineProperties({}, { "enumerableProp": { get: function() { return true; }, - enumerable: true + enumerable: true, }, "nonenumerableProp": { get: function() { return true; - } - } + }, + }, }); - var target = {}; + let target = {}; utils.extend(target, source); expect(target.enumerableProp).toBe(true); expect(target.nonenumerableProp).toBe(undefined); diff --git a/src/base-apis.js b/src/base-apis.js index 47c831c83..88f4239e4 100644 --- a/src/base-apis.js +++ b/src/base-apis.js @@ -22,8 +22,8 @@ limitations under the License. * @module base-apis */ -var httpApi = require("./http-api"); -var utils = require("./utils"); +let httpApi = require("./http-api"); +let 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; - var httpOpts = { + let httpOpts = { baseUrl: opts.baseUrl, idBaseUrl: opts.idBaseUrl, accessToken: opts.accessToken, @@ -68,7 +68,7 @@ function MatrixBaseApis(opts) { prefix: httpApi.PREFIX_R0, onlyData: true, extraParams: opts.queryParams, - localTimeoutMs: opts.localTimeoutMs + localTimeoutMs: opts.localTimeoutMs, }; this._http = new httpApi.MatrixHttpApi(this, httpOpts); @@ -135,15 +135,25 @@ MatrixBaseApis.prototype.register = function( sessionId, auth, bindEmail, guestAccessToken, callback ) { - if (auth === undefined) { auth = {}; } - if (sessionId) { auth.session = sessionId; } + if (auth === undefined) { + auth = {}; +} + if (sessionId) { + auth.session = sessionId; +} - var params = { - auth: auth + let params = { + auth: auth, }; - if (username !== undefined && username !== null) { params.username = username; } - if (password !== undefined && password !== null) { params.password = password; } - if (bindEmail !== undefined && bindEmail !== null) { params.bind_email = bindEmail; } + if (username !== undefined && username !== null) { + params.username = username; +} + if (password !== undefined && password !== null) { + params.password = password; +} + if (bindEmail !== undefined && bindEmail !== null) { + params.bind_email = bindEmail; +} if (guestAccessToken !== undefined && guestAccessToken !== null) { params.guest_access_token = guestAccessToken; } @@ -173,8 +183,10 @@ MatrixBaseApis.prototype.registerGuest = function(opts, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.registerRequest = function(data, kind, callback) { - var params = {}; - if (kind) { params.kind = kind; } + let params = {}; + if (kind) { + params.kind = kind; +} return this._http.request( callback, "POST", "/register", params, data @@ -198,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) { - var login_data = { + let login_data = { type: loginType, }; @@ -220,7 +232,7 @@ MatrixBaseApis.prototype.login = function(loginType, data, callback) { MatrixBaseApis.prototype.loginWithPassword = function(user, password, callback) { return this.login("m.login.password", { user: user, - password: password + password: password, }, callback); }; @@ -232,7 +244,7 @@ MatrixBaseApis.prototype.loginWithPassword = function(user, password, callback) */ MatrixBaseApis.prototype.loginWithSAML2 = function(relayState, callback) { return this.login("m.login.saml2", { - relay_state: relayState + relay_state: relayState, }, callback); }; @@ -243,7 +255,7 @@ MatrixBaseApis.prototype.loginWithSAML2 = function(relayState, callback) { */ MatrixBaseApis.prototype.getCasLoginUrl = function(redirectUrl) { return this._http.getUrl("/login/cas/redirect", { - "redirectUrl": redirectUrl + "redirectUrl": redirectUrl, }, httpApi.PREFIX_UNSTABLE); }; @@ -255,7 +267,7 @@ MatrixBaseApis.prototype.getCasLoginUrl = function(redirectUrl) { */ MatrixBaseApis.prototype.loginWithToken = function(token, callback) { return this.login("m.login.token", { - token: token + token: token, }, callback); }; @@ -286,7 +298,7 @@ MatrixBaseApis.prototype.logout = function(callback) { * @return {module:client.Promise} Resolves: On success, the empty object */ MatrixBaseApis.prototype.deactivateAccount = function(auth, callback) { - var body = {}; + let body = {}; if (auth) { body = { auth: auth, @@ -306,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) { - var path = utils.encodeUri("/auth/$loginType/fallback/web", { + let path = utils.encodeUri("/auth/$loginType/fallback/web", { $loginType: loginType, }); @@ -346,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) { - var path = utils.encodeUri("/rooms/$roomId/state", {$roomId: roomId}); + let path = utils.encodeUri("/rooms/$roomId/state", {$roomId: roomId}); return this._http.authedRequest(callback, "GET", path); }; @@ -360,12 +372,12 @@ MatrixBaseApis.prototype.roomState = function(roomId, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getStateEvent = function(roomId, eventType, stateKey, callback) { - var pathParams = { + let pathParams = { $roomId: roomId, $eventType: eventType, - $stateKey: stateKey + $stateKey: stateKey, }; - var path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); + let path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); if (stateKey !== undefined) { path = utils.encodeUri(path + "/$stateKey", pathParams); } @@ -385,12 +397,12 @@ MatrixBaseApis.prototype.getStateEvent = function(roomId, eventType, stateKey, c */ MatrixBaseApis.prototype.sendStateEvent = function(roomId, eventType, content, stateKey, callback) { - var pathParams = { + let pathParams = { $roomId: roomId, $eventType: eventType, - $stateKey: stateKey + $stateKey: stateKey, }; - var path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); + let path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); if (stateKey !== undefined) { path = utils.encodeUri(path + "/$stateKey", pathParams); } @@ -407,9 +419,9 @@ 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) { - var path = utils.encodeUri("/rooms/$roomId/redact/$eventId", { + let path = utils.encodeUri("/rooms/$roomId/redact/$eventId", { $roomId: roomId, - $eventId: eventId + $eventId: eventId, }); return this._http.authedRequest(callback, "POST", path, undefined, {}); }; @@ -422,8 +434,10 @@ MatrixBaseApis.prototype.redactEvent = function(roomId, eventId, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.roomInitialSync = function(roomId, limit, callback) { - if (utils.isFunction(limit)) { callback = limit; limit = undefined; } - var path = utils.encodeUri("/rooms/$roomId/initialSync", + if (utils.isFunction(limit)) { + callback = limit; limit = undefined; +} + let path = utils.encodeUri("/rooms/$roomId/initialSync", {$roomId: roomId} ); if (!limit) { @@ -460,7 +474,7 @@ MatrixBaseApis.prototype.publicRooms = function(options, callback) { options = {}; } - var query_params = {}; + let query_params = {}; if (options.server) { query_params.server = options.server; delete options.server; @@ -484,11 +498,11 @@ MatrixBaseApis.prototype.publicRooms = function(options, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.createAlias = function(alias, roomId, callback) { - var path = utils.encodeUri("/directory/room/$alias", { - $alias: alias + let path = utils.encodeUri("/directory/room/$alias", { + $alias: alias, }); - var data = { - room_id: roomId + let data = { + room_id: roomId, }; return this._http.authedRequest( callback, "PUT", path, undefined, data @@ -504,8 +518,8 @@ MatrixBaseApis.prototype.createAlias = function(alias, roomId, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deleteAlias = function(alias, callback) { - var path = utils.encodeUri("/directory/room/$alias", { - $alias: alias + let path = utils.encodeUri("/directory/room/$alias", { + $alias: alias, }); return this._http.authedRequest( callback, "DELETE", path, undefined, undefined @@ -521,8 +535,8 @@ MatrixBaseApis.prototype.deleteAlias = function(alias, callback) { */ MatrixBaseApis.prototype.getRoomIdForAlias = function(alias, callback) { // TODO: deprecate this or resolveRoomAlias - var path = utils.encodeUri("/directory/room/$alias", { - $alias: alias + let path = utils.encodeUri("/directory/room/$alias", { + $alias: alias, }); return this._http.authedRequest( callback, "GET", path @@ -537,7 +551,7 @@ MatrixBaseApis.prototype.getRoomIdForAlias = function(alias, callback) { */ MatrixBaseApis.prototype.resolveRoomAlias = function(roomAlias, callback) { // TODO: deprecate this or getRoomIdForAlias - var path = utils.encodeUri("/directory/room/$alias", {$alias: roomAlias}); + let path = utils.encodeUri("/directory/room/$alias", {$alias: roomAlias}); return this._http.request(callback, "GET", path); }; @@ -550,8 +564,8 @@ MatrixBaseApis.prototype.resolveRoomAlias = function(roomAlias, callback) { */ MatrixBaseApis.prototype.getRoomDirectoryVisibility = function(roomId, callback) { - var path = utils.encodeUri("/directory/list/room/$roomId", { - $roomId: roomId + let path = utils.encodeUri("/directory/list/room/$roomId", { + $roomId: roomId, }); return this._http.authedRequest(callback, "GET", path); }; @@ -568,8 +582,8 @@ MatrixBaseApis.prototype.getRoomDirectoryVisibility = */ MatrixBaseApis.prototype.setRoomDirectoryVisibility = function(roomId, visibility, callback) { - var path = utils.encodeUri("/directory/list/room/$roomId", { - $roomId: roomId + let path = utils.encodeUri("/directory/list/room/$roomId", { + $roomId: roomId, }); return this._http.authedRequest( callback, "PUT", path, undefined, { "visibility": visibility } @@ -591,9 +605,9 @@ MatrixBaseApis.prototype.setRoomDirectoryVisibility = */ MatrixBaseApis.prototype.setRoomDirectoryVisibilityAppService = function(networkId, roomId, visibility, callback) { - var path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", { + let path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", { $networkId: networkId, - $roomId: roomId + $roomId: roomId, }); return this._http.authedRequest( callback, "PUT", path, undefined, { "visibility": visibility } @@ -674,9 +688,11 @@ MatrixBaseApis.prototype.getCurrentUploads = function() { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getProfileInfo = function(userId, info, callback) { - if (utils.isFunction(info)) { callback = info; info = undefined; } + if (utils.isFunction(info)) { + callback = info; info = undefined; +} - var path = info ? + let path = info ? utils.encodeUri("/profile/$userId/$info", { $userId: userId, $info: info }) : utils.encodeUri("/profile/$userId", @@ -694,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) { - var path = "/account/3pid"; + let path = "/account/3pid"; return this._http.authedRequest( callback, "GET", path, undefined, undefined ); @@ -708,10 +724,10 @@ MatrixBaseApis.prototype.getThreePids = function(callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addThreePid = function(creds, bind, callback) { - var path = "/account/3pid"; - var data = { + let path = "/account/3pid"; + let data = { 'threePidCreds': creds, - 'bind': bind + 'bind': bind, }; return this._http.authedRequest( callback, "POST", path, null, data @@ -727,10 +743,10 @@ MatrixBaseApis.prototype.addThreePid = function(creds, bind, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deleteThreePid = function(medium, address) { - var path = "/account/3pid/delete"; - var data = { + let path = "/account/3pid/delete"; + let data = { 'medium': medium, - 'address': address + 'address': address, }; return this._http.authedRequestWithPrefix( undefined, "POST", path, null, data, httpApi.PREFIX_UNSTABLE @@ -746,10 +762,10 @@ MatrixBaseApis.prototype.deleteThreePid = function(medium, address) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setPassword = function(authDict, newPassword, callback) { - var path = "/account/password"; - var data = { + let path = "/account/password"; + let data = { 'auth': authDict, - 'new_password': newPassword + 'new_password': newPassword, }; return this._http.authedRequest( @@ -767,7 +783,7 @@ MatrixBaseApis.prototype.setPassword = function(authDict, newPassword, callback) * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getDevices = function() { - var path = "/devices"; + let path = "/devices"; return this._http.authedRequestWithPrefix( undefined, "GET", path, undefined, undefined, httpApi.PREFIX_UNSTABLE @@ -783,7 +799,7 @@ MatrixBaseApis.prototype.getDevices = function() { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setDeviceDetails = function(device_id, body) { - var path = utils.encodeUri("/devices/$device_id", { + let path = utils.encodeUri("/devices/$device_id", { $device_id: device_id, }); @@ -803,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) { - var path = utils.encodeUri("/devices/$device_id", { + let path = utils.encodeUri("/devices/$device_id", { $device_id: device_id, }); - var body = {}; + let body = {}; if (auth) { body.auth = auth; @@ -831,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) { - var path = "/pushers"; + let path = "/pushers"; return this._http.authedRequest( callback, "GET", path, undefined, undefined ); @@ -846,7 +862,7 @@ MatrixBaseApis.prototype.getPushers = function(callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setPusher = function(pusher, callback) { - var path = "/pushers/set"; + let path = "/pushers/set"; return this._http.authedRequest( callback, "POST", path, null, pusher ); @@ -872,9 +888,9 @@ MatrixBaseApis.prototype.getPushRules = function(callback) { */ MatrixBaseApis.prototype.addPushRule = function(scope, kind, ruleId, body, callback) { // NB. Scope not uri encoded because devices need the '/' - var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { + let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { $kind: kind, - $ruleId: ruleId + $ruleId: ruleId, }); return this._http.authedRequest( callback, "PUT", path, undefined, body @@ -891,9 +907,9 @@ 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 '/' - var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { + let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { $kind: kind, - $ruleId: ruleId + $ruleId: ruleId, }); return this._http.authedRequest(callback, "DELETE", path); }; @@ -910,9 +926,9 @@ MatrixBaseApis.prototype.deletePushRule = function(scope, kind, ruleId, callback */ MatrixBaseApis.prototype.setPushRuleEnabled = function(scope, kind, ruleId, enabled, callback) { - var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", { + let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", { $kind: kind, - $ruleId: ruleId + $ruleId: ruleId, }); return this._http.authedRequest( callback, "PUT", path, undefined, {"enabled": enabled} @@ -931,9 +947,9 @@ MatrixBaseApis.prototype.setPushRuleEnabled = function(scope, kind, */ MatrixBaseApis.prototype.setPushRuleActions = function(scope, kind, ruleId, actions, callback) { - var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", { + let path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", { $kind: kind, - $ruleId: ruleId + $ruleId: ruleId, }); return this._http.authedRequest( callback, "PUT", path, undefined, {"actions": actions} @@ -954,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) { - var queryparams = {}; + let queryparams = {}; if (opts.next_batch) { queryparams.next_batch = opts.next_batch; } @@ -983,8 +999,8 @@ MatrixBaseApis.prototype.search = function(opts, callback) { */ MatrixBaseApis.prototype.uploadKeysRequest = function(content, opts, callback) { opts = opts || {}; - var deviceId = opts.device_id; - var path; + let deviceId = opts.device_id; + let path; if (deviceId) { path = utils.encodeUri("/keys/upload/$deviceId", { $deviceId: deviceId, @@ -1008,12 +1024,12 @@ MatrixBaseApis.prototype.uploadKeysRequest = function(content, opts, callback) { * an error response ({@link module:http-api.MatrixError}). */ MatrixBaseApis.prototype.downloadKeysForUsers = function(userIds, callback) { - var downloadQuery = {}; + let downloadQuery = {}; - for (var i = 0; i < userIds.length; ++i) { + for (let i = 0; i < userIds.length; ++i) { downloadQuery[userIds[i]] = {}; } - var content = {device_keys: downloadQuery}; + let content = {device_keys: downloadQuery}; return this._http.authedRequestWithPrefix( callback, "POST", "/keys/query", undefined, content, httpApi.PREFIX_UNSTABLE @@ -1031,20 +1047,20 @@ MatrixBaseApis.prototype.downloadKeysForUsers = function(userIds, callback) { * an error response ({@link module:http-api.MatrixError}). */ MatrixBaseApis.prototype.claimOneTimeKeys = function(devices, key_algorithm) { - var queries = {}; + let queries = {}; if (key_algorithm === undefined) { key_algorithm = "signed_curve25519"; } - for (var i = 0; i < devices.length; ++i) { - var userId = devices[i][0]; - var deviceId = devices[i][1]; - var query = queries[userId] || {}; + for (let i = 0; i < devices.length; ++i) { + let userId = devices[i][0]; + let deviceId = devices[i][1]; + let query = queries[userId] || {}; queries[userId] = query; query[deviceId] = key_algorithm; } - var content = {one_time_keys: queries}; + let content = {one_time_keys: queries}; return this._http.authedRequestWithPrefix( undefined, "POST", "/keys/claim", undefined, content, httpApi.PREFIX_UNSTABLE @@ -1077,11 +1093,11 @@ MatrixBaseApis.prototype.claimOneTimeKeys = function(devices, key_algorithm) { */ MatrixBaseApis.prototype.requestEmailToken = function(email, clientSecret, sendAttempt, nextLink, callback) { - var params = { + let params = { client_secret: clientSecret, email: email, send_attempt: sendAttempt, - next_link: nextLink + next_link: nextLink, }; return this._http.idServerRequest( callback, "POST", "/validate/email/requestToken", @@ -1101,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) { - var params = { + let params = { medium: medium, address: address, }; @@ -1128,12 +1144,12 @@ MatrixBaseApis.prototype.lookupThreePid = function(medium, address, callback) { MatrixBaseApis.prototype.sendToDevice = function( eventType, contentMap, txnId ) { - var path = utils.encodeUri("/sendToDevice/$eventType/$txnId", { + let path = utils.encodeUri("/sendToDevice/$eventType/$txnId", { $eventType: eventType, $txnId: txnId ? txnId : this.makeTxnId(), }); - var body = { + let body = { messages: contentMap, }; @@ -1167,8 +1183,8 @@ MatrixBaseApis.prototype.getThirdpartyProtocols = function() { * @return {module:client.Promise} Resolves to the result object */ MatrixBaseApis.prototype.getThirdpartyLocation = function(protocol, params) { - var path = utils.encodeUri("/thirdparty/location/$protocol", { - $protocol: protocol + let path = utils.encodeUri("/thirdparty/location/$protocol", { + $protocol: protocol, }); return this._http.authedRequestWithPrefix( diff --git a/src/client.js b/src/client.js index c6a92d09b..8d6f8e94e 100644 --- a/src/client.js +++ b/src/client.js @@ -15,32 +15,32 @@ limitations under the License. */ "use strict"; -var PushProcessor = require('./pushprocessor'); +let PushProcessor = require('./pushprocessor'); /** * This is an internal module. See {@link MatrixClient} for the public class. * @module client */ -var EventEmitter = require("events").EventEmitter; -var q = require("q"); -var url = require('url'); +let EventEmitter = require("events").EventEmitter; +let q = require("q"); +let url = require('url'); -var httpApi = require("./http-api"); -var MatrixEvent = require("./models/event").MatrixEvent; -var EventStatus = require("./models/event").EventStatus; -var EventTimeline = require("./models/event-timeline"); -var SearchResult = require("./models/search-result"); -var StubStore = require("./store/stub"); -var webRtcCall = require("./webrtc/call"); -var utils = require("./utils"); -var contentRepo = require("./content-repo"); -var Filter = require("./filter"); -var SyncApi = require("./sync"); -var MatrixBaseApis = require("./base-apis"); -var MatrixError = httpApi.MatrixError; +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; -var SCROLLBACK_DELAY_MS = 3000; -var CRYPTO_ENABLED = false; +let SCROLLBACK_DELAY_MS = 3000; +let CRYPTO_ENABLED = false; try { var Crypto = require("./crypto"); @@ -111,16 +111,16 @@ function MatrixClient(opts) { this.deviceId = opts.deviceId || null; - var userId = (opts.userId || null); + let userId = (opts.userId || null); this.credentials = { userId: userId, }; this.scheduler = opts.scheduler; if (this.scheduler) { - var self = this; + let self = this; this.scheduler.setProcessFunction(function(eventToSend) { - var room = self.getRoom(eventToSend.getRoomId()); + let 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. - var call = webRtcCall.createNewMatrixCall(this); + let call = webRtcCall.createNewMatrixCall(this); this._supportsVoip = false; if (call) { setupCallEventHandler(this); @@ -211,7 +211,9 @@ MatrixClient.prototype.supportsVoip = function() { * @see module:client~MatrixClient#event:"sync" */ MatrixClient.prototype.getSyncState = function() { - if (!this._syncApi) { return null; } + if (!this._syncApi) { + return null; +} return this._syncApi.getSyncState(); }; @@ -425,7 +427,7 @@ MatrixClient.prototype.getEventSenderDeviceInfo = function(event) { * {@link module:client~MatrixClient#setDeviceVerified|setDeviceVerified}. */ MatrixClient.prototype.isEventSenderVerified = function(event) { - var device = this.getEventSenderDeviceInfo(event); + let device = this.getEventSenderDeviceInfo(event); if (!device) { return false; } @@ -545,7 +547,7 @@ MatrixClient.prototype.getUsers = function() { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setAccountData = function(eventType, contents, callback) { - var path = utils.encodeUri("/user/$userId/account_data/$type", { + let path = utils.encodeUri("/user/$userId/account_data/$type", { $userId: this.credentials.userId, $type: eventType, }); @@ -586,14 +588,16 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) { throw new Error("Expected 'opts' object, got function."); } opts = opts || {}; - if (opts.syncRoom === undefined) { opts.syncRoom = true; } + if (opts.syncRoom === undefined) { + opts.syncRoom = true; +} - var room = this.getRoom(roomIdOrAlias); + let room = this.getRoom(roomIdOrAlias); if (room && room.hasMembershipState(this.credentials.userId, "join")) { return q(room); } - var sign_promise = q(); + let sign_promise = q(); if (opts.inviteSignUrl) { sign_promise = this._http.requestOtherUrl( @@ -602,21 +606,21 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) { ); } - var defer = q.defer(); + let defer = q.defer(); - var self = this; + let self = this; sign_promise.then(function(signed_invite_object) { - var data = {}; + let data = {}; if (signed_invite_object) { data.third_party_signed = signed_invite_object; } - var path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias}); + let path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias}); return self._http.authedRequest(undefined, "POST", path, undefined, data); }).then(function(res) { - var roomId = res.room_id; - var syncApi = new SyncApi(self, self._clientOpts); - var room = syncApi.createRoom(roomId); + let roomId = res.room_id; + let syncApi = new SyncApi(self, self._clientOpts); + let room = syncApi.createRoom(roomId); if (opts.syncRoom) { // v2 will do this for us // return syncApi.syncRoom(room); @@ -661,7 +665,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. - var room = this.getRoom(event.getRoomId()); + let room = this.getRoom(event.getRoomId()); _updatePendingEventStatus(room, event, EventStatus.CANCELLED); }; @@ -696,7 +700,7 @@ MatrixClient.prototype.setRoomTopic = function(roomId, topic, callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getRoomTags = function(roomId, callback) { - var path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/", { + let path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/", { $userId: this.credentials.userId, $roomId: roomId, }); @@ -714,7 +718,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) { - var path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { + let path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { $userId: this.credentials.userId, $roomId: roomId, $tag: tagName, @@ -732,7 +736,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) { - var path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { + let path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { $userId: this.credentials.userId, $roomId: roomId, $tag: tagName, @@ -752,7 +756,7 @@ MatrixClient.prototype.deleteRoomTag = function(roomId, tagName, callback) { */ MatrixClient.prototype.setRoomAccountData = function(roomId, eventType, content, callback) { - var path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", { + let path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", { $userId: this.credentials.userId, $roomId: roomId, $type: eventType, @@ -774,8 +778,8 @@ MatrixClient.prototype.setRoomAccountData = function(roomId, eventType, */ MatrixClient.prototype.setPowerLevel = function(roomId, userId, powerLevel, event, callback) { - var content = { - users: {} + let content = { + users: {}, }; if (event && event.getType() === "m.room.power_levels") { // take a copy of the content to ensure we don't corrupt @@ -783,8 +787,8 @@ MatrixClient.prototype.setPowerLevel = function(roomId, userId, powerLevel, content = utils.deepCopy(event.getContent()); } content.users[userId] = powerLevel; - var path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", { - $roomId: roomId + let path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", { + $roomId: roomId, }); return this._http.authedRequest( callback, "PUT", path, undefined, content @@ -802,7 +806,9 @@ MatrixClient.prototype.setPowerLevel = function(roomId, userId, powerLevel, */ MatrixClient.prototype.sendEvent = function(roomId, eventType, content, txnId, callback) { - if (utils.isFunction(txnId)) { callback = txnId; txnId = undefined; } + if (utils.isFunction(txnId)) { + callback = txnId; txnId = undefined; +} if (!txnId) { txnId = this.makeTxnId(); @@ -811,14 +817,14 @@ 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. - var room = this.getRoom(roomId); - var localEvent = new MatrixEvent({ + let room = this.getRoom(roomId); + let localEvent = new MatrixEvent({ event_id: "~" + roomId + ":" + txnId, user_id: this.credentials.userId, room_id: roomId, type: eventType, origin_server_ts: new Date().getTime(), - content: content + content: content, }); localEvent._txnId = txnId; localEvent.status = EventStatus.SENDING; @@ -841,7 +847,7 @@ function _sendEvent(client, room, event, callback) { // so that we can handle synchronous and asynchronous exceptions with the // same code path. return q().then(function() { - var encryptionPromise = null; + let encryptionPromise = null; if (client._crypto) { encryptionPromise = client._crypto.encryptEventIfNeeded(event, room); } @@ -853,7 +859,7 @@ function _sendEvent(client, room, event, callback) { } return encryptionPromise; }).then(function() { - var promise; + let promise; // this event may be queued if (client.scheduler) { // if this returns a promsie then the scheduler has control now and will @@ -906,25 +912,24 @@ function _updatePendingEventStatus(room, event, newStatus) { } function _sendEventHttpRequest(client, event) { - var txnId = event._txnId ? event._txnId : client.makeTxnId(); + let txnId = event._txnId ? event._txnId : client.makeTxnId(); - var pathParams = { + let pathParams = { $roomId: event.getRoomId(), $eventType: event.getWireType(), $stateKey: event.getStateKey(), $txnId: txnId, }; - var path; + let path; if (event.isState()) { - var pathTemplate = "/rooms/$roomId/state/$eventType"; + let pathTemplate = "/rooms/$roomId/state/$eventType"; if (event.getStateKey() && event.getStateKey().length > 0) { pathTemplate = "/rooms/$roomId/state/$eventType/$stateKey"; } path = utils.encodeUri(pathTemplate, pathParams); - } - else { + } else { path = utils.encodeUri( "/rooms/$roomId/send/$eventType/$txnId", pathParams ); @@ -944,7 +949,9 @@ function _sendEventHttpRequest(client, event) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendMessage = function(roomId, content, txnId, callback) { - if (utils.isFunction(txnId)) { callback = txnId; txnId = undefined; } + if (utils.isFunction(txnId)) { + callback = txnId; txnId = undefined; +} return this.sendEvent( roomId, "m.room.message", content, txnId, callback ); @@ -959,9 +966,9 @@ 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) { - var content = { + let content = { msgtype: "m.text", - body: body + body: body, }; return this.sendMessage(roomId, content, txnId, callback); }; @@ -975,9 +982,9 @@ 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) { - var content = { + let content = { msgtype: "m.notice", - body: body + body: body, }; return this.sendMessage(roomId, content, txnId, callback); }; @@ -991,9 +998,9 @@ 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) { - var content = { + let content = { msgtype: "m.emote", - body: body + body: body, }; return this.sendMessage(roomId, content, txnId, callback); }; @@ -1008,13 +1015,17 @@ MatrixClient.prototype.sendEmoteMessage = function(roomId, body, txnId, callback * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendImageMessage = function(roomId, url, info, text, callback) { - if (utils.isFunction(text)) { callback = text; text = undefined; } - if (!text) { text = "Image"; } - var content = { + if (utils.isFunction(text)) { + callback = text; text = undefined; +} + if (!text) { + text = "Image"; +} + let content = { msgtype: "m.image", url: url, info: info, - body: text + body: text, }; return this.sendMessage(roomId, content, callback); }; @@ -1028,11 +1039,11 @@ 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) { - var content = { + let content = { msgtype: "m.text", format: "org.matrix.custom.html", body: body, - formatted_body: htmlBody + formatted_body: htmlBody, }; return this.sendMessage(roomId, content, callback); }; @@ -1046,11 +1057,11 @@ 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) { - var content = { + let content = { msgtype: "m.notice", format: "org.matrix.custom.html", body: body, - formatted_body: htmlBody + formatted_body: htmlBody, }; return this.sendMessage(roomId, content, callback); }; @@ -1064,11 +1075,11 @@ 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) { - var content = { + let content = { msgtype: "m.emote", format: "org.matrix.custom.html", body: body, - formatted_body: htmlBody + formatted_body: htmlBody, }; return this.sendMessage(roomId, content, callback); }; @@ -1086,16 +1097,16 @@ MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) { return q({}); // guests cannot send receipts so don't bother. } - var path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", { + let path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", { $roomId: event.getRoomId(), $receiptType: receiptType, - $eventId: event.getId() + $eventId: event.getId(), }); - var promise = this._http.authedRequest( + let promise = this._http.authedRequest( callback, "POST", path, undefined, {} ); - var room = this.getRoom(event.getRoomId()); + let room = this.getRoom(event.getRoomId()); if (room) { room._addLocalEchoReceipt(this.credentials.userId, event, receiptType); } @@ -1130,13 +1141,13 @@ MatrixClient.prototype.sendReadReceipt = function(event, callback) { * May return synthesized attributes if the URL lacked OG meta. */ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) { - var key = ts + "_" + url; - var og = this.urlPreviewCache[key]; + let key = ts + "_" + url; + let og = this.urlPreviewCache[key]; if (og) { return q(og); } - var self = this; + let self = this; return this._http.authedRequestWithPrefix( callback, "GET", "/preview_url", { url: url, @@ -1162,12 +1173,12 @@ MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callba return q({}); // guests cannot send typing notifications so don't bother. } - var path = utils.encodeUri("/rooms/$roomId/typing/$userId", { + let path = utils.encodeUri("/rooms/$roomId/typing/$userId", { $roomId: roomId, - $userId: this.credentials.userId + $userId: this.credentials.userId, }); - var data = { - typing: isTyping + let data = { + typing: isTyping, }; if (isTyping) { data.timeout = timeoutMs ? timeoutMs : 20000; @@ -1213,16 +1224,16 @@ 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) { - var path = utils.encodeUri( + let path = utils.encodeUri( "/rooms/$roomId/invite", { $roomId: roomId } ); - var identityServerUrl = this.getIdentityServerUrl(); + let identityServerUrl = this.getIdentityServerUrl(); if (!identityServerUrl) { return q.reject(new MatrixError({ error: "No supplied identity server URL", - errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM" + errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM", })); } if (identityServerUrl.indexOf("http://") === 0 || @@ -1234,7 +1245,7 @@ MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, call return this._http.authedRequest(callback, "POST", path, undefined, { id_server: identityServerUrl, medium: medium, - address: address + address: address, }); }; @@ -1274,12 +1285,12 @@ MatrixClient.prototype.forget = function(roomId, deleteRoom, callback) { if (deleteRoom === undefined) { deleteRoom = true; } - var promise = _membershipChange(this, roomId, undefined, "forget", undefined, + let promise = _membershipChange(this, roomId, undefined, "forget", undefined, callback); if (!deleteRoom) { return promise; } - var self = this; + let self = this; return promise.then(function(response) { self.store.removeRoom(roomId); self.emit("deleteRoom", roomId); @@ -1328,16 +1339,18 @@ MatrixClient.prototype.kick = function(roomId, userId, reason, callback) { */ function _setMembershipState(client, roomId, userId, membershipValue, reason, callback) { - if (utils.isFunction(reason)) { callback = reason; reason = undefined; } + if (utils.isFunction(reason)) { + callback = reason; reason = undefined; +} - var path = utils.encodeUri( + let path = utils.encodeUri( "/rooms/$roomId/state/m.room.member/$userId", { $roomId: roomId, $userId: userId} ); return client._http.authedRequest(callback, "PUT", path, undefined, { membership: membershipValue, - reason: reason + reason: reason, }); } @@ -1353,16 +1366,18 @@ function _setMembershipState(client, roomId, userId, membershipValue, reason, * @return {module:http-api.MatrixError} Rejects: with an error response. */ function _membershipChange(client, roomId, userId, membership, reason, callback) { - if (utils.isFunction(reason)) { callback = reason; reason = undefined; } + if (utils.isFunction(reason)) { + callback = reason; reason = undefined; +} - var path = utils.encodeUri("/rooms/$room_id/$membership", { + let path = utils.encodeUri("/rooms/$room_id/$membership", { $room_id: roomId, - $membership: membership + $membership: membership, }); return client._http.authedRequest( callback, "POST", path, undefined, { user_id: userId, // may be undefined e.g. on leave - reason: reason + reason: reason, } ); } @@ -1375,7 +1390,7 @@ function _membershipChange(client, roomId, userId, membership, reason, callback) */ MatrixClient.prototype.getPushActionsForEvent = function(event) { if (!event.getPushActions()) { - var pushProcessor = new PushProcessor(this); + let pushProcessor = new PushProcessor(this); event.setPushActions(pushProcessor.actionsForEvent(event)); } return event.getPushActions(); @@ -1392,9 +1407,9 @@ MatrixClient.prototype.getPushActionsForEvent = function(event) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setProfileInfo = function(info, data, callback) { - var path = utils.encodeUri("/profile/$userId/$info", { + let path = utils.encodeUri("/profile/$userId/$info", { $userId: this.credentials.userId, - $info: info + $info: info, }); return this._http.authedRequest( callback, "PUT", path, undefined, data @@ -1455,15 +1470,15 @@ MatrixClient.prototype.mxcUrlToHttp = * @throws If 'presence' isn't a valid presence enum value. */ MatrixClient.prototype.setPresence = function(opts, callback) { - var path = utils.encodeUri("/presence/$userId/status", { - $userId: this.credentials.userId + let path = utils.encodeUri("/presence/$userId/status", { + $userId: this.credentials.userId, }); if (typeof opts === "string") { opts = { presence: opts }; } - var validStates = ["offline", "online", "unavailable"]; + let validStates = ["offline", "online", "unavailable"]; if (validStates.indexOf(opts.presence) == -1) { throw new Error("Bad presence value: " + opts.presence); } @@ -1473,8 +1488,8 @@ MatrixClient.prototype.setPresence = function(opts, callback) { }; function _presenceList(callback, client, opts, method) { - var path = utils.encodeUri("/presence/list/$userId", { - $userId: client.credentials.userId + let path = utils.encodeUri("/presence/list/$userId", { + $userId: client.credentials.userId, }); return client._http.authedRequest(callback, method, path, undefined, opts); } @@ -1497,7 +1512,7 @@ MatrixClient.prototype.getPresenceList = function(callback) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.inviteToPresenceList = function(callback, userIds) { - var opts = {"invite": userIds}; + let opts = {"invite": userIds}; return _presenceList(callback, this, opts, "POST"); }; @@ -1509,7 +1524,7 @@ MatrixClient.prototype.inviteToPresenceList = function(callback, userIds) { * @return {module:http-api.MatrixError} Rejects: with an error response. **/ MatrixClient.prototype.dropFromPresenceList = function(callback, userIds) { - var opts = {"drop": userIds}; + let opts = {"drop": userIds}; return _presenceList(callback, this, opts, "POST"); }; @@ -1531,16 +1546,17 @@ MatrixClient.prototype.dropFromPresenceList = function(callback, userIds) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.scrollback = function(room, limit, callback) { - if (utils.isFunction(limit)) { callback = limit; limit = undefined; } + if (utils.isFunction(limit)) { + callback = limit; limit = undefined; +} limit = limit || 30; - var timeToWaitMs = 0; + let timeToWaitMs = 0; - var info = this._ongoingScrollbacks[room.roomId] || {}; + let info = this._ongoingScrollbacks[room.roomId] || {}; if (info.promise) { return info.promise; - } - else if (info.errorTs) { - var timeWaitedMs = Date.now() - info.errorTs; + } else if (info.errorTs) { + let timeWaitedMs = Date.now() - info.errorTs; timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0); } @@ -1548,7 +1564,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) { return q(room); // already at the start. } // attempt to grab more events from the store first - var numAdded = this.store.scrollback(room, limit).length; + let numAdded = this.store.scrollback(room, limit).length; if (numAdded === limit) { // store contained everything we needed. return q(room); @@ -1556,26 +1572,26 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) { // reduce the required number of events appropriately limit = limit - numAdded; - var path = utils.encodeUri( + let path = utils.encodeUri( "/rooms/$roomId/messages", {$roomId: room.roomId} ); - var params = { + let params = { from: room.oldState.paginationToken, limit: limit, - dir: 'b' + dir: 'b', }; - var defer = q.defer(); + let defer = q.defer(); info = { promise: defer.promise, - errorTs: null + errorTs: null, }; - var self = this; + let 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) { - var matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self)); + let matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self)); room.addEventsToTimeline(matrixEvents, true, room.getLiveTimeline()); room.oldState.paginationToken = res.end; if (res.chunk.length === 0) { @@ -1586,7 +1602,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) { _resolve(callback, defer, room); }, function(err) { self._ongoingScrollbacks[room.roomId] = { - errorTs: Date.now() + errorTs: Date.now(), }; _reject(callback, defer, err); }); @@ -1610,40 +1626,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 || {}; - var backwards = opts.backwards || false; + let backwards = opts.backwards || false; - var token = eventContext.getPaginateToken(backwards); + let token = eventContext.getPaginateToken(backwards); if (!token) { // no more results. return q.reject(new Error("No paginate token")); } - var dir = backwards ? 'b' : 'f'; - var pendingRequest = eventContext._paginateRequests[dir]; + let dir = backwards ? 'b' : 'f'; + let pendingRequest = eventContext._paginateRequests[dir]; if (pendingRequest) { // already a request in progress - return the existing promise return pendingRequest; } - var path = utils.encodeUri( + let path = utils.encodeUri( "/rooms/$roomId/messages", {$roomId: eventContext.getEvent().getRoomId()} ); - var params = { + let params = { from: token, limit: ('limit' in opts) ? opts.limit : 30, - dir: dir + dir: dir, }; - var self = this; - var promise = + let self = this; + let promise = self._http.authedRequest(undefined, "GET", path, params ).then(function(res) { - var token = res.end; + let token = res.end; if (res.chunk.length === 0) { token = null; } else { - var matrixEvents = utils.map(res.chunk, self.getEventMapper()); + let matrixEvents = utils.map(res.chunk, self.getEventMapper()); if (backwards) { // eventContext expects the events in timeline order, but // back-pagination returns them in reverse order. @@ -1687,7 +1703,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) { return q(timelineSet.getTimelineForEvent(eventId)); } - var path = utils.encodeUri( + let path = utils.encodeUri( "/rooms/$roomId/context/$eventId", { $roomId: timelineSet.room.roomId, $eventId: eventId, @@ -1696,8 +1712,8 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) { // TODO: we should implement a backoff (as per scrollback()) to deal more // nicely with HTTP errors. - var self = this; - var promise = + let self = this; + let promise = self._http.authedRequest(undefined, "GET", path ).then(function(res) { if (!res.event) { @@ -1714,12 +1730,12 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) { // have known state. // events_after is already backwards; events_before is forwards. res.events_after.reverse(); - var events = res.events_after + let events = res.events_after .concat([res.event]) .concat(res.events_before); - var matrixEvents = utils.map(events, self.getEventMapper()); + let matrixEvents = utils.map(events, self.getEventMapper()); - var timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId()); + let timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId()); if (!timeline) { timeline = timelineSet.addTimeline(); timeline.initialiseState(utils.map(res.state, @@ -1733,7 +1749,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. - var tl = timelineSet.getTimelineForEvent(eventId) || timeline; + let tl = timelineSet.getTimelineForEvent(eventId) || timeline; return tl; }); return promise; @@ -1754,12 +1770,12 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) { * events and we reached either end of the timeline; else true. */ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) { - var isNotifTimeline = (eventTimeline.getTimelineSet() === this._notifTimelineSet); + let isNotifTimeline = (eventTimeline.getTimelineSet() === this._notifTimelineSet); // TODO: we should implement a backoff (as per scrollback()) to deal more // nicely with HTTP errors. opts = opts || {}; - var backwards = opts.backwards || false; + let backwards = opts.backwards || false; if (isNotifTimeline) { if (!backwards) { @@ -1767,23 +1783,23 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) { } } - var dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS; + let dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS; - var token = eventTimeline.getPaginationToken(dir); + let token = eventTimeline.getPaginationToken(dir); if (!token) { // no token - no results. return q(false); } - var pendingRequest = eventTimeline._paginationRequests[dir]; + let pendingRequest = eventTimeline._paginationRequests[dir]; if (pendingRequest) { // already a request in progress - return the existing promise return pendingRequest; } - var path, params, promise; - var self = this; + let path, params, promise; + let self = this; if (isNotifTimeline) { path = "/notifications"; @@ -1800,12 +1816,12 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) { this._http.authedRequestWithPrefix(undefined, "GET", path, params, undefined, httpApi.PREFIX_UNSTABLE ).then(function(res) { - var token = res.next_token; - var matrixEvents = []; + let token = res.next_token; + let matrixEvents = []; - for (var i = 0; i < res.notifications.length; i++) { - var notification = res.notifications[i]; - var event = self.getEventMapper()(notification.event); + for (let i = 0; i < res.notifications.length; i++) { + let notification = res.notifications[i]; + let event = self.getEventMapper()(notification.event); event.setPushActions( PushProcessor.actionListToActionsObject(notification.actions) ); @@ -1827,9 +1843,8 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) { eventTimeline._paginationRequests[dir] = null; }); eventTimeline._paginationRequests[dir] = promise; - } - else { - var room = this.getRoom(eventTimeline.getRoomId()); + } else { + let room = this.getRoom(eventTimeline.getRoomId()); if (!room) { throw new Error("Unknown room " + eventTimeline.getRoomId()); } @@ -1840,10 +1855,10 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) { params = { from: token, limit: ('limit' in opts) ? opts.limit : 30, - dir: dir + dir: dir, }; - var filter = eventTimeline.getFilter(); + let 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 @@ -1853,8 +1868,8 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) { promise = this._http.authedRequest(undefined, "GET", path, params ).then(function(res) { - var token = res.end; - var matrixEvents = utils.map(res.chunk, self.getEventMapper()); + let token = res.end; + let matrixEvents = utils.map(res.chunk, self.getEventMapper()); eventTimeline.getTimelineSet() .addEventsToTimeline(matrixEvents, backwards, eventTimeline, token); @@ -1946,14 +1961,14 @@ MatrixClient.prototype.stopPeeking = function() { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setGuestAccess = function(roomId, opts) { - var writePromise = this.sendStateEvent(roomId, "m.room.guest_access", { - guest_access: opts.allowJoin ? "can_join" : "forbidden" + let writePromise = this.sendStateEvent(roomId, "m.room.guest_access", { + guest_access: opts.allowJoin ? "can_join" : "forbidden", }); - var readPromise = q(); + let readPromise = q(); if (opts.allowRead) { readPromise = this.sendStateEvent(roomId, "m.room.history_visibility", { - history_visibility: "world_readable" + history_visibility: "world_readable", }); } @@ -2061,12 +2076,12 @@ MatrixClient.prototype.requestPasswordEmailToken = function(email, clientSecret, MatrixClient.prototype._requestTokenFromEndpoint = function(endpoint, email, clientSecret, sendAttempt, nextLink, callback) { - var id_server_url = url.parse(this.idBaseUrl); + let id_server_url = url.parse(this.idBaseUrl); if (id_server_url.host === null) { throw new Error("Invalid ID server URL: " + this.idBaseUrl); } - var params = { + let params = { client_secret: clientSecret, email: email, send_attempt: sendAttempt, @@ -2093,14 +2108,13 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) { // There can be only room-kind push rule per room // and its id is the room id. if (this.pushRules) { - for (var i = 0; i < this.pushRules[scope].room.length; i++) { - var rule = this.pushRules[scope].room[i]; + for (let i = 0; i < this.pushRules[scope].room.length; i++) { + let rule = this.pushRules[scope].room[i]; if (rule.rule_id === roomId) { return rule; } } - } - else { + } else { throw new Error( "SyncApi.sync() must be done before accessing to push rules." ); @@ -2117,11 +2131,11 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) { - var self = this; - var deferred, hasDontNotifyRule; + let self = this; + let deferred, hasDontNotifyRule; // Get the existing room-kind push rule if any - var roomPushRule = this.getRoomPushRule(scope, roomId); + let roomPushRule = this.getRoomPushRule(scope, roomId); if (roomPushRule) { if (0 <= roomPushRule.actions.indexOf("dont_notify")) { hasDontNotifyRule = true; @@ -2133,21 +2147,19 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) { if (hasDontNotifyRule) { deferred = this.deletePushRule(scope, "room", roomPushRule.rule_id); } - } - else { + } else { if (!roomPushRule) { deferred = this.addPushRule(scope, "room", roomId, { - actions: ["dont_notify"] + actions: ["dont_notify"], }); - } - else if (!hasDontNotifyRule) { + } else if (!hasDontNotifyRule) { // Remove the existing one before setting the mute push rule // This is a workaround to SYN-590 (Push rule update fails) deferred = q.defer(); this.deletePushRule(scope, "room", roomPushRule.rule_id) .done(function() { self.addPushRule(scope, "room", roomId, { - actions: ["dont_notify"] + actions: ["dont_notify"], }).done(function() { deferred.resolve(); }, function(err) { @@ -2163,7 +2175,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) { if (deferred) { // Update this.pushRules when the operation completes - var ruleRefreshDeferred = q.defer(); + let ruleRefreshDeferred = q.defer(); deferred.done(function() { self.getPushRules().done(function(result) { self.pushRules = result; @@ -2204,10 +2216,10 @@ MatrixClient.prototype.searchMessageText = function(opts, callback) { search_categories: { room_events: { keys: opts.keys, - search_term: opts.query - } - } - } + search_term: opts.query, + }, + }, + }, }, callback); }; @@ -2234,7 +2246,7 @@ MatrixClient.prototype.searchMessageText = function(opts, callback) { MatrixClient.prototype.searchRoomEvents = function(opts) { // TODO: support groups - var body = { + let body = { search_categories: { room_events: { search_term: opts.term, @@ -2244,12 +2256,12 @@ MatrixClient.prototype.searchRoomEvents = function(opts) { before_limit: 1, after_limit: 1, include_profile: true, - } - } - } + }, + }, + }, }; - var searchResults = { + let searchResults = { _query: body, results: [], highlights: [], @@ -2280,12 +2292,12 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) { return searchResults.pendingRequest; } - var searchOpts = { + let searchOpts = { body: searchResults._query, next_batch: searchResults.next_batch, }; - var promise = this.search(searchOpts).then( + let promise = this.search(searchOpts).then( this._processRoomEventsSearch.bind(this, searchResults) ).finally(function() { searchResults.pendingRequest = null; @@ -2305,23 +2317,27 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) { * @private */ MatrixClient.prototype._processRoomEventsSearch = function(searchResults, response) { - var room_events = response.search_categories.room_events; + let 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 - var highlights = {}; - room_events.highlights.forEach(function(hl) { highlights[hl] = 1; }); - searchResults.highlights.forEach(function(hl) { highlights[hl] = 1; }); + let highlights = {}; + room_events.highlights.forEach(function(hl) { + highlights[hl] = 1; +}); + searchResults.highlights.forEach(function(hl) { + highlights[hl] = 1; +}); // turn it back into a list. searchResults.highlights = Object.keys(highlights); // append the new results to our existing results - for (var i = 0; i < room_events.results.length; i++) { - var sr = SearchResult.fromJson(room_events.results[i], this.getEventMapper()); + for (let i = 0; i < room_events.results.length; i++) { + let sr = SearchResult.fromJson(room_events.results[i], this.getEventMapper()); searchResults.results.push(sr); } return searchResults; @@ -2342,8 +2358,8 @@ MatrixClient.prototype.syncLeftRooms = function() { if (this._syncLeftRoomsPromise) { return this._syncLeftRoomsPromise; // return the ongoing request } - var self = this; - var syncApi = new SyncApi(this, this._clientOpts); + let self = this; + let syncApi = new SyncApi(this, this._clientOpts); this._syncLeftRoomsPromise = syncApi.syncLeftRooms(); // cleanup locks @@ -2367,15 +2383,15 @@ MatrixClient.prototype.syncLeftRooms = function() { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.createFilter = function(content) { - var self = this; - var path = utils.encodeUri("/user/$userId/filter", { - $userId: this.credentials.userId + let self = this; + let 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 - var filter = Filter.fromJson( + let filter = Filter.fromJson( self.credentials.userId, response.filter_id, content ); self.store.storeFilter(filter); @@ -2394,23 +2410,23 @@ MatrixClient.prototype.createFilter = function(content) { */ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) { if (allowCached) { - var filter = this.store.getFilter(userId, filterId); + let filter = this.store.getFilter(userId, filterId); if (filter) { return q(filter); } } - var self = this; - var path = utils.encodeUri("/user/$userId/filter/$filterId", { + let self = this; + let path = utils.encodeUri("/user/$userId/filter/$filterId", { $userId: userId, - $filterId: filterId + $filterId: filterId, }); return this._http.authedRequest( undefined, "GET", path, undefined, undefined ).then(function(response) { // persist the filter - var filter = Filter.fromJson( + let filter = Filter.fromJson( userId, filterId, response ); self.store.storeFilter(filter); @@ -2424,18 +2440,17 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) { * @return {Promise} Filter ID */ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) { - - var filterId = this.store.getFilterIdByName(filterName); - var promise = q(); - var self = this; + let filterId = this.store.getFilterIdByName(filterName); + let promise = q(); + let self = this; if (filterId) { // check that the existing filter matches our expectations promise = self.getFilter(self.credentials.userId, filterId, true ).then(function(existingFilter) { - var oldDef = existingFilter.getDefinition(); - var newDef = filter.getDefinition(); + let oldDef = existingFilter.getDefinition(); + let newDef = filter.getDefinition(); if (utils.deepCompare(oldDef, newDef)) { // super, just use that. @@ -2493,7 +2508,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) { * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getOpenIdToken = function() { - var path = utils.encodeUri("/user/$userId/openid/request_token", { + let path = utils.encodeUri("/user/$userId/openid/request_token", { $userId: this.credentials.userId, }); @@ -2574,7 +2589,7 @@ MatrixClient.prototype.startClient = function(opts) { // backwards compat for when 'opts' was 'historyLen'. if (typeof opts === "number") { opts = { - initialSyncLimit: opts + initialSyncLimit: opts, }; } @@ -2582,8 +2597,8 @@ MatrixClient.prototype.startClient = function(opts) { if (this._crypto) { this._crypto.uploadKeys(5).done(); - var tenMinutes = 1000 * 60 * 10; - var self = this; + let tenMinutes = 1000 * 60 * 10; + let self = this; this._uploadIntervalID = global.setInterval(function() { self._crypto.uploadKeys(5).done(); }, tenMinutes); @@ -2619,7 +2634,7 @@ MatrixClient.prototype.stopClient = function() { }; function setupCallEventHandler(client) { - var candidatesByCall = { + let candidatesByCall = { // callId: [Candidate] }; @@ -2627,16 +2642,16 @@ function setupCallEventHandler(client) { // This buffer will be inspected to see if we should send incoming call // notifications. It needs to be buffered to correctly determine if an // incoming call has had a matching answer/hangup. - var callEventBuffer = []; - var isClientPrepared = false; + let callEventBuffer = []; + let isClientPrepared = false; client.on("sync", function(state) { if (state === "PREPARED") { isClientPrepared = true; - var ignoreCallIds = {}; // Set + let ignoreCallIds = {}; // Set // inspect the buffer and mark all calls which have been answered // or hung up before passing them to the call event handler. - for (var i = callEventBuffer.length - 1; i >= 0; i--) { - var ev = callEventBuffer[i]; + for (let i = callEventBuffer.length - 1; i >= 0; i--) { + let ev = callEventBuffer[i]; if (ev.getType() === "m.call.answer" || ev.getType() === "m.call.hangup") { ignoreCallIds[ev.getContent().call_id] = "yep"; @@ -2667,9 +2682,9 @@ function setupCallEventHandler(client) { if (event.getType().indexOf("m.call.") !== 0) { return; // not a call event } - var content = event.getContent(); - var call = content.call_id ? client.callList[content.call_id] : undefined; - var i; + let 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)); if (event.getType() === "m.call.invite") { @@ -2718,10 +2733,10 @@ function setupCallEventHandler(client) { } // Were we trying to call that user (room)? - var existingCall; - var existingCalls = utils.values(client.callList); + let existingCall; + let existingCalls = utils.values(client.callList); for (i = 0; i < existingCalls.length; ++i) { - var thisCall = existingCalls[i]; + let thisCall = existingCalls[i]; if (call.room_id === thisCall.room_id && thisCall.direction === 'outbound' && (["wait_local_media", "create_offer", "invite_sent"].indexOf( @@ -2745,20 +2760,17 @@ function setupCallEventHandler(client) { ); existingCall._replacedBy(call); call.answer(); - } - else { + } else { console.log( "Glare detected: rejecting incoming call " + call.callId + " and keeping outgoing call " + existingCall.callId ); call.hangup(); } - } - else { + } else { client.emit("Call.incoming", call); } - } - else if (event.getType() === 'm.call.answer') { + } else if (event.getType() === 'm.call.answer') { if (!call) { return; } @@ -2766,12 +2778,10 @@ function setupCallEventHandler(client) { if (call.state === 'ringing') { call._onAnsweredElsewhere(content); } - } - else { + } else { call._receivedAnswer(content); } - } - else if (event.getType() === 'm.call.candidates') { + } else if (event.getType() === 'm.call.candidates') { if (event.getSender() === client.credentials.userId) { return; } @@ -2783,14 +2793,12 @@ function setupCallEventHandler(client) { candidatesByCall[content.call_id] = candidatesByCall[ content.call_id ].concat(content.candidates); - } - else { + } else { for (i = 0; i < content.candidates.length; i++) { call._gotRemoteIceCandidate(content.candidates[i]); } } - } - else if (event.getType() === 'm.call.hangup') { + } else if (event.getType() === 'm.call.hangup') { // Note that we also observe our own hangups here so we can see // if we've already rejected a call that would otherwise be valid if (!call) { @@ -2803,8 +2811,7 @@ function setupCallEventHandler(client) { call._initWithHangup(event); client.callList[content.call_id] = call; } - } - else { + } else { if (call.state !== 'ended') { call._onHangupReceived(content); delete client.callList[content.call_id]; @@ -2828,22 +2835,26 @@ function checkTurnServers(client) { res.ttl + " secs"); // map the response to a format that can be fed to // RTCPeerConnection - var servers = { + let servers = { urls: res.uris, username: res.username, - credential: res.password + credential: res.password, }; client._turnServers = [servers]; // re-fetch when we're about to reach the TTL client._checkTurnServersTimeoutID = - setTimeout(function() { checkTurnServers(client); }, + setTimeout(function() { + checkTurnServers(client); +}, (res.ttl || (60 * 60)) * 1000 * 0.9 ); } }, function(err) { console.error("Failed to get TURN URIs"); client._checkTurnServersTimeoutID = - setTimeout(function() { checkTurnServers(client); }, 60000); + setTimeout(function() { + checkTurnServers(client); +}, 60000); }); } @@ -2863,7 +2874,7 @@ function _resolve(callback, defer, res) { function _PojoToMatrixEventMapper(client) { function mapper(plainOldJsObject) { - var event = new MatrixEvent(plainOldJsObject); + let event = new MatrixEvent(plainOldJsObject); if (event.isEncrypted()) { _decryptEvent(client, event); } @@ -2888,10 +2899,10 @@ MatrixClient.prototype.getEventMapper = function() { * @return {string} A new client secret */ MatrixClient.prototype.generateClientSecret = function() { - var ret = ""; - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let ret = ""; + let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - for (var i = 0; i < 32; i++) { + for (let i = 0; i < 32; i++) { ret += chars.charAt(Math.floor(Math.random() * chars.length)); } diff --git a/src/content-repo.js b/src/content-repo.js index e39ecaa4e..a2e0912f5 100644 --- a/src/content-repo.js +++ b/src/content-repo.js @@ -16,7 +16,7 @@ limitations under the License. /** * @module content-repo */ -var utils = require("./utils"); +let utils = require("./utils"); /** Content Repo utility functions */ module.exports = { @@ -46,9 +46,9 @@ module.exports = { return ''; } } - var serverAndMediaId = mxc.slice(6); // strips mxc:// - var prefix = "/_matrix/media/v1/download/"; - var params = {}; + let serverAndMediaId = mxc.slice(6); // strips mxc:// + let prefix = "/_matrix/media/v1/download/"; + let params = {}; if (width) { params.width = width; @@ -65,7 +65,7 @@ module.exports = { prefix = "/_matrix/media/v1/thumbnail/"; } - var fragmentOffset = serverAndMediaId.indexOf("#"), + let fragmentOffset = serverAndMediaId.indexOf("#"), fragment = ""; if (fragmentOffset >= 0) { fragment = serverAndMediaId.substr(fragmentOffset); @@ -88,18 +88,22 @@ module.exports = { if (!identiconString) { return null; } - if (!width) { width = 96; } - if (!height) { height = 96; } - var params = { + if (!width) { + width = 96; +} + if (!height) { + height = 96; +} + let params = { width: width, - height: height + height: height, }; - var path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", { - $ident: identiconString + let path = utils.encodeUri("/_matrix/media/v1/identicon/$ident", { + $ident: identiconString, }); return baseUrl + path + (utils.keys(params).length === 0 ? "" : ("?" + utils.encodeParams(params))); - } + }, }; diff --git a/src/crypto/OlmDevice.js b/src/crypto/OlmDevice.js index 42fd117f8..e01b56d20 100644 --- a/src/crypto/OlmDevice.js +++ b/src/crypto/OlmDevice.js @@ -20,13 +20,13 @@ limitations under the License. * * @module crypto/OlmDevice */ -var Olm = require("olm"); -var utils = require("../utils"); +let Olm = require("olm"); +let 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. -var MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4; +let MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4; function checkPayloadLength(payloadString) { if (payloadString === undefined) { @@ -66,8 +66,8 @@ function OlmDevice(sessionStore) { this._sessionStore = sessionStore; this._pickleKey = "DEFAULT_KEY"; - var e2eKeys; - var account = new Olm.Account(); + let e2eKeys; + let account = new Olm.Account(); try { _initialise_account(this._sessionStore, this._pickleKey, account); e2eKeys = JSON.parse(account.identity_keys()); @@ -96,14 +96,14 @@ function OlmDevice(sessionStore) { } function _initialise_account(sessionStore, pickleKey, account) { - var e2eAccount = sessionStore.getEndToEndAccount(); + let e2eAccount = sessionStore.getEndToEndAccount(); if (e2eAccount !== null) { account.unpickle(pickleKey, e2eAccount); return; } account.create(); - var pickled = account.pickle(pickleKey); + let pickled = account.pickle(pickleKey); sessionStore.storeEndToEndAccount(pickled); } @@ -123,9 +123,9 @@ OlmDevice.getOlmVersion = function() { * @private */ OlmDevice.prototype._getAccount = function(func) { - var account = new Olm.Account(); + let account = new Olm.Account(); try { - var pickledAccount = this._sessionStore.getEndToEndAccount(); + let pickledAccount = this._sessionStore.getEndToEndAccount(); account.unpickle(this._pickleKey, pickledAccount); return func(account); } finally { @@ -141,7 +141,7 @@ OlmDevice.prototype._getAccount = function(func) { * @private */ OlmDevice.prototype._saveAccount = function(account) { - var pickledAccount = account.pickle(this._pickleKey); + let pickledAccount = account.pickle(this._pickleKey); this._sessionStore.storeEndToEndAccount(pickledAccount); }; @@ -156,10 +156,10 @@ OlmDevice.prototype._saveAccount = function(account) { * @private */ OlmDevice.prototype._getSession = function(deviceKey, sessionId, func) { - var sessions = this._sessionStore.getEndToEndSessions(deviceKey); - var pickledSession = sessions[sessionId]; + let sessions = this._sessionStore.getEndToEndSessions(deviceKey); + let pickledSession = sessions[sessionId]; - var session = new Olm.Session(); + let session = new Olm.Session(); try { session.unpickle(this._pickleKey, pickledSession); return func(session); @@ -177,7 +177,7 @@ OlmDevice.prototype._getSession = function(deviceKey, sessionId, func) { * @private */ OlmDevice.prototype._saveSession = function(deviceKey, session) { - var pickledSession = session.pickle(this._pickleKey); + let pickledSession = session.pickle(this._pickleKey); this._sessionStore.storeEndToEndSession( deviceKey, session.session_id(), pickledSession ); @@ -192,7 +192,7 @@ OlmDevice.prototype._saveSession = function(deviceKey, session) { * @private */ OlmDevice.prototype._getUtility = function(func) { - var utility = new Olm.Utility(); + let utility = new Olm.Utility(); try { return func(utility); } finally { @@ -242,7 +242,7 @@ OlmDevice.prototype.maxNumberOfOneTimeKeys = function() { * Marks all of the one-time keys as published. */ OlmDevice.prototype.markKeysAsPublished = function() { - var self = this; + let self = this; this._getAccount(function(account) { account.mark_keys_as_published(); self._saveAccount(account); @@ -255,7 +255,7 @@ OlmDevice.prototype.markKeysAsPublished = function() { * @param {number} numKeys number of keys to generate */ OlmDevice.prototype.generateOneTimeKeys = function(numKeys) { - var self = this; + let self = this; this._getAccount(function(account) { account.generate_one_time_keys(numKeys); self._saveAccount(account); @@ -274,9 +274,9 @@ OlmDevice.prototype.generateOneTimeKeys = function(numKeys) { OlmDevice.prototype.createOutboundSession = function( theirIdentityKey, theirOneTimeKey ) { - var self = this; + let self = this; return this._getAccount(function(account) { - var session = new Olm.Session(); + let session = new Olm.Session(); try { session.create_outbound(account, theirIdentityKey, theirOneTimeKey); self._saveSession(theirIdentityKey, session); @@ -308,15 +308,15 @@ OlmDevice.prototype.createInboundSession = function( throw new Error("Need message_type == 0 to create inbound session"); } - var self = this; + let self = this; return this._getAccount(function(account) { - var session = new Olm.Session(); + let session = new Olm.Session(); try { session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext); account.remove_one_time_keys(session); self._saveAccount(account); - var payloadString = session.decrypt(message_type, ciphertext); + let payloadString = session.decrypt(message_type, ciphertext); self._saveSession(theirDeviceIdentityKey, session); @@ -339,7 +339,7 @@ OlmDevice.prototype.createInboundSession = function( * @return {string[]} a list of known session ids for the device */ OlmDevice.prototype.getSessionIdsForDevice = function(theirDeviceIdentityKey) { - var sessions = this._sessionStore.getEndToEndSessions( + let sessions = this._sessionStore.getEndToEndSessions( theirDeviceIdentityKey ); return utils.keys(sessions); @@ -353,7 +353,7 @@ OlmDevice.prototype.getSessionIdsForDevice = function(theirDeviceIdentityKey) { * @return {string?} session id, or null if no established session */ OlmDevice.prototype.getSessionIdForDevice = function(theirDeviceIdentityKey) { - var sessionIds = this.getSessionIdsForDevice(theirDeviceIdentityKey); + let sessionIds = this.getSessionIdsForDevice(theirDeviceIdentityKey); if (sessionIds.length === 0) { return null; } @@ -374,20 +374,20 @@ OlmDevice.prototype.getSessionIdForDevice = function(theirDeviceIdentityKey) { * @return {Array.<{sessionId: string, hasReceivedMessage: Boolean}>} */ OlmDevice.prototype.getSessionInfoForDevice = function(deviceIdentityKey) { - var sessionIds = this.getSessionIdsForDevice(deviceIdentityKey); + let sessionIds = this.getSessionIdsForDevice(deviceIdentityKey); sessionIds.sort(); - var info = []; + let info = []; function getSessionInfo(session) { return { - hasReceivedMessage: session.has_received_message() + hasReceivedMessage: session.has_received_message(), }; } - for (var i = 0; i < sessionIds.length; i++) { - var sessionId = sessionIds[i]; - var res = this._getSession(deviceIdentityKey, sessionId, getSessionInfo); + for (let i = 0; i < sessionIds.length; i++) { + let sessionId = sessionIds[i]; + let res = this._getSession(deviceIdentityKey, sessionId, getSessionInfo); res.sessionId = sessionId; info.push(res); } @@ -407,12 +407,12 @@ OlmDevice.prototype.getSessionInfoForDevice = function(deviceIdentityKey) { OlmDevice.prototype.encryptMessage = function( theirDeviceIdentityKey, sessionId, payloadString ) { - var self = this; + let self = this; checkPayloadLength(payloadString); return this._getSession(theirDeviceIdentityKey, sessionId, function(session) { - var res = session.encrypt(payloadString); + let res = session.encrypt(payloadString); self._saveSession(theirDeviceIdentityKey, session); return res; }); @@ -432,10 +432,10 @@ OlmDevice.prototype.encryptMessage = function( OlmDevice.prototype.decryptMessage = function( theirDeviceIdentityKey, sessionId, message_type, ciphertext ) { - var self = this; + let self = this; return this._getSession(theirDeviceIdentityKey, sessionId, function(session) { - var payloadString = session.decrypt(message_type, ciphertext); + let payloadString = session.decrypt(message_type, ciphertext); self._saveSession(theirDeviceIdentityKey, session); return payloadString; @@ -477,7 +477,7 @@ OlmDevice.prototype.matchesSession = function( * @private */ OlmDevice.prototype._saveOutboundGroupSession = function(session) { - var pickledSession = session.pickle(this._pickleKey); + let pickledSession = session.pickle(this._pickleKey); this._outboundGroupSessionStore[session.session_id()] = pickledSession; }; @@ -492,12 +492,12 @@ OlmDevice.prototype._saveOutboundGroupSession = function(session) { * @private */ OlmDevice.prototype._getOutboundGroupSession = function(sessionId, func) { - var pickled = this._outboundGroupSessionStore[sessionId]; + let pickled = this._outboundGroupSessionStore[sessionId]; if (pickled === null) { throw new Error("Unknown outbound group session " + sessionId); } - var session = new Olm.OutboundGroupSession(); + let session = new Olm.OutboundGroupSession(); try { session.unpickle(this._pickleKey, pickled); return func(session); @@ -513,7 +513,7 @@ OlmDevice.prototype._getOutboundGroupSession = function(sessionId, func) { * @return {string} sessionId for the outbound session. */ OlmDevice.prototype.createOutboundGroupSession = function() { - var session = new Olm.OutboundGroupSession(); + let session = new Olm.OutboundGroupSession(); try { session.create(); this._saveOutboundGroupSession(session); @@ -533,12 +533,12 @@ OlmDevice.prototype.createOutboundGroupSession = function() { * @return {string} ciphertext */ OlmDevice.prototype.encryptGroupMessage = function(sessionId, payloadString) { - var self = this; + let self = this; checkPayloadLength(payloadString); return this._getOutboundGroupSession(sessionId, function(session) { - var res = session.encrypt(payloadString); + let res = session.encrypt(payloadString); self._saveOutboundGroupSession(session); return res; }); @@ -578,7 +578,7 @@ OlmDevice.prototype.getOutboundGroupSessionKey = function(sessionId) { OlmDevice.prototype._saveInboundGroupSession = function( roomId, senderCurve25519Key, sessionId, session, keysClaimed ) { - var r = { + let r = { room_id: roomId, session: session.pickle(this._pickleKey), keysClaimed: keysClaimed, @@ -608,7 +608,7 @@ OlmDevice.prototype._saveInboundGroupSession = function( OlmDevice.prototype._getInboundGroupSession = function( roomId, senderKey, sessionId, func ) { - var r = this._sessionStore.getEndToEndInboundGroupSession( + let r = this._sessionStore.getEndToEndInboundGroupSession( senderKey, sessionId ); @@ -627,7 +627,7 @@ OlmDevice.prototype._getInboundGroupSession = function( ); } - var session = new Olm.InboundGroupSession(); + let session = new Olm.InboundGroupSession(); try { session.unpickle(this._pickleKey, r.session); return func(session, r.keysClaimed || {}); @@ -648,7 +648,7 @@ OlmDevice.prototype._getInboundGroupSession = function( OlmDevice.prototype.addInboundGroupSession = function( roomId, senderKey, sessionId, sessionKey, keysClaimed ) { - var self = this; + let self = this; /* if we already have this session, consider updating it */ function updateSession(session) { @@ -658,7 +658,7 @@ OlmDevice.prototype.addInboundGroupSession = function( return true; } - var r = this._getInboundGroupSession( + let r = this._getInboundGroupSession( roomId, senderKey, sessionId, updateSession ); @@ -667,7 +667,7 @@ OlmDevice.prototype.addInboundGroupSession = function( } // new session. - var session = new Olm.InboundGroupSession(); + let session = new Olm.InboundGroupSession(); try { session.create(sessionKey); if (sessionId != session.session_id()) { @@ -699,18 +699,18 @@ OlmDevice.prototype.addInboundGroupSession = function( OlmDevice.prototype.decryptGroupMessage = function( roomId, senderKey, sessionId, body ) { - var self = this; + let self = this; function decrypt(session, keysClaimed) { - var res = session.decrypt(body); + let res = session.decrypt(body); - var plaintext = res.plaintext; + let plaintext = res.plaintext; if (plaintext === undefined) { // Compatibility for older olm versions. plaintext = res; } else { // Check if we have seen this message index before to detect replay attacks. - var messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index; + let messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index; if (messageIndexKey in self._inboundGroupSessionMessageIndexes) { throw new Error( "Duplicate message index, possible replay attack: " + @@ -722,7 +722,7 @@ OlmDevice.prototype.decryptGroupMessage = function( // the sender must have had the senderKey to persuade us to save the // session. - var keysProved = {curve25519: senderKey}; + let keysProved = {curve25519: senderKey}; self._saveInboundGroupSession( roomId, senderKey, sessionId, session, keysClaimed diff --git a/src/crypto/algorithms/base.js b/src/crypto/algorithms/base.js index 4374fde8f..df24b2aa2 100644 --- a/src/crypto/algorithms/base.js +++ b/src/crypto/algorithms/base.js @@ -20,7 +20,7 @@ limitations under the License. * * @module crypto/algorithms/base */ -var utils = require("../../utils"); +let 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 */ -var EncryptionAlgorithm = function(params) { +let 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. */ -var DecryptionAlgorithm = function(params) { +let DecryptionAlgorithm = function(params) { this._userId = params.userId; this._crypto = params.crypto; this._olmDevice = params.olmDevice; diff --git a/src/crypto/algorithms/index.js b/src/crypto/algorithms/index.js index c8ed0bb05..532b2f205 100644 --- a/src/crypto/algorithms/index.js +++ b/src/crypto/algorithms/index.js @@ -19,7 +19,7 @@ limitations under the License. * @module crypto/algorithms */ -var base = require("./base"); +let base = require("./base"); require("./olm"); require("./megolm"); diff --git a/src/crypto/algorithms/megolm.js b/src/crypto/algorithms/megolm.js index 0a27162ce..7682089fe 100644 --- a/src/crypto/algorithms/megolm.js +++ b/src/crypto/algorithms/megolm.js @@ -21,11 +21,11 @@ limitations under the License. * @module crypto/algorithms/megolm */ -var q = require("q"); +let q = require("q"); -var utils = require("../../utils"); -var olmlib = require("../olmlib"); -var base = require("./base"); +let utils = require("../../utils"); +let olmlib = require("../olmlib"); +let base = require("./base"); /** * @private @@ -59,7 +59,7 @@ function OutboundSessionInfo(sessionId) { OutboundSessionInfo.prototype.needsRotation = function( rotationPeriodMsgs, rotationPeriodMs ) { - var sessionLifetime = new Date().getTime() - this.creationTime; + let sessionLifetime = new Date().getTime() - this.creationTime; if (this.useCount >= rotationPeriodMsgs || sessionLifetime >= rotationPeriodMs @@ -88,16 +88,17 @@ OutboundSessionInfo.prototype.needsRotation = function( OutboundSessionInfo.prototype.sharedWithTooManyDevices = function( devicesInRoom ) { - - for (var userId in this.sharedWithDevices) { - if (!this.sharedWithDevices.hasOwnProperty(userId)) { continue; } + for (let userId in this.sharedWithDevices) { + if (!this.sharedWithDevices.hasOwnProperty(userId)) { + continue; +} if (!devicesInRoom.hasOwnProperty(userId)) { console.log("Starting new session because we shared with " + userId); return true; } - for (var deviceId in this.sharedWithDevices[userId]) { + for (let deviceId in this.sharedWithDevices[userId]) { if (!this.sharedWithDevices[userId].hasOwnProperty(deviceId)) { continue; } @@ -156,9 +157,9 @@ utils.inherits(MegolmEncryption, base.EncryptionAlgorithm); * OutboundSessionInfo when setup is complete. */ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) { - var self = this; + let self = this; - var session; + let session; // takes the previous OutboundSessionInfo, and considers whether to create // a new one. Also shares the key with any (new) devices in the room. @@ -186,23 +187,23 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) { } // now check if we need to share with any devices - var shareMap = {}; + let shareMap = {}; - for (var userId in devicesInRoom) { + for (let userId in devicesInRoom) { if (!devicesInRoom.hasOwnProperty(userId)) { continue; } - var userDevices = devicesInRoom[userId]; + let userDevices = devicesInRoom[userId]; - for (var deviceId in userDevices) { + for (let deviceId in userDevices) { if (!userDevices.hasOwnProperty(deviceId)) { continue; } - var deviceInfo = userDevices[deviceId]; + let deviceInfo = userDevices[deviceId]; - var key = deviceInfo.getIdentityKey(); + let key = deviceInfo.getIdentityKey(); if (key == self._olmDevice.deviceCurve25519Key) { // don't bother sending to ourself continue; @@ -224,10 +225,12 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) { } // helper which returns the session prepared by prepareSession - function returnSession() { return session; } + function returnSession() { + return session; +} // first wait for the previous share to complete - var prom = this._setupPromise.then(prepareSession); + let prom = this._setupPromise.then(prepareSession); // _setupPromise resolves to `session` whether or not the share succeeds this._setupPromise = prom.then(returnSession, returnSession); @@ -242,8 +245,8 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) { * @return {module:crypto/algorithms/megolm.OutboundSessionInfo} session */ MegolmEncryption.prototype._prepareNewSession = function() { - var session_id = this._olmDevice.createOutboundGroupSession(); - var key = this._olmDevice.getOutboundGroupSessionKey(session_id); + let session_id = this._olmDevice.createOutboundGroupSession(); + let key = this._olmDevice.getOutboundGroupSessionKey(session_id); this._olmDevice.addInboundGroupSession( this._roomId, this._olmDevice.deviceCurve25519Key, session_id, @@ -265,10 +268,10 @@ MegolmEncryption.prototype._prepareNewSession = function() { * message has been sent. */ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUser) { - var self = this; + let self = this; - var key = this._olmDevice.getOutboundGroupSessionKey(session.sessionId); - var payload = { + let key = this._olmDevice.getOutboundGroupSessionKey(session.sessionId); + let payload = { type: "m.room_key", content: { algorithm: olmlib.MEGOLM_ALGORITHM, @@ -276,29 +279,29 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse session_id: session.sessionId, session_key: key.key, chain_index: key.chain_index, - } + }, }; - var contentMap = {}; + let contentMap = {}; return olmlib.ensureOlmSessionsForDevices( this._olmDevice, this._baseApis, devicesByUser ).then(function(devicemap) { - var haveTargets = false; + let haveTargets = false; - for (var userId in devicesByUser) { + for (let userId in devicesByUser) { if (!devicesByUser.hasOwnProperty(userId)) { continue; } - var devicesToShareWith = devicesByUser[userId]; - var sessionResults = devicemap[userId]; + let devicesToShareWith = devicesByUser[userId]; + let sessionResults = devicemap[userId]; - for (var i = 0; i < devicesToShareWith.length; i++) { - var deviceInfo = devicesToShareWith[i]; - var deviceId = deviceInfo.deviceId; + for (let i = 0; i < devicesToShareWith.length; i++) { + let deviceInfo = devicesToShareWith[i]; + let deviceId = deviceInfo.deviceId; - var sessionResult = sessionResults[deviceId]; + let sessionResult = sessionResults[deviceId]; if (!sessionResult.sessionId) { // no session with this device, probably because there // were no one-time keys. @@ -318,7 +321,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse "sharing keys with device " + userId + ":" + deviceId ); - var encryptedContent = { + let encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: self._olmDevice.deviceCurve25519Key, ciphertext: {}, @@ -356,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 (var userId in devicesByUser) { + for (let userId in devicesByUser) { if (!devicesByUser.hasOwnProperty(userId)) { continue; } if (!session.sharedWithDevices[userId]) { session.sharedWithDevices[userId] = {}; } - var devicesToShareWith = devicesByUser[userId]; - for (var i = 0; i < devicesToShareWith.length; i++) { - var deviceInfo = devicesToShareWith[i]; + let devicesToShareWith = devicesByUser[userId]; + for (let i = 0; i < devicesToShareWith.length; i++) { + let deviceInfo = devicesToShareWith[i]; session.sharedWithDevices[userId][deviceInfo.deviceId] = key.chain_index; } @@ -383,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) { - var self = this; + let self = this; return this._getDevicesInRoom(room).then(function(devicesInRoom) { return self._ensureOutboundSession(devicesInRoom); }).then(function(session) { - var payloadJson = { + let payloadJson = { room_id: self._roomId, type: eventType, - content: content + content: content, }; - var ciphertext = self._olmDevice.encryptGroupMessage( + let ciphertext = self._olmDevice.encryptGroupMessage( session.sessionId, JSON.stringify(payloadJson) ); - var encryptedContent = { + let encryptedContent = { algorithm: olmlib.MEGOLM_ALGORITHM, sender_key: self._olmDevice.deviceCurve25519Key, ciphertext: ciphertext, @@ -422,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? - var roomMembers = utils.map(room.getJoinedMembers(), function(u) { + let roomMembers = utils.map(room.getJoinedMembers(), function(u) { return u.userId; }); @@ -432,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 (var userId in devices) { + for (let userId in devices) { if (!devices.hasOwnProperty(userId)) { continue; } - var userDevices = devices[userId]; - for (var deviceId in userDevices) { + let userDevices = devices[userId]; + for (let deviceId in userDevices) { if (!userDevices.hasOwnProperty(deviceId)) { continue; } @@ -479,7 +482,7 @@ utils.inherits(MegolmDecryption, base.DecryptionAlgorithm); * problem decrypting the event */ MegolmDecryption.prototype.decryptEvent = function(event) { - var content = event.getWireContent(); + let content = event.getWireContent(); if (!content.sender_key || !content.session_id || !content.ciphertext @@ -487,7 +490,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) { throw new base.DecryptionError("Missing fields in input"); } - var res; + let res; try { res = this._olmDevice.decryptGroupMessage( event.getRoomId(), content.sender_key, content.session_id, content.ciphertext @@ -507,7 +510,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) { ); } - var payload = JSON.parse(res.result); + let 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 @@ -531,8 +534,8 @@ MegolmDecryption.prototype.decryptEvent = function(event) { * @param {module:models/event.MatrixEvent} event */ MegolmDecryption.prototype._addEventToPendingList = function(event) { - var content = event.getWireContent(); - var k = content.sender_key + "|" + content.session_id; + let content = event.getWireContent(); + let k = content.sender_key + "|" + content.session_id; if (!this._pendingEvents[k]) { this._pendingEvents[k] = []; } @@ -546,7 +549,7 @@ MegolmDecryption.prototype._addEventToPendingList = function(event) { */ MegolmDecryption.prototype.onRoomKeyEvent = function(event) { console.log("Adding key from ", event); - var content = event.getContent(); + let content = event.getContent(); if (!content.room_id || !content.session_id || @@ -561,13 +564,13 @@ MegolmDecryption.prototype.onRoomKeyEvent = function(event) { content.session_key, event.getKeysClaimed() ); - var k = event.getSenderKey() + "|" + content.session_id; - var pending = this._pendingEvents[k]; + let k = event.getSenderKey() + "|" + content.session_id; + let pending = this._pendingEvents[k]; if (pending) { // have another go at decrypting events sent with this session. delete this._pendingEvents[k]; - for (var i = 0; i < pending.length; i++) { + for (let i = 0; i < pending.length; i++) { try { this.decryptEvent(pending[i]); console.log("successful re-decryption of", pending[i]); diff --git a/src/crypto/algorithms/olm.js b/src/crypto/algorithms/olm.js index dc42d5b4c..7efa05c64 100644 --- a/src/crypto/algorithms/olm.js +++ b/src/crypto/algorithms/olm.js @@ -20,15 +20,15 @@ limitations under the License. * * @module crypto/algorithms/olm */ -var q = require('q'); +let q = require('q'); -var utils = require("../../utils"); -var olmlib = require("../olmlib"); -var DeviceInfo = require("../deviceinfo"); -var DeviceVerification = DeviceInfo.DeviceVerification; +let utils = require("../../utils"); +let olmlib = require("../olmlib"); +let DeviceInfo = require("../deviceinfo"); +let DeviceVerification = DeviceInfo.DeviceVerification; -var base = require("./base"); +let base = require("./base"); /** * Olm encryption implementation @@ -63,7 +63,7 @@ OlmEncryption.prototype._ensureSession = function(roomMembers) { return q(); } - var self = this; + let 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? - var users = utils.map(room.getJoinedMembers(), function(u) { + let users = utils.map(room.getJoinedMembers(), function(u) { return u.userId; }); - var self = this; + let self = this; return this._ensureSession(users).then(function() { - var payloadFields = { + let payloadFields = { room_id: room.roomId, type: eventType, content: content, }; - var encryptedContent = { + let encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: self._olmDevice.deviceCurve25519Key, ciphertext: {}, }; - for (var i = 0; i < users.length; ++i) { - var userId = users[i]; - var devices = self._crypto.getStoredDevicesForUser(userId); + for (let i = 0; i < users.length; ++i) { + let userId = users[i]; + let devices = self._crypto.getStoredDevicesForUser(userId); - for (var j = 0; j < devices.length; ++j) { - var deviceInfo = devices[j]; - var key = deviceInfo.getIdentityKey(); + for (let j = 0; j < devices.length; ++j) { + let deviceInfo = devices[j]; + let 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) { - var content = event.getWireContent(); - var deviceKey = content.sender_key; - var ciphertext = content.ciphertext; + let content = event.getWireContent(); + let deviceKey = content.sender_key; + let ciphertext = content.ciphertext; if (!ciphertext) { throw new base.DecryptionError("Missing ciphertext"); @@ -168,8 +168,8 @@ OlmDecryption.prototype.decryptEvent = function(event) { if (!(this._olmDevice.deviceCurve25519Key in ciphertext)) { throw new base.DecryptionError("Not included in recipients"); } - var message = ciphertext[this._olmDevice.deviceCurve25519Key]; - var payloadString; + let message = ciphertext[this._olmDevice.deviceCurve25519Key]; + let payloadString; try { payloadString = this._decryptMessage(deviceKey, message); @@ -182,7 +182,7 @@ OlmDecryption.prototype.decryptEvent = function(event) { throw new base.DecryptionError("Bad Encrypted Message"); } - var payload = JSON.parse(payloadString); + let 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) { - var sessionIds = this._olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey); + let sessionIds = this._olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey); // try each session in turn. - var decryptionErrors = {}; - for (var i = 0; i < sessionIds.length; i++) { - var sessionId = sessionIds[i]; + let decryptionErrors = {}; + for (let i = 0; i < sessionIds.length; i++) { + let sessionId = sessionIds[i]; try { - var payload = this._olmDevice.decryptMessage( + let 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) { - var foundSession = this._olmDevice.matchesSession( + let foundSession = this._olmDevice.matchesSession( theirDeviceIdentityKey, sessionId, message.type, message.body ); @@ -295,7 +295,7 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa // prekey message which doesn't match any existing sessions: make a new // session. - var res; + let res; try { res = this._olmDevice.createInboundSession( theirDeviceIdentityKey, message.type, message.body diff --git a/src/crypto/deviceinfo.js b/src/crypto/deviceinfo.js index 8f45aaf28..d14ff27c0 100644 --- a/src/crypto/deviceinfo.js +++ b/src/crypto/deviceinfo.js @@ -62,8 +62,8 @@ function DeviceInfo(deviceId) { * @return {module:crypto~DeviceInfo} new DeviceInfo */ DeviceInfo.fromStorage = function(obj, deviceId) { - var res = new DeviceInfo(deviceId); - for (var prop in obj) { + let res = new DeviceInfo(deviceId); + for (let prop in obj) { if (obj.hasOwnProperty(prop)) { res[prop] = obj[prop]; } @@ -139,7 +139,7 @@ DeviceInfo.DeviceVerification = { BLOCKED: -1, }; -var DeviceVerification = DeviceInfo.DeviceVerification; +let DeviceVerification = DeviceInfo.DeviceVerification; /** */ module.exports = DeviceInfo; diff --git a/src/crypto/index.js b/src/crypto/index.js index fd189d290..ae35bede2 100644 --- a/src/crypto/index.js +++ b/src/crypto/index.js @@ -20,15 +20,15 @@ limitations under the License. * @module crypto */ -var anotherjson = require('another-json'); -var q = require("q"); +let anotherjson = require('another-json'); +let q = require("q"); -var utils = require("../utils"); -var OlmDevice = require("./OlmDevice"); -var olmlib = require("./olmlib"); -var algorithms = require("./algorithms"); -var DeviceInfo = require("./deviceinfo"); -var DeviceVerification = DeviceInfo.DeviceVerification; +let utils = require("../utils"); +let OlmDevice = require("./OlmDevice"); +let olmlib = require("./olmlib"); +let algorithms = require("./algorithms"); +let DeviceInfo = require("./deviceinfo"); +let DeviceVerification = DeviceInfo.DeviceVerification; /** * Cryptography bits @@ -79,7 +79,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) { this._deviceKeys["curve25519:" + this._deviceId] = this._olmDevice.deviceCurve25519Key; - var myDevices = this._sessionStore.getEndToEndDevicesForUser( + let myDevices = this._sessionStore.getEndToEndDevicesForUser( this._userId ); @@ -92,7 +92,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) { if (!myDevices[this._deviceId]) { // add our own deviceinfo to the sessionstore - var deviceInfo = { + let 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? - var rooms = eventEmitter.getRooms(); + let 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) { - var self = this; + let 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,20 +191,20 @@ Crypto.prototype.uploadKeys = function(maxKeys) { // these factors. // We first find how many keys the server has for us. - var keyCount = res.one_time_key_counts.signed_curve25519 || 0; + let keyCount = res.one_time_key_counts.signed_curve25519 || 0; // We then check how many keys we can store in the Account object. - var maxOneTimeKeys = self._olmDevice.maxNumberOfOneTimeKeys(); + let 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. - var keyLimit = Math.floor(maxOneTimeKeys / 2); + let 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. - var numberToGenerate = Math.max(keyLimit - keyCount, 0); + let numberToGenerate = Math.max(keyLimit - keyCount, 0); if (maxKeys !== undefined) { // Creating keys can be an expensive operation so we limit the // number we generate in one go to avoid blocking the application @@ -225,10 +225,10 @@ Crypto.prototype.uploadKeys = function(maxKeys) { // returns a promise which resolves to the response function _uploadDeviceKeys(crypto) { - var userId = crypto._userId; - var deviceId = crypto._deviceId; + let userId = crypto._userId; + let deviceId = crypto._deviceId; - var deviceKeys = { + let 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) { - var oneTimeKeys = crypto._olmDevice.getOneTimeKeys(); - var oneTimeJson = {}; + let oneTimeKeys = crypto._olmDevice.getOneTimeKeys(); + let oneTimeJson = {}; - for (var keyId in oneTimeKeys.curve25519) { + for (let keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { - var k = { + let k = { key: oneTimeKeys.curve25519[keyId], }; crypto._signObject(k); @@ -261,7 +261,7 @@ function _uploadOneTimeKeys(crypto) { } return crypto._baseApis.uploadKeysRequest({ - one_time_keys: oneTimeJson + one_time_keys: oneTimeJson, }, { // for now, we set the device id explicitly, as we may not be using the // same one as used in login. @@ -282,13 +282,13 @@ function _uploadOneTimeKeys(crypto) { * module:crypto/deviceinfo|DeviceInfo}. */ Crypto.prototype.downloadKeys = function(userIds, forceDownload) { - var self = this; + let self = this; // promises we need to wait for while the download happens - var promises = []; + let promises = []; // list of userids we need to download keys for - var downloadUsers = []; + let downloadUsers = []; function perUserCatch(u) { return function(e) { @@ -299,10 +299,10 @@ Crypto.prototype.downloadKeys = function(userIds, forceDownload) { if (forceDownload) { downloadUsers = userIds; } else { - for (var i = 0; i < userIds.length; ++i) { - var u = userIds[i]; + for (let i = 0; i < userIds.length; ++i) { + let u = userIds[i]; - var inprogress = this._keyDownloadsInProgressByUser[u]; + let 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) { - var r = this._doKeyDownloadForUsers(downloadUsers); + let 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) { - var stored = {}; - var self = this; + let stored = {}; + let self = this; userIds.map(function(u) { stored[u] = {}; - var devices = self.getStoredDevicesForUser(u) || []; + let devices = self.getStoredDevicesForUser(u) || []; devices.map(function(dev) { stored[u][dev.deviceId] = dev; }); @@ -351,18 +351,20 @@ 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) { - var self = this; + let self = this; console.log('Starting key download for ' + downloadUsers); - var deferMap = {}; - var promiseMap = {}; + let deferMap = {}; + let promiseMap = {}; downloadUsers.map(function(u) { - var deferred = q.defer(); - var promise = deferred.promise.finally(function() { - var inProgress = self._keyDownloadsInProgressByUser[u]; - utils.removeElement(inProgress, function(e) { return e === promise; }); + let deferred = q.defer(); + let promise = deferred.promise.finally(function() { + let inProgress = self._keyDownloadsInProgressByUser[u]; + utils.removeElement(inProgress, function(e) { + return e === promise; +}); if (inProgress.length === 0) { // no more downloads for this user; remove the element delete self._keyDownloadsInProgressByUser[u]; @@ -381,29 +383,29 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) { this._baseApis.downloadKeysForUsers( downloadUsers ).done(function(res) { - var dk = res.device_keys || {}; + let dk = res.device_keys || {}; - for (var i = 0; i < downloadUsers.length; ++i) { - var userId = downloadUsers[i]; + for (let i = 0; i < downloadUsers.length; ++i) { + let userId = downloadUsers[i]; var deviceId; console.log('got keys for ' + userId + ':', dk[userId]); if (!dk[userId]) { // no result for this user - var err = 'Unknown'; + let err = 'Unknown'; // TODO: do something with res.failures deferMap[userId].reject(err); continue; } // map from deviceid -> deviceinfo for this user - var userStore = {}; - var devs = self._sessionStore.getEndToEndDevicesForUser(userId); + let userStore = {}; + let devs = self._sessionStore.getEndToEndDevicesForUser(userId); if (devs) { for (deviceId in devs) { if (devs.hasOwnProperty(deviceId)) { - var d = DeviceInfo.fromStorage(devs[deviceId], deviceId); + let d = DeviceInfo.fromStorage(devs[deviceId], deviceId); userStore[deviceId] = d; } } @@ -414,7 +416,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) { ); // update the session store - var storage = {}; + let storage = {}; for (deviceId in userStore) { if (!userStore.hasOwnProperty(deviceId)) { continue; @@ -439,7 +441,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) { function _updateStoredDeviceKeysForUser(_olmDevice, userId, userStore, userResult) { - var updated = false; + let updated = false; // remove any devices in the store which aren't in the response for (var deviceId in userStore) { @@ -460,7 +462,7 @@ function _updateStoredDeviceKeysForUser(_olmDevice, userId, userStore, continue; } - var deviceResult = userResult[deviceId]; + let deviceResult = userResult[deviceId]; // check that the user_id and device_id in the response object are // correct @@ -494,18 +496,18 @@ function _storeDeviceKeys(_olmDevice, userStore, deviceResult) { return false; } - var deviceId = deviceResult.device_id; - var userId = deviceResult.user_id; + let deviceId = deviceResult.device_id; + let userId = deviceResult.user_id; - var signKeyId = "ed25519:" + deviceId; - var signKey = deviceResult.keys[signKeyId]; + let signKeyId = "ed25519:" + deviceId; + let signKey = deviceResult.keys[signKeyId]; if (!signKey) { console.log("Device " + userId + ":" + deviceId + " has no ed25519 key"); return false; } - var unsigned = deviceResult.unsigned || {}; + let unsigned = deviceResult.unsigned || {}; try { olmlib.verifySignature(_olmDevice, deviceResult, userId, deviceId, signKey); @@ -516,7 +518,7 @@ function _storeDeviceKeys(_olmDevice, userStore, deviceResult) { } // DeviceInfo - var deviceStore; + let deviceStore; if (deviceId in userStore) { // already have this device. @@ -550,12 +552,12 @@ function _storeDeviceKeys(_olmDevice, userStore, deviceResult) { * managed to get a list of devices for this user yet. */ Crypto.prototype.getStoredDevicesForUser = function(userId) { - var devs = this._sessionStore.getEndToEndDevicesForUser(userId); + let devs = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devs) { return null; } - var res = []; - for (var deviceId in devs) { + let res = []; + for (let deviceId in devs) { if (devs.hasOwnProperty(deviceId)) { res.push(DeviceInfo.fromStorage(devs[deviceId], deviceId)); } @@ -573,7 +575,7 @@ Crypto.prototype.getStoredDevicesForUser = function(userId) { * if we don't know about this device */ Crypto.prototype.getStoredDevice = function(userId, deviceId) { - var devs = this._sessionStore.getEndToEndDevicesForUser(userId); + let devs = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devs || !devs[deviceId]) { return undefined; } @@ -591,13 +593,13 @@ Crypto.prototype.getStoredDevice = function(userId, deviceId) { * "key", and "display_name" parameters. */ Crypto.prototype.listDeviceKeys = function(userId) { - var devices = this.getStoredDevicesForUser(userId) || []; + let devices = this.getStoredDevicesForUser(userId) || []; - var result = []; + let result = []; - for (var i = 0; i < devices.length; ++i) { - var device = devices[i]; - var ed25519Key = device.getFingerprint(); + for (let i = 0; i < devices.length; ++i) { + let device = devices[i]; + let ed25519Key = device.getFingerprint(); if (ed25519Key) { result.push({ id: device.deviceId, @@ -611,8 +613,12 @@ Crypto.prototype.listDeviceKeys = function(userId) { // sort by deviceid result.sort(function(a, b) { - if (a.deviceId < b.deviceId) { return -1; } - if (a.deviceId > b.deviceId) { return 1; } + if (a.deviceId < b.deviceId) { + return -1; +} + if (a.deviceId > b.deviceId) { + return 1; +} return 0; }); @@ -637,25 +643,25 @@ Crypto.prototype.getDeviceByIdentityKey = function(userId, algorithm, sender_key return null; } - var devices = this._sessionStore.getEndToEndDevicesForUser(userId); + let devices = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devices) { return null; } - for (var deviceId in devices) { + for (let deviceId in devices) { if (!devices.hasOwnProperty(deviceId)) { continue; } - var device = devices[deviceId]; - for (var keyId in device.keys) { + let device = devices[deviceId]; + for (let keyId in device.keys) { if (!device.keys.hasOwnProperty(keyId)) { continue; } if (keyId.indexOf("curve25519:") !== 0) { continue; } - var deviceKey = device.keys[keyId]; + let deviceKey = device.keys[keyId]; if (deviceKey == sender_key) { return DeviceInfo.fromStorage(device, deviceId); } @@ -680,13 +686,13 @@ Crypto.prototype.getDeviceByIdentityKey = function(userId, algorithm, sender_key * leave unchanged. */ Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified, blocked) { - var devices = this._sessionStore.getEndToEndDevicesForUser(userId); + let devices = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devices || !devices[deviceId]) { throw new Error("Unknown device " + userId + ":" + deviceId); } - var dev = devices[deviceId]; - var verificationStatus = dev.verified; + let dev = devices[deviceId]; + let verificationStatus = dev.verified; if (verified) { verificationStatus = DeviceVerification.VERIFIED; @@ -723,12 +729,12 @@ Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified, bl * @return {Object.} */ Crypto.prototype.getOlmSessionsForUser = function(userId) { - var devices = this.getStoredDevicesForUser(userId) || []; - var result = {}; - for (var j = 0; j < devices.length; ++j) { - var device = devices[j]; - var deviceKey = device.getIdentityKey(); - var sessions = this._olmDevice.getSessionInfoForDevice(deviceKey); + let devices = this.getStoredDevicesForUser(userId) || []; + let result = {}; + for (let j = 0; j < devices.length; ++j) { + let device = devices[j]; + let deviceKey = device.getIdentityKey(); + let sessions = this._olmDevice.getSessionInfoForDevice(deviceKey); result[device.deviceId] = { deviceIdKey: deviceKey, @@ -747,8 +753,8 @@ Crypto.prototype.getOlmSessionsForUser = function(userId) { * @return {module:crypto/deviceinfo?} */ Crypto.prototype.getEventSenderDeviceInfo = function(event) { - var sender_key = event.getSenderKey(); - var algorithm = event.getWireContent().algorithm; + let sender_key = event.getSenderKey(); + let algorithm = event.getWireContent().algorithm; if (!sender_key || !algorithm) { return null; @@ -758,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. - var device = this.getDeviceByIdentityKey( + let device = this.getDeviceByIdentityKey( event.getSender(), algorithm, sender_key ); @@ -775,7 +781,7 @@ Crypto.prototype.getEventSenderDeviceInfo = function(event) { // // (see https://github.com/vector-im/vector-web/issues/2215) - var claimedKey = event.getKeysClaimed().ed25519; + let claimedKey = event.getKeysClaimed().ed25519; if (!claimedKey) { console.warn("Event " + event.getId() + " claims no ed25519 key: " + "cannot verify sending device"); @@ -802,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?) - var existingConfig = this._sessionStore.getEndToEndRoom(roomId); + let existingConfig = this._sessionStore.getEndToEndRoom(roomId); if (existingConfig) { if (JSON.stringify(existingConfig) != JSON.stringify(config)) { console.error("Ignoring m.room.encryption event which requests " + @@ -811,7 +817,7 @@ Crypto.prototype.setRoomEncryption = function(roomId, config) { } } - var AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm]; + let AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm]; if (!AlgClass) { throw new Error("Unable to encrypt with " + config.algorithm); } @@ -822,7 +828,7 @@ Crypto.prototype.setRoomEncryption = function(roomId, config) { }; this._sessionStore.storeEndToEndRoom(roomId, config); - var alg = new AlgClass({ + let alg = new AlgClass({ userId: this._userId, deviceId: this._deviceId, crypto: this, @@ -853,17 +859,17 @@ Crypto.prototype.setRoomEncryption = function(roomId, config) { * {@link module:crypto~OlmSessionResult} */ Crypto.prototype.ensureOlmSessionsForUsers = function(users) { - var devicesByUser = {}; + let devicesByUser = {}; - for (var i = 0; i < users.length; ++i) { - var userId = users[i]; + for (let i = 0; i < users.length; ++i) { + let userId = users[i]; devicesByUser[userId] = []; - var devices = this.getStoredDevicesForUser(userId) || []; - for (var j = 0; j < devices.length; ++j) { - var deviceInfo = devices[j]; + let devices = this.getStoredDevicesForUser(userId) || []; + for (let j = 0; j < devices.length; ++j) { + let deviceInfo = devices[j]; - var key = deviceInfo.getIdentityKey(); + let key = deviceInfo.getIdentityKey(); if (key == this._olmDevice.deviceCurve25519Key) { // don't bother setting up session to ourself continue; @@ -914,9 +920,9 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) { throw new Error("Cannot send encrypted messages in unknown rooms"); } - var roomId = event.getRoomId(); + let roomId = event.getRoomId(); - var alg = this._roomEncryptors[roomId]; + let alg = this._roomEncryptors[roomId]; if (!alg) { // not encrypting messages in this room @@ -934,7 +940,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. - var myKeys = { + let myKeys = { curve25519: this._olmDevice.deviceCurve25519Key, ed25519: this._olmDevice.deviceEd25519Key, }; @@ -954,8 +960,8 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) { * @raises {algorithms.DecryptionError} if there is a problem decrypting the event */ Crypto.prototype.decryptEvent = function(event) { - var content = event.getWireContent(); - var alg = this._getRoomDecryptor(event.getRoomId(), content.algorithm); + let content = event.getWireContent(); + let alg = this._getRoomDecryptor(event.getRoomId(), content.algorithm); alg.decryptEvent(event); }; @@ -966,8 +972,8 @@ Crypto.prototype.decryptEvent = function(event) { * @param {module:models/event.MatrixEvent} event encryption event */ Crypto.prototype._onCryptoEvent = function(event) { - var roomId = event.getRoomId(); - var content = event.getContent(); + let roomId = event.getRoomId(); + let content = event.getContent(); try { this.setRoomEncryption(roomId, content); @@ -998,27 +1004,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. - var roomsByUser = {}; - for (var i = 0; i < rooms.length; i++) { - var room = rooms[i]; + let roomsByUser = {}; + for (let i = 0; i < rooms.length; i++) { + let room = rooms[i]; // check for rooms with encryption enabled - var alg = this._roomEncryptors[room.roomId]; + let alg = this._roomEncryptors[room.roomId]; if (!alg) { continue; } // ignore any rooms which we have left - var me = room.getMember(this._userId); + let me = room.getMember(this._userId); if (!me || ( me.membership !== "join" && me.membership !== "invite" )) { continue; } - var members = room.getJoinedMembers(); - for (var j = 0; j < members.length; j++) { - var m = members[j]; + let members = room.getJoinedMembers(); + for (let j = 0; j < members.length; j++) { + let m = members[j]; if (!roomsByUser[m.userId]) { roomsByUser[m.userId] = []; } @@ -1027,8 +1033,8 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) { } // build a per-device message for each user - var content = {}; - for (var userId in roomsByUser) { + let content = {}; + for (let userId in roomsByUser) { if (!roomsByUser.hasOwnProperty(userId)) { continue; } @@ -1040,7 +1046,7 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) { }; } - var self = this; + let self = this; this._baseApis.sendToDevice( "m.new_device", // OH HAI! content @@ -1056,14 +1062,14 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) { * @param {module:models/event.MatrixEvent} event key event */ Crypto.prototype._onRoomKeyEvent = function(event) { - var content = event.getContent(); + let content = event.getContent(); if (!content.room_id || !content.algorithm) { console.error("key event is missing fields"); return; } - var alg = this._getRoomDecryptor(content.room_id, content.algorithm); + let alg = this._getRoomDecryptor(content.room_id, content.algorithm); alg.onRoomKeyEvent(event); }; @@ -1076,7 +1082,6 @@ Crypto.prototype._onRoomKeyEvent = function(event) { * @param {string=} oldMembership previous membership */ Crypto.prototype._onRoomMembership = function(event, member, oldMembership) { - // this event handler is registered on the *client* (as opposed to the room // member itself), which means it is only called on changes to the *live* // membership state (ie, it is not called when we back-paginate, nor when @@ -1085,9 +1090,9 @@ Crypto.prototype._onRoomMembership = function(event, member, oldMembership) { // Further, it is automatically registered and called when new members // arrive in the room. - var roomId = member.roomId; + let roomId = member.roomId; - var alg = this._roomEncryptors[roomId]; + let alg = this._roomEncryptors[roomId]; if (!alg) { // not encrypting in this room return; @@ -1104,10 +1109,10 @@ Crypto.prototype._onRoomMembership = function(event, member, oldMembership) { * @param {module:models/event.MatrixEvent} event announcement event */ Crypto.prototype._onNewDeviceEvent = function(event) { - var content = event.getContent(); - var userId = event.getSender(); - var deviceId = content.device_id; - var rooms = content.rooms; + let content = event.getContent(); + let userId = event.getSender(); + let deviceId = content.device_id; + let rooms = content.rooms; if (!rooms || !deviceId) { console.warn("new_device event missing keys"); @@ -1135,15 +1140,15 @@ Crypto.prototype._onNewDeviceEvent = function(event) { * Start device queries for any users who sent us an m.new_device recently */ Crypto.prototype._flushNewDeviceRequests = function() { - var self = this; + let self = this; - var users = utils.keys(this._pendingUsersWithNewDevices); + let users = utils.keys(this._pendingUsersWithNewDevices); if (users.length === 0) { return; } - var r = this._doKeyDownloadForUsers(users); + let r = this._doKeyDownloadForUsers(users); // we've kicked off requests to these users: remove their // pending flag for now. @@ -1185,8 +1190,8 @@ Crypto.prototype._flushNewDeviceRequests = function() { * unknown */ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) { - var decryptors; - var alg; + let decryptors; + let alg; roomId = roomId || null; if (roomId) { @@ -1201,7 +1206,7 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) { } } - var AlgClass = algorithms.DECRYPTION_CLASSES[algorithm]; + let AlgClass = algorithms.DECRYPTION_CLASSES[algorithm]; if (!AlgClass) { throw new algorithms.DecryptionError( 'Unknown encryption algorithm "' + algorithm + '".' @@ -1227,7 +1232,7 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) { * @param {Object} obj Object to which we will add a 'signatures' property */ Crypto.prototype._signObject = function(obj) { - var sigs = {}; + let sigs = {}; sigs[this._userId] = {}; sigs[this._userId]["ed25519:" + this._deviceId] = this._olmDevice.sign(anotherjson.stringify(obj)); diff --git a/src/crypto/olmlib.js b/src/crypto/olmlib.js index fc2a66fe8..c02ac5420 100644 --- a/src/crypto/olmlib.js +++ b/src/crypto/olmlib.js @@ -20,10 +20,10 @@ limitations under the License. * Utilities common to olm encryption algorithms */ -var q = require('q'); -var anotherjson = require('another-json'); +let q = require('q'); +let anotherjson = require('another-json'); -var utils = require("../utils"); +let utils = require("../utils"); /** * matrix algorithm tag for olm @@ -54,8 +54,8 @@ module.exports.encryptMessageForDevice = function( ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice, payloadFields ) { - var deviceKey = recipientDevice.getIdentityKey(); - var sessionId = olmDevice.getSessionIdForDevice(deviceKey); + let deviceKey = recipientDevice.getIdentityKey(); + let 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 ); - var payload = { + let payload = { sender: ourUserId, sender_device: ourDeviceId, @@ -121,20 +121,22 @@ module.exports.encryptMessageForDevice = function( module.exports.ensureOlmSessionsForDevices = function( olmDevice, baseApis, devicesByUser ) { - var devicesWithoutSession = [ + let devicesWithoutSession = [ // [userId, deviceId], ... ]; - var result = {}; + let result = {}; - for (var userId in devicesByUser) { - if (!devicesByUser.hasOwnProperty(userId)) { continue; } + for (let userId in devicesByUser) { + if (!devicesByUser.hasOwnProperty(userId)) { + continue; +} result[userId] = {}; - var devices = devicesByUser[userId]; - for (var j = 0; j < devices.length; j++) { - var deviceInfo = devices[j]; - var deviceId = deviceInfo.deviceId; - var key = deviceInfo.getIdentityKey(); - var sessionId = olmDevice.getSessionIdForDevice(key); + let 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); if (sessionId === null) { devicesWithoutSession.push([userId, deviceId]); } @@ -155,26 +157,28 @@ module.exports.ensureOlmSessionsForDevices = function( // // That should eventually resolve itself, but it's poor form. - var oneTimeKeyAlgorithm = "signed_curve25519"; + let oneTimeKeyAlgorithm = "signed_curve25519"; return baseApis.claimOneTimeKeys( devicesWithoutSession, oneTimeKeyAlgorithm ).then(function(res) { - var otk_res = res.one_time_keys || {}; - for (var userId in devicesByUser) { - if (!devicesByUser.hasOwnProperty(userId)) { continue; } - var userRes = otk_res[userId] || {}; - var devices = devicesByUser[userId]; - for (var j = 0; j < devices.length; j++) { - var deviceInfo = devices[j]; - var deviceId = deviceInfo.deviceId; + let otk_res = res.one_time_keys || {}; + for (let userId in devicesByUser) { + if (!devicesByUser.hasOwnProperty(userId)) { + continue; +} + let userRes = otk_res[userId] || {}; + let devices = devicesByUser[userId]; + for (let j = 0; j < devices.length; j++) { + let deviceInfo = devices[j]; + let deviceId = deviceInfo.deviceId; if (result[userId][deviceId].sessionId) { // we already have a result for this device continue; } - var deviceRes = userRes[deviceId] || {}; - var oneTimeKey = null; - for (var keyId in deviceRes) { + let deviceRes = userRes[deviceId] || {}; + let oneTimeKey = null; + for (let keyId in deviceRes) { if (keyId.indexOf(oneTimeKeyAlgorithm + ":") === 0) { oneTimeKey = deviceRes[keyId]; } @@ -188,7 +192,7 @@ module.exports.ensureOlmSessionsForDevices = function( continue; } - var sid = _verifyKeyAndStartSession( + let sid = _verifyKeyAndStartSession( olmDevice, oneTimeKey, userId, deviceInfo ); result[userId][deviceId].sessionId = sid; @@ -200,7 +204,7 @@ module.exports.ensureOlmSessionsForDevices = function( function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) { - var deviceId = deviceInfo.deviceId; + let deviceId = deviceInfo.deviceId; try { _verifySignature( olmDevice, oneTimeKey, userId, deviceId, @@ -214,7 +218,7 @@ function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) { return null; } - var sid; + let sid; try { sid = olmDevice.createOutboundSession( deviceInfo.getIdentityKey(), oneTimeKey.key @@ -246,13 +250,13 @@ function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) { * * @param {string} signingKey base64-ed ed25519 public key */ -var _verifySignature = module.exports.verifySignature = function( +let _verifySignature = module.exports.verifySignature = function( olmDevice, obj, signingUserId, signingDeviceId, signingKey ) { - var signKeyId = "ed25519:" + signingDeviceId; - var signatures = obj.signatures || {}; - var userSigs = signatures[signingUserId] || {}; - var signature = userSigs[signKeyId]; + let signKeyId = "ed25519:" + signingDeviceId; + let signatures = obj.signatures || {}; + let userSigs = signatures[signingUserId] || {}; + let signature = userSigs[signKeyId]; if (!signature) { throw Error("No signature"); } @@ -261,7 +265,7 @@ var _verifySignature = module.exports.verifySignature = function( // anotherjson delete obj.unsigned; delete obj.signatures; - var json = anotherjson.stringify(obj); + let json = anotherjson.stringify(obj); olmDevice.verifySignature( signingKey, json, signature diff --git a/src/filter-component.js b/src/filter-component.js index 47fd298da..bb2133698 100644 --- a/src/filter-component.js +++ b/src/filter-component.js @@ -27,10 +27,9 @@ limitations under the License. */ function _matches_wildcard(actual_value, filter_value) { if (filter_value.endsWith("*")) { - var type_prefix = filter_value.slice(0, -1); + let type_prefix = filter_value.slice(0, -1); return actual_value.substr(0, type_prefix.length) === type_prefix; - } - else { + } else { return actual_value === filter_value; } } @@ -84,24 +83,29 @@ FilterComponent.prototype.check = function(event) { * @return {bool} true if the event fields match the filter */ FilterComponent.prototype._checkFields = - function(room_id, sender, event_type, contains_url) -{ - var literal_keys = { - "rooms": function(v) { return room_id === v; }, - "senders": function(v) { return sender === v; }, - "types": function(v) { return _matches_wildcard(event_type, v); }, + function(room_id, sender, event_type, contains_url) { + let literal_keys = { + "rooms": function(v) { + return room_id === v; +}, + "senders": function(v) { + return sender === v; +}, + "types": function(v) { + return _matches_wildcard(event_type, v); +}, }; - var self = this; + let self = this; Object.keys(literal_keys).forEach(function(name) { - var match_func = literal_keys[name]; - var not_name = "not_" + name; - var disallowed_values = self[not_name]; + let match_func = literal_keys[name]; + let not_name = "not_" + name; + let disallowed_values = self[not_name]; if (disallowed_values.map(match_func)) { return false; } - var allowed_values = self[name]; + let allowed_values = self[name]; if (allowed_values) { if (!allowed_values.map(match_func)) { return false; @@ -109,7 +113,7 @@ FilterComponent.prototype._checkFields = } }); - var contains_url_filter = this.filter_json.contains_url; + let contains_url_filter = this.filter_json.contains_url; if (contains_url_filter !== undefined) { if (contains_url_filter !== contains_url) { return false; diff --git a/src/filter.js b/src/filter.js index 1aa892960..c64b7aff1 100644 --- a/src/filter.js +++ b/src/filter.js @@ -18,7 +18,7 @@ limitations under the License. * @module filter */ -var FilterComponent = require("./filter-component"); +let FilterComponent = require("./filter-component"); /** * @param {Object} obj @@ -26,9 +26,9 @@ var FilterComponent = require("./filter-component"); * @param {*} val */ function setProp(obj, keyNesting, val) { - var nestedKeys = keyNesting.split("."); - var currentObj = obj; - for (var i = 0; i < (nestedKeys.length - 1); i++) { + let nestedKeys = keyNesting.split("."); + let currentObj = obj; + for (let i = 0; i < (nestedKeys.length - 1); i++) { if (!currentObj[nestedKeys[i]]) { currentObj[nestedKeys[i]] = {}; } @@ -106,10 +106,10 @@ Filter.prototype.setDefinition = function(definition) { // "event_fields": ["type", "content", "sender"] // } - var room_filter_json = definition.room; + let room_filter_json = definition.room; // consider the top level rooms/not_rooms filter - var room_filter_fields = {}; + let 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) { - var filter = new Filter(userId, filterId); + let filter = new Filter(userId, filterId); filter.setDefinition(jsonObj); return filter; }; diff --git a/src/http-api.js b/src/http-api.js index 35dcbb4c7..35a0330f1 100644 --- a/src/http-api.js +++ b/src/http-api.js @@ -18,13 +18,13 @@ limitations under the License. * This is an internal module. See {@link MatrixHttpApi} for the public class. * @module http-api */ -var q = require("q"); -var utils = require("./utils"); +let q = require("q"); +let 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. -var callbacks = require("./realtime-callbacks"); +let callbacks = require("./realtime-callbacks"); /* TODO: @@ -91,13 +91,13 @@ module.exports.MatrixHttpApi.prototype = { * path and query parameters respectively. */ getContentUri: function() { - var params = { - access_token: this.opts.accessToken + let params = { + access_token: this.opts.accessToken, }; return { base: this.opts.baseUrl, path: "/_matrix/media/v1/upload", - params: params + params: params, }; }, @@ -145,16 +145,16 @@ 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. - var contentType = opts.type || file.type || 'application/octet-stream'; - var fileName = opts.name || file.name; + let contentType = opts.type || file.type || 'application/octet-stream'; + let fileName = opts.name || file.name; // we used to recommend setting file.stream to the thing to upload on // nodejs. - var body = file.stream ? file.stream : file; + let body = file.stream ? file.stream : file; // backwards-compatibility hacks where we used to do different things // between browser and node. - var rawResponse = opts.rawResponse; + let rawResponse = opts.rawResponse; if (rawResponse === undefined) { if (global.XMLHttpRequest) { rawResponse = false; @@ -169,7 +169,7 @@ module.exports.MatrixHttpApi.prototype = { } } - var onlyContentUri = opts.onlyContentUri; + let onlyContentUri = opts.onlyContentUri; if (!rawResponse && onlyContentUri === undefined) { if (global.XMLHttpRequest) { console.warn( @@ -192,17 +192,17 @@ module.exports.MatrixHttpApi.prototype = { // (browser-request doesn't support progress either, which is also kind // of important here) - var upload = { loaded: 0, total: 0 }; - var promise; + let upload = { loaded: 0, total: 0 }; + let promise; // XMLHttpRequest doesn't parse JSON for us. request normally does, but // we're setting opts.json=false so that it doesn't JSON-encode the // request, which also means it doesn't JSON-decode the response. Either // way, we have to JSON-parse the response ourselves. - var bodyParser = null; + let bodyParser = null; if (!rawResponse) { bodyParser = function(rawBody) { - var body = JSON.parse(rawBody); + let body = JSON.parse(rawBody); if (onlyContentUri) { body = body.content_uri; if (body === undefined) { @@ -214,12 +214,12 @@ module.exports.MatrixHttpApi.prototype = { } if (global.XMLHttpRequest) { - var defer = q.defer(); - var xhr = new global.XMLHttpRequest(); + let defer = q.defer(); + let xhr = new global.XMLHttpRequest(); upload.xhr = xhr; - var cb = requestCallback(defer, opts.callback, this.opts.onlyData); + let cb = requestCallback(defer, opts.callback, this.opts.onlyData); - var timeout_fn = function() { + let timeout_fn = function() { xhr.abort(); cb(new Error('Timeout')); }; @@ -257,7 +257,7 @@ module.exports.MatrixHttpApi.prototype = { xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000); defer.notify(ev); }); - var url = this.opts.baseUrl + "/_matrix/media/v1/upload"; + let url = this.opts.baseUrl + "/_matrix/media/v1/upload"; url += "?access_token=" + encodeURIComponent(this.opts.accessToken); url += "&filename=" + encodeURIComponent(fileName); @@ -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 { - var queryParams = { + let queryParams = { filename: fileName, }; @@ -283,11 +283,11 @@ module.exports.MatrixHttpApi.prototype = { ); } - var self = this; + let self = this; // remove the upload from the list on completion - var promise0 = promise.finally(function() { - for (var i = 0; i < self.uploads.length; ++i) { + let promise0 = promise.finally(function() { + for (let i = 0; i < self.uploads.length; ++i) { if (self.uploads[i] === upload) { self.uploads.splice(i, 1); return; @@ -317,7 +317,7 @@ module.exports.MatrixHttpApi.prototype = { }, idServerRequest: function(callback, method, path, params, prefix) { - var fullUri = this.opts.idBaseUrl + prefix + path; + let fullUri = this.opts.idBaseUrl + prefix + path; if (callback !== undefined && !utils.isFunction(callback)) { throw Error( @@ -325,12 +325,12 @@ module.exports.MatrixHttpApi.prototype = { ); } - var opts = { + let opts = { uri: fullUri, method: method, withCredentials: false, json: false, - _matrix_opts: this.opts + _matrix_opts: this.opts, }; if (method == 'GET') { opts.qs = params; @@ -338,7 +338,7 @@ module.exports.MatrixHttpApi.prototype = { opts.form = params; } - var defer = q.defer(); + let 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; } - var request_promise = this.request( + let request_promise = this.request( callback, method, path, queryParams, data, opts ); - var self = this; + let 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 || {}; - var prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix; - var fullUri = this.opts.baseUrl + prefix + path; + let prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix; + let fullUri = this.opts.baseUrl + prefix + path; return this.requestOtherUrl( callback, method, fullUri, queryParams, data, opts @@ -551,7 +551,7 @@ module.exports.MatrixHttpApi.prototype = { } else if (isFinite(opts)) { // opts used to be localTimeoutMs opts = { - localTimeoutMs: opts + localTimeoutMs: opts, }; } @@ -572,7 +572,7 @@ module.exports.MatrixHttpApi.prototype = { * @return {string} URL */ getUrl: function(path, queryParams, prefix) { - var queryString = ""; + let queryString = ""; if (queryParams) { queryString = "?" + utils.encodeParams(queryParams); } @@ -613,22 +613,24 @@ module.exports.MatrixHttpApi.prototype = { } opts = opts || {}; - var self = this; + let self = this; if (this.opts.extraParams) { - for (var key in this.opts.extraParams) { - if (!this.opts.extraParams.hasOwnProperty(key)) { continue; } + for (let key in this.opts.extraParams) { + if (!this.opts.extraParams.hasOwnProperty(key)) { + continue; +} queryParams[key] = this.opts.extraParams[key]; } } - var json = opts.json === undefined ? true : opts.json; + let json = opts.json === undefined ? true : opts.json; - var defer = q.defer(); + let defer = q.defer(); - var timeoutId; - var timedOut = false; - var req; - var localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs; + let timeoutId; + let timedOut = false; + let req; + let localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs; if (localTimeoutMs) { timeoutId = callbacks.setTimeout(function() { timedOut = true; @@ -638,12 +640,12 @@ module.exports.MatrixHttpApi.prototype = { defer.reject(new module.exports.MatrixError({ error: "Locally timed out waiting for a response", errcode: "ORG.MATRIX.JSSDK_TIMEOUT", - timeout: localTimeoutMs + timeout: localTimeoutMs, })); }, localTimeoutMs); } - var reqPromise = defer.promise; + let reqPromise = defer.promise; try { req = this.opts.request( @@ -656,7 +658,7 @@ module.exports.MatrixHttpApi.prototype = { json: json, timeout: localTimeoutMs, headers: opts.headers || {}, - _matrix_opts: this.opts + _matrix_opts: this.opts, }, function(err, response, body) { if (localTimeoutMs) { @@ -668,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 - var parseErrorJson = !json; - var handlerFn = requestCallback( + let parseErrorJson = !json; + let handlerFn = requestCallback( defer, callback, self.opts.onlyData, parseErrorJson, opts.bodyParser @@ -682,15 +684,14 @@ module.exports.MatrixHttpApi.prototype = { // abort() operations on underlying HTTP requests :( reqPromise.abort = req.abort.bind(req); } - } - catch (ex) { + } catch (ex) { defer.reject(ex); if (callback) { callback(ex); } } return reqPromise; - } + }, }; /* @@ -704,7 +705,7 @@ module.exports.MatrixHttpApi.prototype = { * If parseErrorJson is true, we will JSON.parse the body if we get a 4xx error. * */ -var requestCallback = function( +let requestCallback = function( defer, userDefinedCallback, onlyData, parseErrorJson, bodyParser ) { @@ -733,12 +734,11 @@ var requestCallback = function( if (err) { defer.reject(err); userDefinedCallback(err); - } - else { - var res = { + } else { + let res = { code: response.statusCode, headers: response.headers, - data: body + data: body, }; defer.resolve(onlyData ? body : res); userDefinedCallback(null, onlyData ? body : res); diff --git a/src/interactive-auth.js b/src/interactive-auth.js index 8b6395e23..d4e2d7f14 100644 --- a/src/interactive-auth.js +++ b/src/interactive-auth.js @@ -16,9 +16,9 @@ limitations under the License. "use strict"; /** @module interactive-auth */ -var q = require("q"); +let q = require("q"); -var utils = require("./utils"); +let utils = require("./utils"); /** * Abstracts the logic used to drive the interactive auth process. @@ -93,7 +93,7 @@ InteractiveAuth.prototype = { * @return {object?} any parameters from the server for this stage */ getStageParams: function(loginType) { - var params = {}; + let params = {}; if (this._data && this._data.params) { params = this._data.params; } @@ -115,7 +115,7 @@ InteractiveAuth.prototype = { } // use the sessionid from the last request. - var auth = { + let auth = { session: this._data.session, }; utils.extend(auth, authData); @@ -131,12 +131,12 @@ InteractiveAuth.prototype = { * @param {object?} auth new auth dict, including session id */ _doRequest: function(auth) { - var self = this; + let 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 // extra q().then) - var prom; + let prom; try { prom = this._requestCallback(auth); } catch (e) { @@ -164,12 +164,12 @@ InteractiveAuth.prototype = { * @private */ _startNextAuthStage: function() { - var nextStage = this._chooseStage(); + let nextStage = this._chooseStage(); if (!nextStage) { throw new Error("No incomplete flows from the server"); } - var stageError = null; + let stageError = null; if (this._data.errcode || this._data.error) { stageError = { errcode: this._data.errcode || "", @@ -186,9 +186,9 @@ InteractiveAuth.prototype = { * @return {string?} login type */ _chooseStage: function() { - var flow = this._chooseFlow(); + let flow = this._chooseFlow(); console.log("Active flow => %s", JSON.stringify(flow)); - var nextStage = this._firstUncompletedStage(flow); + let nextStage = this._firstUncompletedStage(flow); console.log("Next stage: %s", nextStage); return nextStage; }, @@ -200,7 +200,7 @@ InteractiveAuth.prototype = { * @return {object} flow */ _chooseFlow: function() { - var flows = this._data.flows || []; + let 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) { - var completed = (this._data || {}).completed || []; - for (var i = 0; i < flow.stages.length; ++i) { - var stageType = flow.stages[i]; + let completed = (this._data || {}).completed || []; + for (let i = 0; i < flow.stages.length; ++i) { + let stageType = flow.stages[i]; if (completed.indexOf(stageType) === -1) { return stageType; } diff --git a/src/matrix.js b/src/matrix.js index 3a7edcff4..b434d6551 100644 --- a/src/matrix.js +++ b/src/matrix.js @@ -68,7 +68,7 @@ module.exports.createNewMatrixCall = require("./webrtc/call").createNewMatrixCal // expose the underlying request object so different environments can use // different request libs (e.g. request or browser-request) -var request; +let request; /** * The function used to perform HTTP requests. Only use this if you want to * use a different HTTP library, e.g. Angular's $http. This should @@ -94,7 +94,7 @@ module.exports.getRequest = function() { * @param {requestWrapperFunction} wrapper The wrapping function. */ module.exports.wrapRequest = function(wrapper) { - var origRequest = request; + let origRequest = request; request = function(options, callback) { return wrapper(origRequest, options, callback); }; @@ -119,12 +119,12 @@ module.exports.wrapRequest = function(wrapper) { module.exports.createClient = function(opts) { if (typeof opts === "string") { opts = { - "baseUrl": opts + "baseUrl": opts, }; } opts.request = opts.request || request; opts.store = opts.store || new module.exports.MatrixInMemoryStore({ - localStorage: global.localStorage + localStorage: global.localStorage, }); opts.scheduler = opts.scheduler || new module.exports.MatrixScheduler(); return new module.exports.MatrixClient(opts); diff --git a/src/models/event-timeline-set.js b/src/models/event-timeline-set.js index 6b827db73..696135e24 100644 --- a/src/models/event-timeline-set.js +++ b/src/models/event-timeline-set.js @@ -17,14 +17,14 @@ limitations under the License. /** * @module models/event-timeline-set */ -var EventEmitter = require("events").EventEmitter; -var utils = require("../utils"); -var EventTimeline = require("./event-timeline"); +let EventEmitter = require("events").EventEmitter; +let utils = require("../utils"); +let EventTimeline = require("./event-timeline"); // var DEBUG = false; -var DEBUG = true; +let DEBUG = true; -var debuglog; +let debuglog; if (DEBUG) { // using bind means that we get to keep useful line numbers in the console debuglog = console.log.bind(console); @@ -106,8 +106,7 @@ EventTimelineSet.prototype.getPendingEvents = function() { if (this._filter) { return this._filter.filterRoomTimeline(this.room.getPendingEvents()); - } - else { + } else { return this.room.getPendingEvents(); } }; @@ -137,7 +136,7 @@ EventTimelineSet.prototype.eventIdToTimeline = function(eventId) { * @param {String} newEventId event ID of the replacement event */ EventTimelineSet.prototype.replaceEventId = function(oldEventId, newEventId) { - var existingTimeline = this._eventIdToTimeline[oldEventId]; + let existingTimeline = this._eventIdToTimeline[oldEventId]; if (existingTimeline) { delete this._eventIdToTimeline[oldEventId]; this._eventIdToTimeline[newEventId] = existingTimeline; @@ -155,7 +154,7 @@ EventTimelineSet.prototype.replaceEventId = function(oldEventId, newEventId) { * @fires module:client~MatrixClient#event:"Room.timelineReset" */ EventTimelineSet.prototype.resetLiveTimeline = function(backPaginationToken, flush) { - var newTimeline; + let newTimeline; if (!this._timelineSupport || flush) { // if timeline support is disabled, forget about the old timelines @@ -167,12 +166,16 @@ EventTimelineSet.prototype.resetLiveTimeline = function(backPaginationToken, flu } // initialise the state in the new timeline from our last known state - var evMap = this._liveTimeline.getState(EventTimeline.FORWARDS).events; - var events = []; - for (var evtype in evMap) { - if (!evMap.hasOwnProperty(evtype)) { continue; } - for (var stateKey in evMap[evtype]) { - if (!evMap[evtype].hasOwnProperty(stateKey)) { continue; } + let evMap = this._liveTimeline.getState(EventTimeline.FORWARDS).events; + let events = []; + for (let evtype in evMap) { + if (!evMap.hasOwnProperty(evtype)) { + continue; +} + for (let stateKey in evMap[evtype]) { + if (!evMap[evtype].hasOwnProperty(stateKey)) { + continue; +} events.push(evMap[evtype][stateKey]); } } @@ -195,7 +198,7 @@ EventTimelineSet.prototype.resetLiveTimeline = function(backPaginationToken, flu * the given event, or null if unknown */ EventTimelineSet.prototype.getTimelineForEvent = function(eventId) { - var res = this._eventIdToTimeline[eventId]; + let res = this._eventIdToTimeline[eventId]; return (res === undefined) ? null : res; }; @@ -206,12 +209,14 @@ EventTimelineSet.prototype.getTimelineForEvent = function(eventId) { * @return {?module:models/event~MatrixEvent} the given event, or undefined if unknown */ EventTimelineSet.prototype.findEventById = function(eventId) { - var tl = this.getTimelineForEvent(eventId); + let tl = this.getTimelineForEvent(eventId); if (!tl) { return undefined; } return utils.findElement(tl.getEvents(), - function(ev) { return ev.getId() == eventId; }); + function(ev) { + return ev.getId() == eventId; +}); }; /** @@ -226,7 +231,7 @@ EventTimelineSet.prototype.addTimeline = function() { " it."); } - var timeline = new EventTimeline(this); + let timeline = new EventTimeline(this); this._timelines.push(timeline); return timeline; }; @@ -273,9 +278,9 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel } } - var direction = toStartOfTimeline ? EventTimeline.BACKWARDS : + let direction = toStartOfTimeline ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS; - var inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS : + let inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS : EventTimeline.BACKWARDS; // Adding events to timelines can be quite complicated. The following @@ -347,13 +352,13 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel // paginating with the same token, we might as well use the new pagination // token in the hope that we eventually work our way out of the mess. - var didUpdate = false; - var lastEventWasNew = false; - for (var i = 0; i < events.length; i++) { - var event = events[i]; - var eventId = event.getId(); + let didUpdate = false; + let lastEventWasNew = false; + for (let i = 0; i < events.length; i++) { + let event = events[i]; + let eventId = event.getId(); - var existingTimeline = this._eventIdToTimeline[eventId]; + let existingTimeline = this._eventIdToTimeline[eventId]; if (!existingTimeline) { // we don't know about this event yet. Just add it to the timeline. @@ -370,7 +375,7 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel continue; } - var neighbour = timeline.getNeighbouringTimeline(direction); + let 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 @@ -418,19 +423,19 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel */ EventTimelineSet.prototype.addLiveEvent = function(event, duplicateStrategy) { if (this._filter) { - var events = this._filter.filterRoomTimeline([event]); + let events = this._filter.filterRoomTimeline([event]); if (!events.length) { return; } } - var timeline = this._eventIdToTimeline[event.getId()]; + let timeline = this._eventIdToTimeline[event.getId()]; if (timeline) { if (duplicateStrategy === "replace") { debuglog("EventTimelineSet.addLiveEvent: replacing duplicate event " + event.getId()); - var tlEvents = timeline.getEvents(); - for (var j = 0; j < tlEvents.length; j++) { + let 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 EventTimeline.setEventMetadata( @@ -471,11 +476,11 @@ EventTimelineSet.prototype.addLiveEvent = function(event, duplicateStrategy) { */ EventTimelineSet.prototype.addEventToTimeline = function(event, timeline, toStartOfTimeline) { - var eventId = event.getId(); + let eventId = event.getId(); timeline.addEvent(event, toStartOfTimeline); this._eventIdToTimeline[eventId] = timeline; - var data = { + let data = { timeline: timeline, liveEvent: !toStartOfTimeline && timeline == this._liveTimeline, }; @@ -496,7 +501,7 @@ EventTimelineSet.prototype.addEventToTimeline = function(event, timeline, EventTimelineSet.prototype.handleRemoteEcho = function(localEvent, oldEventId, newEventId) { // XXX: why don't we infer newEventId from localEvent? - var existingTimeline = this._eventIdToTimeline[oldEventId]; + let existingTimeline = this._eventIdToTimeline[oldEventId]; if (existingTimeline) { delete this._eventIdToTimeline[oldEventId]; this._eventIdToTimeline[newEventId] = existingTimeline; @@ -505,8 +510,7 @@ EventTimelineSet.prototype.handleRemoteEcho = function(localEvent, oldEventId, if (this._filter.filterRoomTimeline([localEvent]).length) { this.addEventToTimeline(localEvent, this._liveTimeline, false); } - } - else { + } else { this.addEventToTimeline(localEvent, this._liveTimeline, false); } } @@ -521,15 +525,15 @@ EventTimelineSet.prototype.handleRemoteEcho = function(localEvent, oldEventId, * in this room. */ EventTimelineSet.prototype.removeEvent = function(eventId) { - var timeline = this._eventIdToTimeline[eventId]; + let timeline = this._eventIdToTimeline[eventId]; if (!timeline) { return null; } - var removed = timeline.removeEvent(eventId); + let removed = timeline.removeEvent(eventId); if (removed) { delete this._eventIdToTimeline[eventId]; - var data = { + let data = { timeline: timeline, }; this.emit("Room.timeline", removed, this.room, undefined, true, data); @@ -555,8 +559,8 @@ EventTimelineSet.prototype.compareEventOrdering = function(eventId1, eventId2) { return 0; } - var timeline1 = this._eventIdToTimeline[eventId1]; - var timeline2 = this._eventIdToTimeline[eventId2]; + let timeline1 = this._eventIdToTimeline[eventId1]; + let timeline2 = this._eventIdToTimeline[eventId2]; if (timeline1 === undefined) { return null; @@ -568,11 +572,11 @@ EventTimelineSet.prototype.compareEventOrdering = function(eventId1, eventId2) { if (timeline1 === timeline2) { // both events are in the same timeline - figure out their // relative indices - var idx1, idx2; - var events = timeline1.getEvents(); - for (var idx = 0; idx < events.length && + let idx1, idx2; + let events = timeline1.getEvents(); + for (let idx = 0; idx < events.length && (idx1 === undefined || idx2 === undefined); idx++) { - var evId = events[idx].getId(); + let evId = events[idx].getId(); if (evId == eventId1) { idx1 = idx; } @@ -587,7 +591,7 @@ EventTimelineSet.prototype.compareEventOrdering = function(eventId1, eventId2) { // linkedlist to see which comes first. // first work forwards from timeline1 - var tl = timeline1; + let tl = timeline1; while (tl) { if (tl === timeline2) { // timeline1 is before timeline2 diff --git a/src/models/event-timeline.js b/src/models/event-timeline.js index 5c1545286..bcc943b46 100644 --- a/src/models/event-timeline.js +++ b/src/models/event-timeline.js @@ -4,9 +4,9 @@ * @module models/event-timeline */ -var RoomState = require("./room-state"); -var utils = require("../utils"); -var MatrixEvent = require("./event").MatrixEvent; +let RoomState = require("./room-state"); +let utils = require("../utils"); +let MatrixEvent = require("./event").MatrixEvent; /** * Construct a new EventTimeline @@ -75,10 +75,14 @@ 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. - var oldStateEvents = utils.map( + let oldStateEvents = utils.map( utils.deepCopy( - stateEvents.map(function(mxEvent) { return mxEvent.event; }) - ), function(ev) { return new MatrixEvent(ev); }); + stateEvents.map(function(mxEvent) { + return mxEvent.event; +}) + ), function(ev) { + return new MatrixEvent(ev); +}); this._startState.setStateEvents(oldStateEvents); this._endState.setStateEvents(stateEvents); @@ -232,13 +236,12 @@ EventTimeline.prototype.setNeighbouringTimeline = function(neighbour, direction) * @param {boolean} atStart true to insert new event at the start */ EventTimeline.prototype.addEvent = function(event, atStart) { - var stateContext = atStart ? this._startState : this._endState; + let stateContext = atStart ? this._startState : this._endState; // only call setEventMetadata on the unfiltered timelineSets - var timelineSet = this.getTimelineSet(); + let timelineSet = this.getTimelineSet(); if (timelineSet.room && - timelineSet.room.getUnfilteredTimelineSet() === timelineSet) - { + timelineSet.room.getUnfilteredTimelineSet() === timelineSet) { EventTimeline.setEventMetadata(event, stateContext, atStart); // modify state @@ -260,7 +263,7 @@ EventTimeline.prototype.addEvent = function(event, atStart) { } } - var insertIndex; + let insertIndex; if (atStart) { insertIndex = 0; @@ -309,8 +312,8 @@ EventTimeline.setEventMetadata = function(event, stateContext, toStartOfTimeline * @return {?MatrixEvent} removed event, or null if not found */ EventTimeline.prototype.removeEvent = function(eventId) { - for (var i = this._events.length - 1; i >= 0; i--) { - var ev = this._events[i]; + for (let i = this._events.length - 1; i >= 0; i--) { + let ev = this._events[i]; if (ev.getId() == eventId) { this._events.splice(i, 1); if (i < this._baseIndex) { diff --git a/src/models/event.js b/src/models/event.js index c49176544..03864f2c7 100644 --- a/src/models/event.js +++ b/src/models/event.js @@ -21,9 +21,9 @@ limitations under the License. * @module models/event */ -var EventEmitter = require("events").EventEmitter; +let EventEmitter = require("events").EventEmitter; -var utils = require('../utils.js'); +let utils = require('../utils.js'); /** * Enum for event statuses. @@ -340,18 +340,22 @@ utils.extend(module.exports.MatrixEvent.prototype, { } this.event.unsigned.redacted_because = redaction_event.event; - var key; + let key; for (key in this.event) { - if (!this.event.hasOwnProperty(key)) { continue; } + if (!this.event.hasOwnProperty(key)) { + continue; +} if (!_REDACT_KEEP_KEY_MAP[key]) { delete this.event[key]; } } - var keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {}; - var content = this.getContent(); + let keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {}; + let content = this.getContent(); for (key in content) { - if (!content.hasOwnProperty(key)) { continue; } + if (!content.hasOwnProperty(key)) { + continue; +} if (!keeps[key]) { delete content[key]; } @@ -394,7 +398,7 @@ utils.extend(module.exports.MatrixEvent.prototype, { // successfully sent. this.status = null; this._date = new Date(this.event.origin_server_ts); - } + }, }); @@ -420,13 +424,15 @@ utils.extend(module.exports.MatrixEvent.prototype, { * m.room.aliases allows key aliases */ // a map giving the keys we keep when an event is redacted -var _REDACT_KEEP_KEY_MAP = [ +let _REDACT_KEEP_KEY_MAP = [ 'event_id', 'type', 'room_id', 'user_id', 'state_key', 'prev_state', 'content', 'unsigned', -].reduce(function(ret, val) { ret[val] = 1; return ret; }, {}); +].reduce(function(ret, val) { + ret[val] = 1; return ret; +}, {}); // a map from event type to the .content keys we keep when an event is redacted -var _REDACT_KEEP_CONTENT_MAP = { +let _REDACT_KEEP_CONTENT_MAP = { 'm.room.member': {'membership': 1}, 'm.room.create': {'creator': 1}, 'm.room.join_rules': {'join_rule': 1}, diff --git a/src/models/room-member.js b/src/models/room-member.js index f04bce6fa..a1c80dcbd 100644 --- a/src/models/room-member.js +++ b/src/models/room-member.js @@ -17,10 +17,10 @@ limitations under the License. /** * @module models/room-member */ -var EventEmitter = require("events").EventEmitter; -var ContentRepo = require("../content-repo"); +let EventEmitter = require("events").EventEmitter; +let ContentRepo = require("../content-repo"); -var utils = require("../utils"); +let utils = require("../utils"); /** * Construct a new room member. @@ -52,7 +52,7 @@ function RoomMember(roomId, userId) { this.user = null; this.membership = null; this.events = { - member: null + member: null, }; this._updateModifiedTime(); } @@ -73,10 +73,10 @@ RoomMember.prototype.setMembershipEvent = function(event, roomState) { } this.events.member = event; - var oldMembership = this.membership; + let oldMembership = this.membership; this.membership = event.getDirectionalContent().membership; - var oldName = this.name; + let oldName = this.name; this.name = calculateDisplayName(this, event, roomState); if (oldMembership !== this.membership) { this._updateModifiedTime(); @@ -99,12 +99,12 @@ RoomMember.prototype.setPowerLevelEvent = function(powerLevelEvent) { if (powerLevelEvent.getType() !== "m.room.power_levels") { return; } - var maxLevel = powerLevelEvent.getContent().users_default || 0; + let maxLevel = powerLevelEvent.getContent().users_default || 0; utils.forEach(utils.values(powerLevelEvent.getContent().users), function(lvl) { maxLevel = Math.max(maxLevel, lvl); }); - var oldPowerLevel = this.powerLevel; - var oldPowerLevelNorm = this.powerLevelNorm; + let oldPowerLevel = this.powerLevel; + let 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; } - var oldTyping = this.typing; + let oldTyping = this.typing; this.typing = false; - var typingList = event.getContent().user_ids; + let typingList = event.getContent().user_ids; if (!utils.isArray(typingList)) { // malformed event :/ bail early. TODO: whine? return; @@ -189,18 +189,19 @@ RoomMember.prototype.getLastModifiedTime = function() { */ RoomMember.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod, allowDefault, allowDirectLinks) { - if (allowDefault === undefined) { allowDefault = true; } + if (allowDefault === undefined) { + allowDefault = true; +} if (!this.events.member && !allowDefault) { return null; } - var rawUrl = this.events.member ? this.events.member.getContent().avatar_url : null; - var httpUrl = ContentRepo.getHttpUriForMxc( + let rawUrl = this.events.member ? this.events.member.getContent().avatar_url : null; + let httpUrl = ContentRepo.getHttpUriForMxc( baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks ); if (httpUrl) { return httpUrl; - } - else if (allowDefault) { + } else if (allowDefault) { return ContentRepo.getIdenticonUri( baseUrl, this.userId, width, height ); @@ -209,8 +210,8 @@ RoomMember.prototype.getAvatarUrl = }; function calculateDisplayName(member, event, roomState) { - var displayName = event.getDirectionalContent().displayname; - var selfUserId = member.userId; + let displayName = event.getDirectionalContent().displayname; + let selfUserId = member.userId; if (!displayName) { return selfUserId; @@ -220,8 +221,8 @@ function calculateDisplayName(member, event, roomState) { return displayName; } - var userIds = roomState.getUserIdsWithDisplayName(displayName); - var otherUsers = userIds.filter(function(u) { + let userIds = roomState.getUserIdsWithDisplayName(displayName); + let otherUsers = userIds.filter(function(u) { return u !== selfUserId; }); if (otherUsers.length > 0) { diff --git a/src/models/room-state.js b/src/models/room-state.js index 799dbbe93..5fda628bc 100644 --- a/src/models/room-state.js +++ b/src/models/room-state.js @@ -17,10 +17,10 @@ limitations under the License. /** * @module models/room-state */ -var EventEmitter = require("events").EventEmitter; +let EventEmitter = require("events").EventEmitter; -var utils = require("../utils"); -var RoomMember = require("./room-member"); +let utils = require("../utils"); +let 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]); } - var event = this.events[eventType][stateKey]; + let event = this.events[eventType][stateKey]; return event ? event : null; }; @@ -115,13 +115,17 @@ RoomState.prototype.getStateEvents = function(eventType, stateKey) { * @fires module:client~MatrixClient#event:"RoomState.events" */ RoomState.prototype.setStateEvents = function(stateEvents) { - var self = this; + let self = this; this._updateModifiedTime(); // update the core event dict utils.forEach(stateEvents, function(event) { - if (event.getRoomId() !== self.roomId) { return; } - if (!event.isState()) { return; } + if (event.getRoomId() !== self.roomId) { + return; +} + if (!event.isState()) { + return; +} if (self.events[event.getType()] === undefined) { self.events[event.getType()] = {}; @@ -141,18 +145,21 @@ RoomState.prototype.setStateEvents = function(stateEvents) { // the given array (e.g. disambiguating display names in one go to do both // clashing names rather than progressively which only catches 1 of them). utils.forEach(stateEvents, function(event) { - if (event.getRoomId() !== self.roomId) { return; } - if (!event.isState()) { return; } + if (event.getRoomId() !== self.roomId) { + return; +} + if (!event.isState()) { + return; +} if (event.getType() === "m.room.member") { - var userId = event.getStateKey(); + let 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 // into the timeline if (event.getContent().membership === "leave" || - event.getContent().membership === "ban") - { + event.getContent().membership === "ban") { event.getContent().avatar_url = event.getContent().avatar_url || event.getPrevContent().avatar_url; @@ -161,7 +168,7 @@ RoomState.prototype.setStateEvents = function(stateEvents) { event.getPrevContent().displayname; } - var member = self.members[userId]; + let member = self.members[userId]; if (!member) { member = new RoomMember(event.getRoomId(), userId); self.emit("RoomState.newMember", event, self, member); @@ -171,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). - var sentinel = new RoomMember(event.getRoomId(), userId); + let 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. - var pwrLvlEvent = self.getStateEvents("m.room.power_levels", ""); + let pwrLvlEvent = self.getStateEvents("m.room.power_levels", ""); if (pwrLvlEvent) { roomMember.setPowerLevelEvent(pwrLvlEvent); } @@ -184,9 +191,8 @@ RoomState.prototype.setStateEvents = function(stateEvents) { self._sentinels[userId] = sentinel; self.members[userId] = member; self.emit("RoomState.members", event, self, member); - } - else if (event.getType() === "m.room.power_levels") { - var members = utils.values(self.members); + } else if (event.getType() === "m.room.power_levels") { + let members = utils.values(self.members); utils.forEach(members, function(member) { member.setPowerLevelEvent(event); self.emit("RoomState.members", event, self, member); @@ -306,16 +312,18 @@ RoomState.prototype.maySendStateEvent = function(stateEventType, userId) { * according to the room's state. */ RoomState.prototype._maySendEventOfType = function(eventType, userId, state) { - var member = this.getMember(userId); - if (!member || member.membership == 'leave') { return false; } + let member = this.getMember(userId); + if (!member || member.membership == 'leave') { + return false; +} - var power_levels_event = this.getStateEvents('m.room.power_levels', ''); + let power_levels_event = this.getStateEvents('m.room.power_levels', ''); - var power_levels; - var events_levels = {}; + let power_levels; + let events_levels = {}; - var state_default = 0; - var events_default = 0; + let state_default = 0; + let events_default = 0; if (power_levels_event) { power_levels = power_levels_event.getContent(); events_levels = power_levels.events || {}; @@ -330,7 +338,7 @@ RoomState.prototype._maySendEventOfType = function(eventType, userId, state) { } } - var required_level = state ? state_default : events_default; + let required_level = state ? state_default : events_default; if (events_levels[eventType] !== undefined) { required_level = events_levels[eventType]; } @@ -347,11 +355,11 @@ function _updateThirdPartyTokenCache(roomState, memberEvent) { if (!memberEvent.getContent().third_party_invite) { return; } - var token = (memberEvent.getContent().third_party_invite.signed || {}).token; + let token = (memberEvent.getContent().third_party_invite.signed || {}).token; if (!token) { return; } - var threePidInvite = roomState.getStateEvents( + let threePidInvite = roomState.getStateEvents( "m.room.third_party_invite", token ); if (!threePidInvite) { @@ -361,15 +369,15 @@ function _updateThirdPartyTokenCache(roomState, memberEvent) { } function _updateDisplayNameCache(roomState, userId, displayName) { - var oldName = roomState._userIdsToDisplayNames[userId]; + let 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. - var existingUserIds = roomState._displayNameToUserIds[oldName] || []; - for (var i = 0; i < existingUserIds.length; i++) { + let existingUserIds = roomState._displayNameToUserIds[oldName] || []; + for (let i = 0; i < existingUserIds.length; i++) { if (existingUserIds[i] === userId) { // remove this user ID from this array existingUserIds.splice(i, 1); diff --git a/src/models/room.js b/src/models/room.js index 4c84147a4..b3a526fc2 100644 --- a/src/models/room.js +++ b/src/models/room.js @@ -17,30 +17,30 @@ limitations under the License. /** * @module models/room */ -var EventEmitter = require("events").EventEmitter; +let EventEmitter = require("events").EventEmitter; -var EventStatus = require("./event").EventStatus; -var RoomSummary = require("./room-summary"); -var MatrixEvent = require("./event").MatrixEvent; -var utils = require("../utils"); -var ContentRepo = require("../content-repo"); -var EventTimeline = require("./event-timeline"); -var EventTimelineSet = require("./event-timeline-set"); +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"); 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 - var fakeReceipt = { + let fakeReceipt = { content: {}, type: "m.receipt", - room_id: event.getRoomId() + room_id: event.getRoomId(), }; fakeReceipt.content[event.getId()] = {}; fakeReceipt.content[event.getId()][receiptType] = {}; fakeReceipt.content[event.getId()][receiptType][userId] = { - ts: event.getTs() + ts: event.getTs(), }; return new MatrixEvent(fakeReceipt); } @@ -204,7 +204,7 @@ Room.prototype.getLiveTimeline = function() { * @param {string=} backPaginationToken token for back-paginating the new timeline */ Room.prototype.resetLiveTimeline = function(backPaginationToken) { - for (var i = 0; i < this._timelineSets.length; i++) { + for (let i = 0; i < this._timelineSets.length; i++) { this._timelineSets[i].resetLiveTimeline(backPaginationToken); } @@ -308,19 +308,20 @@ Room.prototype.setUnreadNotificationCount = function(type, count) { */ Room.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod, allowDefault) { - var roomAvatarEvent = this.currentState.getStateEvents("m.room.avatar", ""); - if (allowDefault === undefined) { allowDefault = true; } + let roomAvatarEvent = this.currentState.getStateEvents("m.room.avatar", ""); + if (allowDefault === undefined) { + allowDefault = true; +} if (!roomAvatarEvent && !allowDefault) { return null; } - var mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null; + let mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null; if (mainUrl) { return ContentRepo.getHttpUriForMxc( baseUrl, mainUrl, width, height, resizeMethod ); - } - else if (allowDefault) { + } else if (allowDefault) { return ContentRepo.getIdenticonUri( baseUrl, this.roomId, width, height ); @@ -336,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() { - var alias_strings = []; + let alias_strings = []; - var alias_events = this.currentState.getStateEvents("m.room.aliases"); + let alias_events = this.currentState.getStateEvents("m.room.aliases"); if (alias_events) { - for (var i = 0; i < alias_events.length; ++i) { - var alias_event = alias_events[i]; + for (let i = 0; i < alias_events.length; ++i) { + let alias_event = alias_events[i]; if (utils.isArray(alias_event.getContent().aliases)) { Array.prototype.push.apply( alias_strings, alias_event.getContent().aliases @@ -359,7 +360,7 @@ Room.prototype.getAliases = function() { * @return {?string} The room's canonical alias, or null if there is none */ Room.prototype.getCanonicalAlias = function() { - var canonicalAlias = this.currentState.getStateEvents("m.room.canonical_alias", ""); + let canonicalAlias = this.currentState.getStateEvents("m.room.canonical_alias", ""); if (canonicalAlias) { return canonicalAlias.getContent().alias; } @@ -399,7 +400,7 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline, * @return {RoomMember} The member or null. */ Room.prototype.getMember = function(userId) { - var member = this.currentState.members[userId]; + let member = this.currentState.members[userId]; if (!member) { return null; } @@ -444,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) { - var member = this.getMember(userId); + let member = this.getMember(userId); if (!member) { return false; } @@ -460,8 +461,8 @@ Room.prototype.getOrCreateFilteredTimelineSet = function(filter) { if (this._filteredTimelineSets[filter.filterId]) { return this._filteredTimelineSets[filter.filterId]; } - var opts = Object.assign({ filter: filter }, this._opts); - var timelineSet = new EventTimelineSet(this, opts); + let opts = Object.assign({ filter: filter }, this._opts); + let timelineSet = new EventTimelineSet(this, opts); reEmit(this, timelineSet, ["Room.timeline", "Room.timelineReset"]); this._filteredTimelineSets[filter.filterId] = timelineSet; this._timelineSets.push(timelineSet); @@ -473,14 +474,14 @@ 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 - var unfilteredLiveTimeline = this.getLiveTimeline(); + let unfilteredLiveTimeline = this.getLiveTimeline(); unfilteredLiveTimeline.getEvents().forEach(function(event) { timelineSet.addLiveEvent(event); }); // find the earliest unfiltered timeline - var timeline = unfilteredLiveTimeline; + let timeline = unfilteredLiveTimeline; while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) { timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS); } @@ -507,9 +508,9 @@ Room.prototype.getOrCreateFilteredTimelineSet = function(filter) { * @param {Filter} filter the filter whose timelineSet is to be forgotten */ Room.prototype.removeFilteredTimelineSet = function(filter) { - var timelineSet = this._filteredTimelineSets[filter.filterId]; + let timelineSet = this._filteredTimelineSets[filter.filterId]; delete this._filteredTimelineSets[filter.filterId]; - var i = this._timelineSets.indexOf(timelineSet); + let i = this._timelineSets.indexOf(timelineSet); if (i > -1) { this._timelineSets.splice(i, 1); } @@ -525,12 +526,12 @@ Room.prototype.removeFilteredTimelineSet = function(filter) { * @private */ Room.prototype._addLiveEvent = function(event, duplicateStrategy) { - var i; + let i; if (event.getType() === "m.room.redaction") { - var redactId = event.event.redacts; + let redactId = event.event.redacts; // if we know about this event, redact its contents now. - var redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId); + let redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId); if (redactedEvent) { redactedEvent.makeRedacted(event); this.emit("Room.redaction", event, this); @@ -550,7 +551,7 @@ Room.prototype._addLiveEvent = function(event, duplicateStrategy) { } if (event.getUnsigned().transaction_id) { - var existingEvent = this._txnToEvent[event.getUnsigned().transaction_id]; + let existingEvent = this._txnToEvent[event.getUnsigned().transaction_id]; if (existingEvent) { // remote echo of an event we sent earlier this._handleRemoteEcho(event, existingEvent); @@ -623,15 +624,14 @@ Room.prototype.addPendingEvent = function(event, txnId) { if (this._opts.pendingEventOrdering == "detached") { this._pendingEventList.push(event); } else { - for (var i = 0; i < this._timelineSets.length; i++) { - var timelineSet = this._timelineSets[i]; + for (let i = 0; i < this._timelineSets.length; i++) { + let timelineSet = this._timelineSets[i]; if (timelineSet.getFilter()) { if (this._filter.filterRoomTimeline([event]).length) { timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), false); } - } - else { + } else { timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), false); } @@ -656,9 +656,9 @@ Room.prototype.addPendingEvent = function(event, txnId) { * @private */ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) { - var oldEventId = localEvent.getId(); - var newEventId = remoteEvent.getId(); - var oldStatus = localEvent.status; + let oldEventId = localEvent.getId(); + let newEventId = remoteEvent.getId(); + let oldStatus = localEvent.status; // no longer pending delete this._txnToEvent[remoteEvent.transaction_id]; @@ -667,7 +667,9 @@ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) { if (this._pendingEventList) { utils.removeElement( this._pendingEventList, - function(ev) { return ev.getId() == oldEventId; }, + function(ev) { + return ev.getId() == oldEventId; +}, false ); } @@ -676,8 +678,8 @@ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) { // any, which is good, because we don't want to try decoding it again). localEvent.handleRemoteEcho(remoteEvent.event); - for (var i = 0; i < this._timelineSets.length; i++) { - var timelineSet = this._timelineSets[i]; + for (let i = 0; i < this._timelineSets.length; i++) { + let 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); @@ -689,7 +691,7 @@ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) { /* a map from current event status to a list of allowed next statuses */ -var ALLOWED_TRANSITIONS = {}; +let ALLOWED_TRANSITIONS = {}; ALLOWED_TRANSITIONS[EventStatus.ENCRYPTING] = [ EventStatus.SENDING, @@ -736,7 +738,7 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) { // SENT races against /sync, so we have to special-case it. if (newStatus == EventStatus.SENT) { - var timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId); + let timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId); if (timeline) { // we've already received the event via the event stream. // nothing more to do here. @@ -744,15 +746,15 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) { } } - var oldStatus = event.status; - var oldEventId = event.getId(); + let oldStatus = event.status; + let oldEventId = event.getId(); if (!oldStatus) { throw new Error("updatePendingEventStatus called on an event which is " + "not a local echo."); } - var allowed = ALLOWED_TRANSITIONS[oldStatus]; + let allowed = ALLOWED_TRANSITIONS[oldStatus]; if (!allowed || allowed.indexOf(newStatus) < 0) { throw new Error("Invalid EventStatus transition " + oldStatus + "->" + newStatus); @@ -767,16 +769,17 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) { // if the event was already in the timeline (which will be the case if // opts.pendingEventOrdering==chronological), we need to update the // timeline map. - for (var i = 0; i < this._timelineSets.length; i++) { + for (let i = 0; i < this._timelineSets.length; i++) { this._timelineSets[i].replaceEventId(oldEventId, newEventId); } - } - else if (newStatus == EventStatus.CANCELLED) { + } else if (newStatus == EventStatus.CANCELLED) { // remove it from the pending event list, or the timeline. if (this._pendingEventList) { utils.removeElement( this._pendingEventList, - function(ev) { return ev.getId() == oldEventId; }, + function(ev) { + return ev.getId() == oldEventId; +}, false ); } @@ -804,14 +807,14 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) { * @throws If duplicateStrategy is not falsey, 'replace' or 'ignore'. */ Room.prototype.addLiveEvents = function(events, duplicateStrategy) { - var i; + let i; if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) { throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'"); } // sanity check that the live timeline is still live for (i = 0; i < this._timelineSets.length; i++) { - var liveTimeline = this._timelineSets[i].getLiveTimeline(); + let 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 " + @@ -829,8 +832,7 @@ Room.prototype.addLiveEvents = function(events, duplicateStrategy) { for (i = 0; i < events.length; i++) { if (events[i].getType() === "m.typing") { this.currentState.setTypingEvent(events[i]); - } - else if (events[i].getType() === "m.receipt") { + } else if (events[i].getType() === "m.receipt") { this.addReceipt(events[i]); } // N.B. account_data is added directly by /sync to avoid @@ -848,7 +850,7 @@ Room.prototype.addLiveEvents = function(events, duplicateStrategy) { * @param {String[]} event_ids A list of event_ids to remove. */ Room.prototype.removeEvents = function(event_ids) { - for (var i = 0; i < event_ids.length; ++i) { + for (let i = 0; i < event_ids.length; ++i) { this.removeEvent(event_ids[i]); } }; @@ -861,9 +863,9 @@ Room.prototype.removeEvents = function(event_ids) { * @return {bool} true if the event was removed from any of the room's timeline sets */ Room.prototype.removeEvent = function(eventId) { - var removedAny = false; - for (var i = 0; i < this._timelineSets.length; i++) { - var removed = this._timelineSets[i].removeEvent(eventId); + let removedAny = false; + for (let i = 0; i < this._timelineSets.length; i++) { + let removed = this._timelineSets[i].removeEvent(eventId); if (removed) { removedAny = true; } @@ -882,14 +884,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. - var self = this; - var membershipEvent = this.currentState.getStateEvents( + let self = this; + let membershipEvent = this.currentState.getStateEvents( "m.room.member", userId ); if (membershipEvent && membershipEvent.getContent().membership === "invite") { - var strippedStateEvents = membershipEvent.event.invite_room_state || []; + let strippedStateEvents = membershipEvent.event.invite_room_state || []; utils.forEach(strippedStateEvents, function(strippedEvent) { - var existingEvent = self.currentState.getStateEvents( + let existingEvent = self.currentState.getStateEvents( strippedEvent.type, strippedEvent.state_key ); if (!existingEvent) { @@ -900,16 +902,16 @@ Room.prototype.recalculate = function(userId) { content: strippedEvent.content, event_id: "$fake" + Date.now(), room_id: self.roomId, - user_id: userId // technically a lie + user_id: userId, // technically a lie })]); } }); } - var oldName = this.name; + let oldName = this.name; this.name = calculateRoomName(this, userId); this.summary = new RoomSummary(this.roomId, { - title: this.name + title: this.name, }); if (oldName !== this.name) { @@ -941,7 +943,7 @@ Room.prototype.getUsersReadUpTo = function(event) { * @return {String} ID of the latest event that the given user has read, or null. */ Room.prototype.getEventReadUpTo = function(userId, ignoreSynthesized) { - var receipts = this._receipts; + let receipts = this._receipts; if (ignoreSynthesized) { receipts = this._realReceipts; } @@ -982,7 +984,9 @@ Room.prototype.addReceipt = function(event, fake) { // } // } // } - if (fake === undefined) { fake = false; } + if (fake === undefined) { + fake = false; +} if (!fake) { this._addReceiptsToStructure(event, this._realReceipts); // we don't bother caching real receipts by event ID @@ -1002,18 +1006,18 @@ Room.prototype.addReceipt = function(event, fake) { * @param {Object} receipts The object to add receipts to */ Room.prototype._addReceiptsToStructure = function(event, receipts) { - var self = this; + let 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) { - var receipt = event.getContent()[eventId][receiptType][userId]; + let receipt = event.getContent()[eventId][receiptType][userId]; if (!receipts[receiptType]) { receipts[receiptType] = {}; } - var existingReceipt = receipts[receiptType][userId]; + let existingReceipt = receipts[receiptType][userId]; if (!existingReceipt) { receipts[receiptType][userId] = {}; @@ -1022,7 +1026,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.) - var ordering = self.getUnfilteredTimelineSet().compareEventOrdering( + let ordering = self.getUnfilteredTimelineSet().compareEventOrdering( existingReceipt.eventId, eventId); if (ordering !== null && ordering >= 0) { return; @@ -1031,7 +1035,7 @@ Room.prototype._addReceiptsToStructure = function(event, receipts) { receipts[receiptType][userId] = { eventId: eventId, - data: receipt + data: receipt, }; }); }); @@ -1044,17 +1048,17 @@ Room.prototype._addReceiptsToStructure = function(event, receipts) { * @return {Object} Map of receipts by event ID */ Room.prototype._buildReceiptCache = function(receipts) { - var receiptCacheByEventId = {}; + let receiptCacheByEventId = {}; utils.keys(receipts).forEach(function(receiptType) { utils.keys(receipts[receiptType]).forEach(function(userId) { - var receipt = receipts[receiptType][userId]; + let receipt = receipts[receiptType][userId]; if (!receiptCacheByEventId[receipt.eventId]) { receiptCacheByEventId[receipt.eventId] = []; } receiptCacheByEventId[receipt.eventId].push({ userId: userId, type: receiptType, - data: receipt.data + data: receipt.data, }); }); }); @@ -1099,8 +1103,8 @@ Room.prototype.addTags = function(event) { * @param {Array} events an array of account_data events to add */ Room.prototype.addAccountData = function(events) { - for (var i = 0; i < events.length; i++) { - var event = events[i]; + for (let i = 0; i < events.length; i++) { + let event = events[i]; if (event.getType() === "m.tag") { this.addTags(event); } @@ -1132,16 +1136,16 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) { if (!ignoreRoomNameEvent) { // check for an alias, if any. for now, assume first alias is the // official one. - var mRoomName = room.currentState.getStateEvents("m.room.name", ""); + let mRoomName = room.currentState.getStateEvents("m.room.name", ""); if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) { return mRoomName.getContent().name; } } - var alias = room.getCanonicalAlias(); + let alias = room.getCanonicalAlias(); if (!alias) { - var aliases = room.getAliases(); + let aliases = room.getAliases(); if (aliases.length) { alias = aliases[0]; @@ -1152,16 +1156,16 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) { } // get members that are NOT ourselves and are actually in the room. - var otherMembers = utils.filter(room.currentState.getMembers(), function(m) { + let otherMembers = utils.filter(room.currentState.getMembers(), function(m) { return (m.userId !== userId && m.membership !== "leave"); }); - var allMembers = utils.filter(room.currentState.getMembers(), function(m) { + let allMembers = utils.filter(room.currentState.getMembers(), function(m) { return (m.membership !== "leave"); }); - var myMemberEventArray = utils.filter(room.currentState.getMembers(), function(m) { + let myMemberEventArray = utils.filter(room.currentState.getMembers(), function(m) { return (m.userId == userId); }); - var myMemberEvent = ( + let myMemberEvent = ( (myMemberEventArray.length && myMemberEventArray[0].events) ? myMemberEventArray[0].events.member.event : undefined ); @@ -1188,45 +1192,38 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) { // self-chat, peeked room with 1 participant, // or inbound invite, or outbound 3PID invite. if (allMembers[0].userId === userId) { - var thirdPartyInvites = + let thirdPartyInvites = room.currentState.getStateEvents("m.room.third_party_invite"); if (thirdPartyInvites && thirdPartyInvites.length > 0) { - var name = "Inviting " + + let name = "Inviting " + thirdPartyInvites[0].getContent().display_name; if (thirdPartyInvites.length > 1) { if (thirdPartyInvites.length == 2) { name += " and " + thirdPartyInvites[1].getContent().display_name; - } - else { + } else { name += " and " + thirdPartyInvites.length + " others"; } } return name; - } - else { + } else { return "Empty room"; } - } - else { + } else { return allMembers[0].name; } - } - else { + } else { // there really isn't anyone in this room... return "Empty room"; } - } - else if (otherMembers.length === 1) { + } else if (otherMembers.length === 1) { return otherMembers[0].name; - } - else if (otherMembers.length === 2) { + } else if (otherMembers.length === 2) { return ( otherMembers[0].name + " and " + otherMembers[1].name ); - } - else { + } else { return ( otherMembers[0].name + " and " + (otherMembers.length - 1) + " others" ); @@ -1243,11 +1240,11 @@ function reEmit(reEmitEntity, emittableEntity, eventNames) { // Transformation Example: // listener on "foo" => function(a,b) { ... } // Re-emit on "thing" => thing.emit("foo", a, b) - var newArgs = [eventName]; - for (var i = 0; i < arguments.length; i++) { + let newArgs = [eventName]; + for (let i = 0; i < arguments.length; i++) { newArgs.push(arguments[i]); } - reEmitEntity.emit.apply(reEmitEntity, newArgs); + reEmitEntity.emit(...newArgs); }); }); } diff --git a/src/models/search-result.js b/src/models/search-result.js index 4e5ad143e..3c36cc8d9 100644 --- a/src/models/search-result.js +++ b/src/models/search-result.js @@ -19,8 +19,8 @@ limitations under the License. * @module models/search-result */ -var EventContext = require("./event-context"); -var utils = require("../utils"); +let EventContext = require("./event-context"); +let utils = require("../utils"); /** * Construct a new SearchResult @@ -45,11 +45,11 @@ function SearchResult(rank, eventContext) { */ SearchResult.fromJson = function(jsonObj, eventMapper) { - var jsonContext = jsonObj.context || {}; - var events_before = jsonContext.events_before || []; - var events_after = jsonContext.events_after || []; + let jsonContext = jsonObj.context || {}; + let events_before = jsonContext.events_before || []; + let events_after = jsonContext.events_after || []; - var context = new EventContext(eventMapper(jsonObj.result)); + let context = new EventContext(eventMapper(jsonObj.result)); context.setPaginateToken(jsonContext.start, true); context.addEvents(utils.map(events_before, eventMapper), true); diff --git a/src/models/user.js b/src/models/user.js index 1c4f1b70e..f89404503 100644 --- a/src/models/user.js +++ b/src/models/user.js @@ -17,8 +17,8 @@ limitations under the License. /** * @module models/user */ - var EventEmitter = require("events").EventEmitter; - var utils = require("../utils"); + let EventEmitter = require("events").EventEmitter; + let utils = require("../utils"); /** * Construct a new User. A User must have an ID and can optionally have extra @@ -54,7 +54,7 @@ function User(userId) { this.currentlyActive = false; this.events = { presence: null, - profile: null + profile: null, }; this._updateModifiedTime(); } @@ -73,26 +73,23 @@ User.prototype.setPresenceEvent = function(event) { if (event.getType() !== "m.presence") { return; } - var firstFire = this.events.presence === null; + let firstFire = this.events.presence === null; this.events.presence = event; - var eventsToFire = []; + let eventsToFire = []; if (event.getContent().presence !== this.presence || firstFire) { eventsToFire.push("User.presence"); } if (event.getContent().avatar_url && - event.getContent().avatar_url !== this.avatarUrl) - { + event.getContent().avatar_url !== this.avatarUrl) { eventsToFire.push("User.avatarUrl"); } if (event.getContent().displayname && - event.getContent().displayname !== this.displayName) - { + event.getContent().displayname !== this.displayName) { eventsToFire.push("User.displayName"); } if (event.getContent().currently_active !== undefined && - event.getContent().currently_active !== this.currentlyActive) - { + event.getContent().currently_active !== this.currentlyActive) { eventsToFire.push("User.currentlyActive"); } @@ -114,7 +111,7 @@ User.prototype.setPresenceEvent = function(event) { this._updateModifiedTime(); - for (var i = 0; i < eventsToFire.length; i++) { + for (let i = 0; i < eventsToFire.length; i++) { this.emit(eventsToFire[i], event, this); } }; @@ -125,7 +122,7 @@ User.prototype.setPresenceEvent = function(event) { * @param {string} name The new display name. */ User.prototype.setDisplayName = function(name) { - var oldName = this.displayName; + let oldName = this.displayName; this.displayName = name; if (name !== oldName) { this._updateModifiedTime(); @@ -149,7 +146,7 @@ User.prototype.setRawDisplayName = function(name) { * @param {string} url The new avatar URL. */ User.prototype.setAvatarUrl = function(url) { - var oldUrl = this.avatarUrl; + let oldUrl = this.avatarUrl; this.avatarUrl = url; if (url !== oldUrl) { this._updateModifiedTime(); diff --git a/src/pushprocessor.js b/src/pushprocessor.js index 0580286f2..8afd53ac2 100644 --- a/src/pushprocessor.js +++ b/src/pushprocessor.js @@ -23,24 +23,28 @@ limitations under the License. * @param {Object} client The Matrix client object to use */ function PushProcessor(client) { - var escapeRegExp = function(string) { + let escapeRegExp = function(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }; - var matchingRuleFromKindSet = function(ev, kindset, device) { - var rulekinds_in_order = ['override', 'content', 'room', 'sender', 'underride']; - for (var ruleKindIndex = 0; + let matchingRuleFromKindSet = function(ev, kindset, device) { + let rulekinds_in_order = ['override', 'content', 'room', 'sender', 'underride']; + for (let ruleKindIndex = 0; ruleKindIndex < rulekinds_in_order.length; ++ruleKindIndex) { - var kind = rulekinds_in_order[ruleKindIndex]; - var ruleset = kindset[kind]; + let kind = rulekinds_in_order[ruleKindIndex]; + let ruleset = kindset[kind]; - for (var ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) { - var rule = ruleset[ruleIndex]; - if (!rule.enabled) { continue; } + for (let ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) { + let rule = ruleset[ruleIndex]; + if (!rule.enabled) { + continue; +} - var rawrule = templateRuleToRaw(kind, rule, device); - if (!rawrule) { continue; } + let rawrule = templateRuleToRaw(kind, rule, device); + if (!rawrule) { + continue; +} if (ruleMatchesEvent(rawrule, ev)) { rule.kind = kind; @@ -51,11 +55,11 @@ function PushProcessor(client) { return null; }; - var templateRuleToRaw = function(kind, tprule, device) { - var rawrule = { + let templateRuleToRaw = function(kind, tprule, device) { + let rawrule = { 'rule_id': tprule.rule_id, 'actions': tprule.actions, - 'conditions': [] + 'conditions': [], }; switch (kind) { case 'underride': @@ -63,55 +67,61 @@ function PushProcessor(client) { rawrule.conditions = tprule.conditions; break; case 'room': - if (!tprule.rule_id) { return null; } + if (!tprule.rule_id) { + return null; +} rawrule.conditions.push({ 'kind': 'event_match', 'key': 'room_id', - 'pattern': tprule.rule_id + 'pattern': tprule.rule_id, }); break; case 'sender': - if (!tprule.rule_id) { return null; } + if (!tprule.rule_id) { + return null; +} rawrule.conditions.push({ 'kind': 'event_match', 'key': 'user_id', - 'pattern': tprule.rule_id + 'pattern': tprule.rule_id, }); break; case 'content': - if (!tprule.pattern) { return null; } + if (!tprule.pattern) { + return null; +} rawrule.conditions.push({ 'kind': 'event_match', 'key': 'content.body', - 'pattern': tprule.pattern + 'pattern': tprule.pattern, }); break; } if (device) { rawrule.conditions.push({ 'kind': 'device', - 'profile_tag': device + 'profile_tag': device, }); } return rawrule; }; - var ruleMatchesEvent = function(rule, ev) { - var ret = true; - for (var i = 0; i < rule.conditions.length; ++i) { - var cond = rule.conditions[i]; + let ruleMatchesEvent = function(rule, ev) { + let ret = true; + for (let i = 0; i < rule.conditions.length; ++i) { + let cond = rule.conditions[i]; ret &= eventFulfillsCondition(cond, ev); } //console.log("Rule "+rule.rule_id+(ret ? " matches" : " doesn't match")); return ret; }; - var eventFulfillsCondition = function(cond, ev) { - var condition_functions = { + let eventFulfillsCondition = function(cond, ev) { + let condition_functions = { "event_match": eventFulfillsEventMatchCondition, "device": eventFulfillsDeviceCondition, "contains_display_name": eventFulfillsDisplayNameCondition, - "room_member_count": eventFulfillsRoomMemberCountCondition + "room_member_count": eventFulfillsRoomMemberCountCondition, }; if (condition_functions[cond.kind]) { return condition_functions[cond.kind](cond, ev); @@ -119,21 +129,29 @@ function PushProcessor(client) { return true; }; - var eventFulfillsRoomMemberCountCondition = function(cond, ev) { - if (!cond.is) { return false; } + let eventFulfillsRoomMemberCountCondition = function(cond, ev) { + if (!cond.is) { + return false; +} - var room = client.getRoom(ev.getRoomId()); - if (!room || !room.currentState || !room.currentState.members) { return false; } + let room = client.getRoom(ev.getRoomId()); + if (!room || !room.currentState || !room.currentState.members) { + return false; +} - var memberCount = Object.keys(room.currentState.members).filter(function(m) { + let memberCount = Object.keys(room.currentState.members).filter(function(m) { return room.currentState.members[m].membership == 'join'; }).length; - var m = cond.is.match(/^([=<>]*)([0-9]*)$/); - if (!m) { return false; } - var ineq = m[1]; - var rhs = parseInt(m[2]); - if (isNaN(rhs)) { return false; } + let m = cond.is.match(/^([=<>]*)([0-9]*)$/); + if (!m) { + return false; +} + let ineq = m[1]; + let rhs = parseInt(m[2]); + if (isNaN(rhs)) { + return false; +} switch (ineq) { case '': case '==': @@ -151,64 +169,68 @@ function PushProcessor(client) { } }; - var eventFulfillsDisplayNameCondition = function(cond, ev) { - var content = ev.getContent(); + let eventFulfillsDisplayNameCondition = function(cond, ev) { + let content = ev.getContent(); if (!content || !content.body || typeof content.body != 'string') { return false; } - var room = client.getRoom(ev.getRoomId()); + let room = client.getRoom(ev.getRoomId()); if (!room || !room.currentState || !room.currentState.members || - !room.currentState.getMember(client.credentials.userId)) { return false; } + !room.currentState.getMember(client.credentials.userId)) { + return false; +} - var displayName = room.currentState.getMember(client.credentials.userId).name; + let 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_]. - var pat = new RegExp("(^|\\W)" + escapeRegExp(displayName) + "(\\W|$)", 'i'); + let pat = new RegExp("(^|\\W)" + escapeRegExp(displayName) + "(\\W|$)", 'i'); return content.body.search(pat) > -1; }; - var eventFulfillsDeviceCondition = function(cond, ev) { + let eventFulfillsDeviceCondition = function(cond, ev) { return false; // XXX: Allow a profile tag to be set for the web client instance }; - var eventFulfillsEventMatchCondition = function(cond, ev) { - var val = valueForDottedKey(cond.key, ev); - if (!val || typeof val != 'string') { return false; } + let eventFulfillsEventMatchCondition = function(cond, ev) { + let val = valueForDottedKey(cond.key, ev); + if (!val || typeof val != 'string') { + return false; +} - var pat; + let pat; if (cond.key == 'content.body') { pat = '(^|\\W)' + globToRegexp(cond.pattern) + '(\\W|$)'; } else { pat = '^' + globToRegexp(cond.pattern) + '$'; } - var regex = new RegExp(pat, 'i'); + let regex = new RegExp(pat, 'i'); return !!val.match(regex); }; - var globToRegexp = function(glob) { + let globToRegexp = function(glob) { // From // https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132 // Because micromatch is about 130KB with dependencies, // and minimatch is not much better. - var pat = escapeRegExp(glob); + let pat = escapeRegExp(glob); pat = pat.replace(/\\\*/, '.*'); pat = pat.replace(/\?/, '.'); pat = pat.replace(/\\\[(!|)(.*)\\]/, function(match, p1, p2, offset, string) { - var first = p1 && '^' || ''; - var second = p2.replace(/\\\-/, '-'); + let first = p1 && '^' || ''; + let second = p2.replace(/\\\-/, '-'); return '[' + first + second + ']'; }); return pat; }; - var valueForDottedKey = function(key, ev) { - var parts = key.split('.'); - var val; + let valueForDottedKey = function(key, ev) { + let parts = key.split('.'); + let val; // special-case the first component to deal with encrypted messages - var firstPart = parts[0]; + let firstPart = parts[0]; if (firstPart == 'content') { val = ev.getContent(); parts.shift(); @@ -221,33 +243,43 @@ function PushProcessor(client) { } while (parts.length > 0) { - var thispart = parts.shift(); - if (!val[thispart]) { return null; } + let thispart = parts.shift(); + if (!val[thispart]) { + return null; +} val = val[thispart]; } return val; }; - var matchingRuleForEventWithRulesets = function(ev, rulesets) { - if (!rulesets || !rulesets.device) { return null; } - if (ev.getSender() == client.credentials.userId) { return null; } + let matchingRuleForEventWithRulesets = function(ev, rulesets) { + if (!rulesets || !rulesets.device) { + return null; +} + if (ev.getSender() == client.credentials.userId) { + return null; +} - var allDevNames = Object.keys(rulesets.device); - for (var i = 0; i < allDevNames.length; ++i) { - var devname = allDevNames[i]; - var devrules = rulesets.device[devname]; + let allDevNames = Object.keys(rulesets.device); + for (let i = 0; i < allDevNames.length; ++i) { + let devname = allDevNames[i]; + let devrules = rulesets.device[devname]; - var matchingRule = matchingRuleFromKindSet(devrules, devname); - if (matchingRule) { return matchingRule; } + let matchingRule = matchingRuleFromKindSet(devrules, devname); + if (matchingRule) { + return matchingRule; +} } return matchingRuleFromKindSet(ev, rulesets.global); }; - var pushActionsForEventAndRulesets = function(ev, rulesets) { - var rule = matchingRuleForEventWithRulesets(ev, rulesets); - if (!rule) { return {}; } + let pushActionsForEventAndRulesets = function(ev, rulesets) { + let rule = matchingRuleForEventWithRulesets(ev, rulesets); + if (!rule) { + return {}; +} - var actionObj = PushProcessor.actionListToActionsObject(rule.actions); + let actionObj = PushProcessor.actionListToActionsObject(rule.actions); // Some actions are implicit in some situations: we add those here if (actionObj.tweaks.highlight === undefined) { @@ -280,13 +312,15 @@ function PushProcessor(client) { * @return {object} A object with key 'notify' (true or false) and an object of actions */ PushProcessor.actionListToActionsObject = function(actionlist) { - var actionobj = { 'notify': false, 'tweaks': {} }; - for (var i = 0; i < actionlist.length; ++i) { - var action = actionlist[i]; + let actionobj = { 'notify': false, 'tweaks': {} }; + for (let i = 0; i < actionlist.length; ++i) { + let action = actionlist[i]; if (action === 'notify') { actionobj.notify = true; } else if (typeof action === 'object') { - if (action.value === undefined) { action.value = true; } + if (action.value === undefined) { + action.value = true; +} actionobj.tweaks[action.set_tweak] = action.value; } } diff --git a/src/realtime-callbacks.js b/src/realtime-callbacks.js index 9b5c6c0e8..63f75e155 100644 --- a/src/realtime-callbacks.js +++ b/src/realtime-callbacks.js @@ -27,20 +27,20 @@ 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. -var TIMER_CHECK_PERIOD_MS = 1000; +let TIMER_CHECK_PERIOD_MS = 1000; // counter, for making up ids to return from setTimeout -var _count = 0; +let _count = 0; // the key for our callback with the real global.setTimeout -var _realCallbackKey; +let _realCallbackKey; // a sorted list of the callbacks to be run. // each is an object with keys [runAt, func, params, key]. -var _callbackList = []; +let _callbackList = []; // var debuglog = console.log.bind(console); -var debuglog = function() {}; +let debuglog = function() {}; /** * Replace the function used by this module to get the current time. @@ -54,7 +54,7 @@ var debuglog = function() {}; module.exports.setNow = function(f) { _now = f || Date.now; }; -var _now = Date.now; +let _now = Date.now; /** * reimplementation of window.setTimeout, which will call the callback if @@ -72,12 +72,12 @@ module.exports.setTimeout = function(func, delayMs) { delayMs = 0; } - var params = Array.prototype.slice.call(arguments, 2); - var runAt = _now() + delayMs; - var key = _count++; + let params = Array.prototype.slice.call(arguments, 2); + let runAt = _now() + delayMs; + let key = _count++; debuglog("setTimeout: scheduling cb", key, "at", runAt, "(delay", delayMs, ")"); - var data = { + let 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 - var idx = binarySearch( + let idx = binarySearch( _callbackList, function(el) { return el.runAt - runAt; } @@ -108,9 +108,9 @@ module.exports.clearTimeout = function(key) { } // remove the element from the list - var i; + let i; for (i = 0; i < _callbackList.length; i++) { - var cb = _callbackList[i]; + let cb = _callbackList[i]; if (cb.key == key) { _callbackList.splice(i, 1); break; @@ -129,29 +129,29 @@ function _scheduleRealCallback() { global.clearTimeout(_realCallbackKey); } - var first = _callbackList[0]; + let first = _callbackList[0]; if (!first) { debuglog("_scheduleRealCallback: no more callbacks, not rescheduling"); return; } - var now = _now(); - var delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS); + let now = _now(); + let delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS); debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs); _realCallbackKey = global.setTimeout(_runCallbacks, delayMs); } function _runCallbacks() { - var cb; - var now = _now(); + let cb; + let now = _now(); debuglog("_runCallbacks: now:", now); // get the list of things to call - var callbacksToRun = []; + let callbacksToRun = []; while (true) { - var first = _callbackList[0]; + let first = _callbackList[0]; if (!first || first.runAt > now) { break; } @@ -165,7 +165,7 @@ function _runCallbacks() { // register their own setTimeouts. _scheduleRealCallback(); - for (var i = 0; i < callbacksToRun.length; i++) { + for (let i = 0; i < callbacksToRun.length; i++) { cb = callbacksToRun[i]; try { cb.func.apply(null, cb.params); @@ -184,12 +184,12 @@ function _runCallbacks() { */ function binarySearch(array, func) { // min is inclusive, max exclusive. - var min = 0, + let min = 0, max = array.length; while (min < max) { - var mid = (min + max) >> 1; - var res = func(array[mid]); + let mid = (min + max) >> 1; + let res = func(array[mid]); if (res > 0) { // the element at 'mid' is too big; set it as the new max. max = mid; diff --git a/src/scheduler.js b/src/scheduler.js index 2d46bae23..de77524bb 100644 --- a/src/scheduler.js +++ b/src/scheduler.js @@ -19,10 +19,10 @@ limitations under the License. * of requests. * @module scheduler */ -var utils = require("./utils"); -var q = require("q"); +let utils = require("./utils"); +let q = require("q"); -var DEBUG = false; // set true to enable console logging. +let 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) { - var name = this.queueAlgorithm(event); + let name = this.queueAlgorithm(event); if (!name || !this._queues[name]) { return null; } @@ -76,11 +76,11 @@ MatrixScheduler.prototype.getQueueForEvent = function(event) { * @return {boolean} True if this event was removed. */ MatrixScheduler.prototype.removeEventFromQueue = function(event) { - var name = this.queueAlgorithm(event); + let name = this.queueAlgorithm(event); if (!name || !this._queues[name]) { return false; } - var removed = false; + let removed = false; utils.removeElement(this._queues[name], function(element) { if (element.event.getId() === event.getId()) { removed = true; @@ -110,7 +110,7 @@ MatrixScheduler.prototype.setProcessFunction = function(fn) { * resolved or rejected in due time, else null. */ MatrixScheduler.prototype.queueEvent = function(event) { - var queueName = this.queueAlgorithm(event); + let queueName = this.queueAlgorithm(event); if (!queueName) { return null; } @@ -118,11 +118,11 @@ MatrixScheduler.prototype.queueEvent = function(event) { if (!this._queues[queueName]) { this._queues[queueName] = []; } - var defer = q.defer(); + let defer = q.defer(); this._queues[queueName].push({ event: event, defer: defer, - attempts: 0 + attempts: 0, }); debuglog( "Queue algorithm dumped event %s into queue '%s'", @@ -155,7 +155,7 @@ MatrixScheduler.RETRY_BACKOFF_RATELIMIT = function(event, attempts, err) { } if (err.name === "M_LIMIT_EXCEEDED") { - var waitTime = err.data.retry_after_ms; + let 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 - var obj = _peekNextEvent(scheduler, queueName); + let obj = _peekNextEvent(scheduler, queueName); if (!obj) { // queue is empty. Mark as inactive and stop recursing. - var index = scheduler._activeQueues.indexOf(queueName); + let 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 - var waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err); + let 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 @@ -241,8 +241,7 @@ function _processQueue(scheduler, queueName) { obj.defer.reject(err); // process next event _processQueue(scheduler, queueName); - } - else { + } else { setTimeout(function() { _processQueue(scheduler, queueName); }, waitTimeMs); @@ -251,7 +250,7 @@ function _processQueue(scheduler, queueName) { } function _peekNextEvent(scheduler, queueName) { - var queue = scheduler._queues[queueName]; + let queue = scheduler._queues[queueName]; if (!utils.isArray(queue)) { return null; } @@ -259,7 +258,7 @@ function _peekNextEvent(scheduler, queueName) { } function _removeNextEvent(scheduler, queueName) { - var queue = scheduler._queues[queueName]; + let queue = scheduler._queues[queueName]; if (!utils.isArray(queue)) { return null; } @@ -268,7 +267,7 @@ function _removeNextEvent(scheduler, queueName) { function debuglog() { if (DEBUG) { - console.log.apply(console, arguments); + console.log(...arguments); } } diff --git a/src/store/memory.js b/src/store/memory.js index 3c0386504..93b48e88a 100644 --- a/src/store/memory.js +++ b/src/store/memory.js @@ -18,8 +18,8 @@ limitations under the License. * This is an internal module. See {@link MatrixInMemoryStore} for the public class. * @module store/memory */ - var utils = require("../utils"); - var User = require("../models/user"); + let utils = require("../utils"); + let 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 - var self = this; + let self = this; room.currentState.getMembers().forEach(function(m) { self._onRoomMember(null, room.currentState, m); }); @@ -97,7 +97,7 @@ module.exports.MatrixInMemoryStore.prototype = { return; } - var user = this.users[member.userId] || new User(member.userId); + let user = this.users[member.userId] || new User(member.userId); if (member.name) { user.setDisplayName(member.name); if (member.events.member) { @@ -202,7 +202,9 @@ module.exports.MatrixInMemoryStore.prototype = { * @param {Filter} filter */ storeFilter: function(filter) { - if (!filter) { return; } + if (!filter) { + return; +} if (!this.filters[filter.userId]) { this.filters[filter.userId] = {}; } @@ -233,8 +235,7 @@ module.exports.MatrixInMemoryStore.prototype = { } try { return this.localStorage.getItem("mxjssdk_memory_filter_" + filterName); - } - catch (e) {} + } catch (e) {} return null; }, @@ -249,8 +250,7 @@ module.exports.MatrixInMemoryStore.prototype = { } try { this.localStorage.setItem("mxjssdk_memory_filter_" + filterName, filterId); - } - catch (e) {} + } catch (e) {} }, /** @@ -260,7 +260,7 @@ module.exports.MatrixInMemoryStore.prototype = { * @param {Array} events The events to store. */ storeAccountDataEvents: function(events) { - var self = this; + let self = this; events.forEach(function(event) { self.accountData[event.getType()] = event; }); diff --git a/src/store/session/webstorage.js b/src/store/session/webstorage.js index 9903f9f3c..155bb5652 100644 --- a/src/store/session/webstorage.js +++ b/src/store/session/webstorage.js @@ -19,10 +19,10 @@ limitations under the License. * @module store/session/webstorage */ -var utils = require("../../utils"); +let utils = require("../../utils"); -var DEBUG = false; // set true to enable console logging. -var E2E_PREFIX = "session.e2e."; +let DEBUG = false; // set true to enable console logging. +let E2E_PREFIX = "session.e2e."; /** * Construct a web storage session store, capable of storing account keys, @@ -103,7 +103,7 @@ WebStorageSessionStore.prototype = { * @param {string} session Base64 encoded end-to-end session. */ storeEndToEndSession: function(deviceKey, sessionId, session) { - var sessions = this.getEndToEndSessions(deviceKey) || {}; + let sessions = this.getEndToEndSessions(deviceKey) || {}; sessions[sessionId] = session; setJsonItem( this.store, keyEndToEndSessions(deviceKey), sessions @@ -121,12 +121,12 @@ WebStorageSessionStore.prototype = { }, getEndToEndInboundGroupSession: function(senderKey, sessionId) { - var key = keyEndToEndInboundGroupSession(senderKey, sessionId); + let key = keyEndToEndInboundGroupSession(senderKey, sessionId); return this.store.getItem(key); }, storeEndToEndInboundGroupSession: function(senderKey, sessionId, pickledSession) { - var key = keyEndToEndInboundGroupSession(senderKey, sessionId); + let key = keyEndToEndInboundGroupSession(senderKey, sessionId); return this.store.setItem(key, pickledSession); }, @@ -146,11 +146,11 @@ WebStorageSessionStore.prototype = { */ getEndToEndRoom: function(roomId) { return getJsonItem(this.store, keyEndToEndRoom(roomId)); - } + }, }; -var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account"; -var KEY_END_TO_END_ANNOUNCED = E2E_PREFIX + "announced"; +let KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account"; +let KEY_END_TO_END_ANNOUNCED = E2E_PREFIX + "announced"; function keyEndToEndDevicesForUser(userId) { return E2E_PREFIX + "devices/" + userId; @@ -171,8 +171,7 @@ function keyEndToEndRoom(roomId) { function getJsonItem(store, key) { try { return JSON.parse(store.getItem(key)); - } - catch (e) { + } catch (e) { debuglog("Failed to get key %s: %s", key, e); debuglog(e.stack); } @@ -185,7 +184,7 @@ function setJsonItem(store, key, val) { function debuglog() { if (DEBUG) { - console.log.apply(console, arguments); + console.log(...arguments); } } diff --git a/src/sync.js b/src/sync.js index cb3c9b1e2..9742a2dd3 100644 --- a/src/sync.js +++ b/src/sync.js @@ -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. */ -var q = require("q"); -var User = require("./models/user"); -var Room = require("./models/room"); -var utils = require("./utils"); -var Filter = require("./filter"); -var EventTimeline = require("./models/event-timeline"); +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"); -var DEBUG = true; +let 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. -var BUFFER_PERIOD_MS = 80 * 1000; +let BUFFER_PERIOD_MS = 80 * 1000; function getFilterName(userId, suffix) { // scope this on the user ID because people may login on many accounts @@ -45,8 +45,10 @@ function getFilterName(userId, suffix) { } function debuglog() { - if (!DEBUG) { return; } - console.log.apply(console, arguments); + if (!DEBUG) { + return; +} + console.log(...arguments); } @@ -86,8 +88,8 @@ function SyncApi(client, opts) { * @return {Room} */ SyncApi.prototype.createRoom = function(roomId) { - var client = this.client; - var room = new Room(roomId, { + let client = this.client; + let room = new Room(roomId, { pendingEventOrdering: this.opts.pendingEventOrdering, timelineSupport: client.timelineSupport, }); @@ -106,12 +108,12 @@ SyncApi.prototype.createRoom = function(roomId) { * @private */ SyncApi.prototype._registerStateListeners = function(room) { - var client = this.client; + let 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?) reEmit(client, room.currentState, [ - "RoomState.events", "RoomState.members", "RoomState.newMember" + "RoomState.events", "RoomState.members", "RoomState.newMember", ]); room.currentState.on("RoomState.newMember", function(event, state, member) { member.user = client.getUser(member.userId); @@ -119,7 +121,7 @@ SyncApi.prototype._registerStateListeners = function(room) { client, member, [ "RoomMember.name", "RoomMember.typing", "RoomMember.powerLevel", - "RoomMember.membership" + "RoomMember.membership", ] ); }); @@ -142,17 +144,17 @@ SyncApi.prototype._deregisterStateListeners = function(room) { * @return {Promise} Resolved when they've been added to the store. */ SyncApi.prototype.syncLeftRooms = function() { - var client = this.client; - var self = this; + let client = this.client; + let self = this; // grab a filter with limit=1 and include_leave=true - var filter = new Filter(this.client.credentials.userId); + let filter = new Filter(this.client.credentials.userId); filter.setTimelineLimit(1); filter.setIncludeLeaveRooms(true); - var localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; - var qps = { - timeout: 0 // don't want to block since this is a single isolated req + let localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; + let qps = { + timeout: 0, // don't want to block since this is a single isolated req }; return client.getOrCreateFilter( @@ -163,13 +165,13 @@ SyncApi.prototype.syncLeftRooms = function() { undefined, "GET", "/sync", qps, undefined, localTimeoutMs ); }).then(function(data) { - var leaveRooms = []; + let leaveRooms = []; if (data.rooms && data.rooms.leave) { leaveRooms = self._mapSyncResponseToRoomArray(data.rooms.leave); } - var rooms = []; + let rooms = []; leaveRooms.forEach(function(leaveObj) { - var room = leaveObj.room; + let room = leaveObj.room; rooms.push(room); if (!leaveObj.isBrandNewRoom) { // the intention behind syncLeftRooms is to add in rooms which were @@ -183,9 +185,9 @@ SyncApi.prototype.syncLeftRooms = function() { return; } leaveObj.timeline = leaveObj.timeline || {}; - var timelineEvents = + let timelineEvents = self._mapSyncEventsFormat(leaveObj.timeline, room); - var stateEvents = self._mapSyncEventsFormat(leaveObj.state, room); + let stateEvents = self._mapSyncEventsFormat(leaveObj.state, room); // set the back-pagination token. Do this *before* adding any // events so that clients can start back-paginating. @@ -210,8 +212,8 @@ SyncApi.prototype.syncLeftRooms = function() { * store. */ SyncApi.prototype.peek = function(roomId) { - var self = this; - var client = this.client; + let self = this; + let client = this.client; this._peekRoomId = roomId; return this.client.roomInitialSync(roomId, 20).then(function(response) { // make sure things are init'd @@ -219,17 +221,17 @@ SyncApi.prototype.peek = function(roomId) { response.messages.chunk = response.messages.chunk || []; response.state = response.state || []; - var peekRoom = self.createRoom(roomId); + let peekRoom = self.createRoom(roomId); // FIXME: Mostly duplicated from _processRoomEvents but not entirely // because "state" in this API is at the BEGINNING of the chunk - var oldStateEvents = utils.map( + let oldStateEvents = utils.map( utils.deepCopy(response.state), client.getEventMapper() ); - var stateEvents = utils.map( + let stateEvents = utils.map( response.state, client.getEventMapper() ); - var messages = utils.map( + let messages = utils.map( response.messages.chunk, client.getEventMapper() ); @@ -239,11 +241,10 @@ SyncApi.prototype.peek = function(roomId) { if (response.presence && utils.isArray(response.presence)) { response.presence.map(client.getEventMapper()).forEach( function(presenceEvent) { - var user = client.store.getUser(presenceEvent.getContent().user_id); + let user = client.store.getUser(presenceEvent.getContent().user_id); if (user) { user.setPresenceEvent(presenceEvent); - } - else { + } else { user = createNewUser(client, presenceEvent.getContent().user_id); user.setPresenceEvent(presenceEvent); client.store.storeUser(user); @@ -300,14 +301,13 @@ SyncApi.prototype._peekPoll = function(roomId, token) { return; } - var self = this; + let self = this; // FIXME: gut wrenching; hard-coded timeout values this.client._http.authedRequest(undefined, "GET", "/events", { room_id: roomId, timeout: 30 * 1000, - from: token + from: token, }, undefined, 50 * 1000).done(function(res) { - // We have a problem that we get presence both from /events and /sync // however, /sync only returns presence for users in rooms // you're actually joined to. @@ -320,11 +320,10 @@ SyncApi.prototype._peekPoll = function(roomId, token) { res.chunk.filter(function(e) { return e.type === "m.presence"; }).map(self.client.getEventMapper()).forEach(function(presenceEvent) { - var user = self.client.store.getUser(presenceEvent.getContent().user_id); + let user = self.client.store.getUser(presenceEvent.getContent().user_id); if (user) { user.setPresenceEvent(presenceEvent); - } - else { + } else { user = createNewUser(self.client, presenceEvent.getContent().user_id); user.setPresenceEvent(presenceEvent); self.client.store.storeUser(user); @@ -333,10 +332,10 @@ SyncApi.prototype._peekPoll = function(roomId, token) { }); // strip out events which aren't for the given room_id (e.g presence) - var events = res.chunk.filter(function(e) { + let events = res.chunk.filter(function(e) { return e.room_id === roomId; }).map(self.client.getEventMapper()); - var room = self.client.getRoom(roomId); + let room = self.client.getRoom(roomId); room.addLiveEvents(events); self._peekPoll(roomId, res.end); }, function(err) { @@ -363,8 +362,8 @@ SyncApi.prototype.sync = function() { debuglog("SyncApi.sync: starting with sync token " + this.client.store.getSyncToken()); - var client = this.client; - var self = this; + let client = this.client; + let self = this; this._running = true; @@ -393,7 +392,7 @@ SyncApi.prototype.sync = function() { } function getFilter() { - var filter; + let filter; if (self.opts.filter) { filter = self.opts.filter; } else { @@ -422,8 +421,7 @@ SyncApi.prototype.sync = function() { if (client.isGuest()) { // no push rules for guests, no access to POST filter for guests. self._sync({}); - } - else { + } else { getPushRules(); } }; @@ -438,7 +436,9 @@ SyncApi.prototype.stop = function() { this._onOnlineBound = undefined; } this._running = false; - if (this._currentSyncRequest) { this._currentSyncRequest.abort(); } + if (this._currentSyncRequest) { + this._currentSyncRequest.abort(); +} if (this._keepAliveTimer) { clearTimeout(this._keepAliveTimer); this._keepAliveTimer = null; @@ -451,7 +451,9 @@ SyncApi.prototype.stop = function() { * @return {boolean} True if this resulted in a request being retried. */ SyncApi.prototype.retryImmediately = function() { - if (!this._connectionReturnedDefer) { return false; } + if (!this._connectionReturnedDefer) { + return false; +} this._startKeepAlives(0); return true; }; @@ -463,8 +465,8 @@ SyncApi.prototype.retryImmediately = function() { * @param {boolean} syncOptions.hasSyncedBefore */ SyncApi.prototype._sync = function(syncOptions) { - var client = this.client; - var self = this; + let client = this.client; + let self = this; if (!this._running) { debuglog("Sync no longer running: exiting."); @@ -476,14 +478,14 @@ SyncApi.prototype._sync = function(syncOptions) { return; } - var filterId = syncOptions.filterId; + let filterId = syncOptions.filterId; if (client.isGuest() && !filterId) { filterId = this._getGuestFilter(); } - var syncToken = client.store.getSyncToken(); + let syncToken = client.store.getSyncToken(); - var qps = { + let qps = { filter: filterId, timeout: this.opts.pollTimeout, }; @@ -506,7 +508,7 @@ SyncApi.prototype._sync = function(syncOptions) { } // normal timeout= plus buffer time - var clientSideTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; + let clientSideTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; this._currentSyncRequest = client._http.authedRequest( undefined, "GET", "/sync", qps, undefined, clientSideTimeoutMs @@ -520,8 +522,7 @@ SyncApi.prototype._sync = function(syncOptions) { try { self._processSyncResponse(syncToken, data); - } - catch (e) { + } catch (e) { // log the exception with stack if we have it, else fall back // to the plain description console.error("Caught /sync error", e.stack || e); @@ -575,8 +576,8 @@ SyncApi.prototype._sync = function(syncOptions) { * @param {Object} data The response from /sync */ SyncApi.prototype._processSyncResponse = function(syncToken, data) { - var client = this.client; - var self = this; + let client = this.client; + let self = this; // data looks like: // { @@ -620,11 +621,10 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { if (data.presence && utils.isArray(data.presence.events)) { data.presence.events.map(client.getEventMapper()).forEach( function(presenceEvent) { - var user = client.store.getUser(presenceEvent.getSender()); + let user = client.store.getUser(presenceEvent.getSender()); if (user) { user.setPresenceEvent(presenceEvent); - } - else { + } else { user = createNewUser(client, presenceEvent.getSender()); user.setPresenceEvent(presenceEvent); client.store.storeUser(user); @@ -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)) { - var events = data.account_data.events.map(client.getEventMapper()); + let 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) { - var content = toDeviceEvent.getContent(); + let content = toDeviceEvent.getContent(); if ( toDeviceEvent.getType() == "m.room.message" && content.msgtype == "m.bad.encrypted" @@ -673,9 +673,9 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { // the returned json structure is a bit crap, so make it into a // nicer form (array) after applying sanity to make sure we don't fail // on missing keys (on the off chance) - var inviteRooms = []; - var joinRooms = []; - var leaveRooms = []; + let inviteRooms = []; + let joinRooms = []; + let leaveRooms = []; if (data.rooms) { if (data.rooms.invite) { @@ -693,8 +693,8 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { // Handle invites inviteRooms.forEach(function(inviteObj) { - var room = inviteObj.room; - var stateEvents = + let room = inviteObj.room; + let stateEvents = self._mapSyncEventsFormat(inviteObj.invite_state, room); self._processRoomEvents(room, stateEvents); if (inviteObj.isBrandNewRoom) { @@ -702,16 +702,18 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { client.store.storeRoom(room); client.emit("Room", room); } - stateEvents.forEach(function(e) { client.emit("event", e); }); + stateEvents.forEach(function(e) { + client.emit("event", e); +}); }); // Handle joins joinRooms.forEach(function(joinObj) { - var room = joinObj.room; - var stateEvents = self._mapSyncEventsFormat(joinObj.state, room); - var timelineEvents = self._mapSyncEventsFormat(joinObj.timeline, room); - var ephemeralEvents = self._mapSyncEventsFormat(joinObj.ephemeral); - var accountDataEvents = self._mapSyncEventsFormat(joinObj.account_data); + 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); // we do this first so it's correct when any of the events fire if (joinObj.unread_notifications) { @@ -730,9 +732,8 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { // events so that clients can start back-paginating. room.getLiveTimeline().setPaginationToken( joinObj.timeline.prev_batch, EventTimeline.BACKWARDS); - } - else if (joinObj.timeline.limited) { - var limited = true; + } else if (joinObj.timeline.limited) { + let limited = true; // we've got a limited sync, so we *probably* have a gap in the // timeline, so should reset. But we might have been peeking or @@ -746,8 +747,8 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { // which we'll try to paginate but not get any new events (which // will stop us linking the empty timeline into the chain). // - for (var i = timelineEvents.length - 1; i >= 0; i--) { - var eventId = timelineEvents[i].getId(); + for (let i = timelineEvents.length - 1; i >= 0; i--) { + let eventId = timelineEvents[i].getId(); if (room.getTimelineForEvent(eventId)) { debuglog("Already have event " + eventId + " in limited " + "sync - not resetting"); @@ -801,20 +802,28 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { client.store.storeRoom(room); client.emit("Room", room); } - stateEvents.forEach(function(e) { client.emit("event", e); }); - timelineEvents.forEach(function(e) { client.emit("event", e); }); - ephemeralEvents.forEach(function(e) { client.emit("event", e); }); - accountDataEvents.forEach(function(e) { client.emit("event", e); }); + stateEvents.forEach(function(e) { + client.emit("event", e); +}); + timelineEvents.forEach(function(e) { + client.emit("event", e); +}); + ephemeralEvents.forEach(function(e) { + client.emit("event", e); +}); + accountDataEvents.forEach(function(e) { + client.emit("event", e); +}); }); // Handle leaves (e.g. kicked rooms) leaveRooms.forEach(function(leaveObj) { - var room = leaveObj.room; - var stateEvents = + let room = leaveObj.room; + let stateEvents = self._mapSyncEventsFormat(leaveObj.state, room); - var timelineEvents = + let timelineEvents = self._mapSyncEventsFormat(leaveObj.timeline, room); - var accountDataEvents = + let accountDataEvents = self._mapSyncEventsFormat(leaveObj.account_data); self._processRoomEvents(room, stateEvents, timelineEvents); @@ -826,9 +835,15 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) { client.emit("Room", room); } - stateEvents.forEach(function(e) { client.emit("event", e); }); - timelineEvents.forEach(function(e) { client.emit("event", e); }); - accountDataEvents.forEach(function(e) { client.emit("event", e); }); + stateEvents.forEach(function(e) { + client.emit("event", e); +}); + timelineEvents.forEach(function(e) { + client.emit("event", e); +}); + accountDataEvents.forEach(function(e) { + client.emit("event", e); +}); }); // update the notification timeline, if appropriate. @@ -861,7 +876,7 @@ SyncApi.prototype._startKeepAlives = function(delay) { if (this._keepAliveTimer !== null) { clearTimeout(this._keepAliveTimer); } - var self = this; + let self = this; if (delay > 0) { self._keepAliveTimer = setTimeout( self._pokeKeepAlive.bind(self), @@ -880,7 +895,7 @@ SyncApi.prototype._startKeepAlives = function(delay) { * */ SyncApi.prototype._pokeKeepAlive = function() { - var self = this; + let self = this; function success() { clearTimeout(self._keepAliveTimer); if (self._connectionReturnedDefer) { @@ -932,12 +947,12 @@ SyncApi.prototype._mapSyncResponseToRoomArray = function(obj) { // Maps { roomid: {stuff}, roomid: {stuff} } // to // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}] - var client = this.client; - var self = this; + let client = this.client; + let self = this; return utils.keys(obj).map(function(roomId) { - var arrObj = obj[roomId]; - var room = client.store.getRoom(roomId); - var isBrandNewRoom = false; + let arrObj = obj[roomId]; + let room = client.store.getRoom(roomId); + let isBrandNewRoom = false; if (!room) { room = self.createRoom(roomId); isBrandNewRoom = true; @@ -957,7 +972,7 @@ SyncApi.prototype._mapSyncEventsFormat = function(obj, room) { if (!obj || !utils.isArray(obj.events)) { return []; } - var mapper = this.client.getEventMapper(); + let mapper = this.client.getEventMapper(); return obj.events.map(function(e) { if (room) { e.room_id = room.roomId; @@ -973,7 +988,7 @@ SyncApi.prototype._resolveInvites = function(room) { if (!room || !this.opts.resolveInvitesToProfiles) { return; } - var client = this.client; + let 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) { @@ -982,22 +997,21 @@ SyncApi.prototype._resolveInvites = function(room) { } member._requestedProfileInfo = true; // try to get a cached copy first. - var user = client.getUser(member.userId); - var promise; + let user = client.getUser(member.userId); + let promise; if (user) { promise = q({ avatar_url: user.avatarUrl, - displayname: user.displayName + displayname: user.displayName, }); - } - else { + } else { promise = client.getProfileInfo(member.userId); } promise.done(function(info) { // 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. - var inviteEvent = member.events.member; + let inviteEvent = member.events.member; if (inviteEvent.getContent().membership !== "invite") { // between resolving and now they have since joined, so don't clobber return; @@ -1022,17 +1036,19 @@ SyncApi.prototype._resolveInvites = function(room) { SyncApi.prototype._processRoomEvents = function(room, stateEventList, timelineEventList) { timelineEventList = timelineEventList || []; - var client = this.client; + let 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! - var oldStateEvents = utils.map( + let oldStateEvents = utils.map( utils.deepCopy( - stateEventList.map(function(mxEvent) { return mxEvent.event; }) + stateEventList.map(function(mxEvent) { + return mxEvent.event; +}) ), client.getEventMapper() ); - var stateEvents = stateEventList; + let stateEvents = stateEventList; // set the state of the room to as it was before the timeline executes // @@ -1051,11 +1067,10 @@ SyncApi.prototype._processRoomEvents = function(room, stateEventList, // gather our notifications into this._notifEvents if (client.getNotifTimelineSet()) { - for (var i = 0; i < timelineEventList.length; i++) { - var pushActions = client.getPushActionsForEvent(timelineEventList[i]); + for (let i = 0; i < timelineEventList.length; i++) { + let pushActions = client.getPushActionsForEvent(timelineEventList[i]); if (pushActions && pushActions.notify && - pushActions.tweaks && pushActions.tweaks.highlight) - { + pushActions.tweaks && pushActions.tweaks.highlight) { this._notifEvents.push(timelineEventList[i]); } } @@ -1070,7 +1085,7 @@ SyncApi.prototype._processRoomEvents = function(room, stateEventList, * @return {string} */ SyncApi.prototype._getGuestFilter = function() { - var guestRooms = this.client._guestRooms; // FIXME: horrible gut-wrenching + let guestRooms = this.client._guestRooms; // FIXME: horrible gut-wrenching if (!guestRooms) { return "{}"; } @@ -1079,9 +1094,9 @@ SyncApi.prototype._getGuestFilter = function() { return JSON.stringify({ room: { timeline: { - limit: 20 - } - } + limit: 20, + }, + }, }); }; @@ -1091,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) { - var old = this._syncState; + let old = this._syncState; this._syncState = newState; this.client.emit("sync", this._syncState, old, data); }; @@ -1108,10 +1123,10 @@ SyncApi.prototype._onOnline = function() { }; function createNewUser(client, userId) { - var user = new User(userId); + let user = new User(userId); reEmit(client, user, [ "User.avatarUrl", "User.displayName", "User.presence", - "User.currentlyActive", "User.lastPresenceTs" + "User.currentlyActive", "User.lastPresenceTs", ]); return user; } @@ -1125,11 +1140,11 @@ function reEmit(reEmitEntity, emittableEntity, eventNames) { // Transformation Example: // listener on "foo" => function(a,b) { ... } // Re-emit on "thing" => thing.emit("foo", a, b) - var newArgs = [eventName]; - for (var i = 0; i < arguments.length; i++) { + let newArgs = [eventName]; + for (let i = 0; i < arguments.length; i++) { newArgs.push(arguments[i]); } - reEmitEntity.emit.apply(reEmitEntity, newArgs); + reEmitEntity.emit(...newArgs); }); }); } diff --git a/src/timeline-window.js b/src/timeline-window.js index 742634313..226eedbab 100644 --- a/src/timeline-window.js +++ b/src/timeline-window.js @@ -17,25 +17,25 @@ limitations under the License. /** @module timeline-window */ -var q = require("q"); -var EventTimeline = require("./models/event-timeline"); +let q = require("q"); +let EventTimeline = require("./models/event-timeline"); /** * @private */ -var DEBUG = false; +let DEBUG = false; /** * @private */ -var debuglog = DEBUG ? console.log.bind(console) : function() {}; +let debuglog = DEBUG ? console.log.bind(console) : function() {}; /** * the number of times we ask the server for more events before giving up * * @private */ -var DEFAULT_PAGINATE_LOOP_LIMIT = 5; +let 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) { - var self = this; + let 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. - var initFields = function(timeline, eventIndex) { - var endIndex = Math.min(timeline.getEvents().length, + let initFields = function(timeline, eventIndex) { + let endIndex = Math.min(timeline.getEvents().length, eventIndex + Math.ceil(initialWindowSize / 2)); - var startIndex = Math.max(0, endIndex - initialWindowSize); + let 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; @@ -116,7 +116,7 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) { return this._client.getEventTimeline(this._timelineSet, initialEventId) .then(function(tl) { // make sure that our window includes the event - for (var i = 0; i < tl.getEvents().length; i++) { + for (let i = 0; i < tl.getEvents().length; i++) { if (tl.getEvents()[i].getId() == initialEventId) { initFields(tl, i); return; @@ -126,7 +126,7 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) { }); } else { // start with the most recent events - var tl = this._timelineSet.getLiveTimeline(); + let tl = this._timelineSet.getLiveTimeline(); initFields(tl, tl.getEvents().length); return q(); } @@ -146,7 +146,7 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) { * @return {boolean} true if we can paginate in the given direction */ TimelineWindow.prototype.canPaginate = function(direction) { - var tl; + let tl; if (direction == EventTimeline.BACKWARDS) { tl = this._start; } else if (direction == EventTimeline.FORWARDS) { @@ -161,9 +161,13 @@ TimelineWindow.prototype.canPaginate = function(direction) { } if (direction == EventTimeline.BACKWARDS) { - if (tl.index > tl.minIndex()) { return true; } + if (tl.index > tl.minIndex()) { + return true; +} } else { - if (tl.index < tl.maxIndex()) { return true; } + if (tl.index < tl.maxIndex()) { + return true; +} } return Boolean(tl.timeline.getNeighbouringTimeline(direction) || @@ -205,7 +209,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest, requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT; } - var tl; + let tl; if (direction == EventTimeline.BACKWARDS) { tl = this._start; } else if (direction == EventTimeline.FORWARDS) { @@ -224,7 +228,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest, } // try moving the cap - var count = (direction == EventTimeline.BACKWARDS) ? + let count = (direction == EventTimeline.BACKWARDS) ? tl.retreat(size) : tl.advance(size); if (count) { @@ -232,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 - var excess = this._eventCount - this._windowLimit; + let excess = this._eventCount - this._windowLimit; if (excess > 0) { this.unpaginate(excess, direction != EventTimeline.BACKWARDS); } @@ -246,18 +250,18 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest, } // try making a pagination request - var token = tl.timeline.getPaginationToken(direction); + let token = tl.timeline.getPaginationToken(direction); if (!token) { debuglog("TimelineWindow: no token"); return q(false); } debuglog("TimelineWindow: starting request"); - var self = this; + let self = this; - var prom = this._client.paginateEventTimeline(tl.timeline, { + let prom = this._client.paginateEventTimeline(tl.timeline, { backwards: direction == EventTimeline.BACKWARDS, - limit: size + limit: size, }).finally(function() { tl.pendingPaginate = null; }).then(function(r) { @@ -294,7 +298,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest, * of the timeline. */ TimelineWindow.prototype.unpaginate = function(delta, startOfTimeline) { - var tl = startOfTimeline ? this._start : this._end; + let tl = startOfTimeline ? this._start : this._end; // sanity-check the delta if (delta > this._eventCount || delta < 0) { @@ -303,7 +307,7 @@ TimelineWindow.prototype.unpaginate = function(delta, startOfTimeline) { } while (delta > 0) { - var count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta); + let count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta); if (count <= 0) { // sadness. This shouldn't be possible. throw new Error( @@ -330,13 +334,13 @@ TimelineWindow.prototype.getEvents = function() { return []; } - var result = []; + let result = []; // iterate through each timeline between this._start and this._end // (inclusive). - var timeline = this._start.timeline; + let timeline = this._start.timeline; while (true) { - var events = timeline.getEvents(); + let 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 @@ -346,7 +350,7 @@ TimelineWindow.prototype.getEvents = function() { // (Note that both this._start.index and this._end.index are relative // to their respective timelines' BaseIndex). // - var startIndex = 0, endIndex = events.length; + let startIndex = 0, endIndex = events.length; if (timeline === this._start.timeline) { startIndex = this._start.index + timeline.getBaseIndex(); } @@ -354,7 +358,7 @@ TimelineWindow.prototype.getEvents = function() { endIndex = this._end.index + timeline.getBaseIndex(); } - for (var i = startIndex; i < endIndex; i++) { + for (let i = startIndex; i < endIndex; i++) { result.push(events[i]); } @@ -415,7 +419,7 @@ TimelineIndex.prototype.advance = function(delta) { // first try moving the index in the current timeline. See if there is room // to do so. - var cappedDelta; + let cappedDelta; if (delta < 0) { // we want to wind the index backwards. // @@ -443,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. - var neighbour = this.timeline.getNeighbouringTimeline( + let neighbour = this.timeline.getNeighbouringTimeline( delta < 0 ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS); if (neighbour) { this.timeline = neighbour; diff --git a/src/utils.js b/src/utils.js index 2f3fe28b0..e9d3c2ba1 100644 --- a/src/utils.js +++ b/src/utils.js @@ -26,9 +26,11 @@ limitations under the License. * @return {string} The encoded string e.g. foo=bar&baz=taz */ module.exports.encodeParams = function(params) { - var qs = ""; - for (var key in params) { - if (!params.hasOwnProperty(key)) { continue; } + let qs = ""; + for (let key in params) { + if (!params.hasOwnProperty(key)) { + continue; +} qs += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); } @@ -44,8 +46,10 @@ 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 (var key in variables) { - if (!variables.hasOwnProperty(key)) { continue; } + for (let key in variables) { + if (!variables.hasOwnProperty(key)) { + continue; +} pathTemplate = pathTemplate.replace( key, encodeURIComponent(variables[key]) ); @@ -61,8 +65,8 @@ module.exports.encodeUri = function(pathTemplate, variables) { * @return {Array} A new array with the results of the function. */ module.exports.map = function(array, fn) { - var results = new Array(array.length); - for (var i = 0; i < array.length; i++) { + let results = new Array(array.length); + for (let i = 0; i < array.length; i++) { results[i] = fn(array[i]); } return results; @@ -77,8 +81,8 @@ module.exports.map = function(array, fn) { * @return {Array} A new array with the results of the function. */ module.exports.filter = function(array, fn) { - var results = []; - for (var i = 0; i < array.length; i++) { + let results = []; + for (let i = 0; i < array.length; i++) { if (fn(array[i], i, array)) { results.push(array[i]); } @@ -92,9 +96,11 @@ module.exports.filter = function(array, fn) { * @return {string[]} The keys of the object. */ module.exports.keys = function(obj) { - var keys = []; - for (var key in obj) { - if (!obj.hasOwnProperty(key)) { continue; } + let keys = []; + for (let key in obj) { + if (!obj.hasOwnProperty(key)) { + continue; +} keys.push(key); } return keys; @@ -106,9 +112,11 @@ module.exports.keys = function(obj) { * @return {Array<*>} The values of the object. */ module.exports.values = function(obj) { - var values = []; - for (var key in obj) { - if (!obj.hasOwnProperty(key)) { continue; } + let values = []; + for (let key in obj) { + if (!obj.hasOwnProperty(key)) { + continue; +} values.push(obj[key]); } return values; @@ -121,7 +129,7 @@ module.exports.values = function(obj) { * function signature fn(element, index). */ module.exports.forEach = function(array, fn) { - for (var i = 0; i < array.length; i++) { + for (let i = 0; i < array.length; i++) { fn(array[i], i); } }; @@ -138,15 +146,14 @@ module.exports.forEach = function(array, fn) { * the given function. */ module.exports.findElement = function(array, fn, reverse) { - var i; + let i; if (reverse) { for (i = array.length - 1; i >= 0; i--) { if (fn(array[i], i, array)) { return array[i]; } } - } - else { + } else { for (i = 0; i < array.length; i++) { if (fn(array[i], i, array)) { return array[i]; @@ -166,8 +173,8 @@ module.exports.findElement = function(array, fn, reverse) { * @return {boolean} True if an element was removed. */ module.exports.removeElement = function(array, fn, reverse) { - var i; - var removed; + let i; + let removed; if (reverse) { for (i = array.length - 1; i >= 0; i--) { if (fn(array[i], i, array)) { @@ -176,8 +183,7 @@ module.exports.removeElement = function(array, fn, reverse) { return removed; } } - } - else { + } else { for (i = 0; i < array.length; i++) { if (fn(array[i], i, array)) { removed = array[i]; @@ -215,7 +221,7 @@ module.exports.isArray = function(value) { * @throws If the object is missing keys. */ module.exports.checkObjectHasKeys = function(obj, keys) { - for (var i = 0; i < keys.length; i++) { + for (let i = 0; i < keys.length; i++) { if (!obj.hasOwnProperty(keys[i])) { throw new Error("Missing required key: " + keys[i]); } @@ -229,8 +235,10 @@ module.exports.checkObjectHasKeys = function(obj, keys) { * @throws If there are extra keys. */ module.exports.checkObjectHasNoAdditionalKeys = function(obj, allowedKeys) { - for (var key in obj) { - if (!obj.hasOwnProperty(key)) { continue; } + for (let key in obj) { + if (!obj.hasOwnProperty(key)) { + continue; +} if (allowedKeys.indexOf(key) === -1) { throw new Error("Unknown key: " + key); } @@ -255,7 +263,7 @@ module.exports.deepCopy = function(obj) { * * @return {boolean} true if the two objects are equal */ -var deepCompare = module.exports.deepCompare = function(x, y) { +let deepCompare = module.exports.deepCompare = function(x, y) { // Inspired by // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249 @@ -301,7 +309,7 @@ var deepCompare = module.exports.deepCompare = function(x, y) { return false; } - for (var i = 0; i < x.length; i++) { + for (let i = 0; i < x.length; i++) { if (!deepCompare(x[i], y[i])) { return false; } @@ -312,7 +320,7 @@ var deepCompare = module.exports.deepCompare = function(x, y) { /* jshint -W089 */ // check that all of y's direct keys are in x - var p; + let p; for (p in y) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; @@ -347,10 +355,10 @@ var deepCompare = module.exports.deepCompare = function(x, y) { * @return {Object} target */ module.exports.extend = function() { - var target = arguments[0] || {}; - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var propName in source) { // eslint-disable-line guard-for-in + let 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 target[propName] = source[propName]; } } @@ -367,22 +375,21 @@ module.exports.runPolyfills = function() { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { - if (this === void 0 || this === null) { throw new TypeError(); } - var t = Object(this); - var len = t.length >>> 0; + let t = Object(this); + let len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } - var res = []; - var thisArg = arguments.length >= 2 ? arguments[1] : void 0; - for (var i = 0; i < len; i++) { + let res = []; + let thisArg = arguments.length >= 2 ? arguments[1] : void 0; + for (let i = 0; i < len; i++) { if (i in t) { - var val = t[i]; + let val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by @@ -406,10 +413,8 @@ module.exports.runPolyfills = function() { // Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.io/#x15.4.4.19 if (!Array.prototype.map) { - Array.prototype.map = function(callback, thisArg) { - - var T, A, k; + let T, A, k; if (this === null || this === undefined) { throw new TypeError(' this is null or not defined'); @@ -417,12 +422,12 @@ module.exports.runPolyfills = function() { // 1. Let O be the result of calling ToObject passing the |this| // value as the argument. - var O = Object(this); + let 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). - var len = O.length >>> 0; + let len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 @@ -445,7 +450,6 @@ module.exports.runPolyfills = function() { // 8. Repeat, while k < len while (k < len) { - var kValue, mappedValue; // a. Let Pk be ToString(k). @@ -455,7 +459,6 @@ module.exports.runPolyfills = function() { // This step can be combined with c // c. If kPresent is true, then if (k in O) { - // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; @@ -500,10 +503,8 @@ module.exports.runPolyfills = function() { // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.io/#x15.4.4.18 if (!Array.prototype.forEach) { - Array.prototype.forEach = function(callback, thisArg) { - - var T, k; + let T, k; if (this === null || this === undefined) { throw new TypeError(' this is null or not defined'); @@ -511,12 +512,12 @@ module.exports.runPolyfills = function() { // 1. Let O be the result of calling ToObject passing the |this| value as the // argument. - var O = Object(this); + let 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). - var len = O.length >>> 0; + let len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 @@ -534,7 +535,6 @@ module.exports.runPolyfills = function() { // 7. Repeat, while k < len while (k < len) { - var kValue; // a. Let Pk be ToString(k). @@ -545,7 +545,6 @@ module.exports.runPolyfills = function() { // This step can be combined with c // c. If kPresent is true, then if (k in O) { - // i. Let kValue be the result of calling the Get internal method of O with // argument Pk kValue = O[k]; @@ -583,7 +582,7 @@ module.exports.inherits = function(ctor, superCtor) { function Temp() {} // make a safe reference to Object.prototype.hasOwnProperty - var hasOwn = Object.prototype.hasOwnProperty; + let hasOwn = Object.prototype.hasOwnProperty; return function(O) { // 1. If Type(O) is not Object or Null throw a TypeError exception. @@ -596,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; - var obj = new Temp(); + let 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 @@ -605,8 +604,8 @@ module.exports.inherits = function(ctor, superCtor) { // Properties. if (arguments.length > 1) { // Object.defineProperties does ToObject on its first argument. - var Properties = Object(arguments[1]); - for (var prop in Properties) { + let Properties = Object(arguments[1]); + for (let prop in Properties) { if (hasOwn.call(Properties, prop)) { obj[prop] = Properties[prop]; } @@ -649,7 +648,7 @@ module.exports.inherits = function(ctor, superCtor) { value: ctor, enumerable: false, writable: true, - configurable: true - } + configurable: true, + }, }); }; diff --git a/src/webrtc/call.js b/src/webrtc/call.js index 772472407..1ad12c8d2 100644 --- a/src/webrtc/call.js +++ b/src/webrtc/call.js @@ -18,9 +18,9 @@ limitations under the License. * This is an internal module. See {@link createNewMatrixCall} for the public API. * @module webrtc/call */ -var utils = require("../utils"); -var EventEmitter = require("events").EventEmitter; -var DEBUG = true; // set true to enable console logging. +let utils = require("../utils"); +let EventEmitter = require("events").EventEmitter; +let DEBUG = true; // set true to enable console logging. // events: hangup, error(err), replaced(call), state(state, oldState) @@ -43,7 +43,7 @@ function MatrixCall(opts) { this.turnServers = opts.turnServers || []; if (this.turnServers.length === 0) { this.turnServers.push({ - urls: [MatrixCall.FALLBACK_STUN_SERVER] + urls: [MatrixCall.FALLBACK_STUN_SERVER], }); } utils.forEach(this.turnServers, function(server) { @@ -122,21 +122,20 @@ MatrixCall.prototype.placeVideoCall = function(remoteVideoElement, localVideoEle * @throws If you have not specified a listener for 'error' events. */ MatrixCall.prototype.placeScreenSharingCall = - function(remoteVideoElement, localVideoElement) -{ + function(remoteVideoElement, localVideoElement) { debuglog("placeScreenSharingCall"); checkForErrorListener(this); - var screenConstraints = _getChromeScreenSharingConstraints(this); + let screenConstraints = _getChromeScreenSharingConstraints(this); if (!screenConstraints) { return; } this.localVideoElement = localVideoElement; this.remoteVideoElement = remoteVideoElement; - var self = this; + let self = this; this.webRtc.getUserMedia(screenConstraints, function(stream) { self.screenSharingStream = stream; debuglog("Got screen stream, requesting audio stream..."); - var audioConstraints = _getUserMediaVideoContraints('voice'); + let audioConstraints = _getUserMediaVideoContraints('voice'); _placeCallWithConstraints(self, audioConstraints); }, function(err) { self.emit("error", @@ -174,8 +173,7 @@ MatrixCall.prototype.playElement = function(element, queueId) { console.log("previous promise failed for " + queueId); return element.play(); }); - } - else { + } else { this.mediaPromises[queueId] = element.play(); } }; @@ -197,8 +195,7 @@ MatrixCall.prototype.pauseElement = function(element, queueId) { console.log("previous promise failed for " + queueId); return element.pause(); }); - } - else { + } else { // pause doesn't actually return a promise, but do this for symmetry // and just in case it does in future. this.mediaPromises[queueId] = element.pause(); @@ -224,8 +221,7 @@ MatrixCall.prototype.assignElement = function(element, src, queueId) { console.log("previous promise failed for " + queueId); element.src = src; }); - } - else { + } else { element.src = src; } }; @@ -270,9 +266,9 @@ MatrixCall.prototype.setLocalVideoElement = function(element) { this.URL.createObjectURL(this.localAVStream), "localVideo"); element.muted = true; - var self = this; + let self = this; setTimeout(function() { - var vel = self.getLocalVideoElement(); + let vel = self.getLocalVideoElement(); if (vel.play) { self.playElement(vel, "localVideo"); } @@ -310,7 +306,7 @@ MatrixCall.prototype.setRemoteAudioElement = function(element) { MatrixCall.prototype._initWithInvite = function(event) { this.msg = event.getContent(); this.peerConn = _createPeerConnection(this); - var self = this; + let self = this; if (this.peerConn) { this.peerConn.setRemoteDescription( new this.webRtc.RtcSessionDescription(this.msg.offer), @@ -330,8 +326,7 @@ MatrixCall.prototype._initWithInvite = function(event) { this.msg.offer.sdp.indexOf('m=video') > -1 ) { this.type = 'video'; - } - else { + } else { this.type = 'voice'; } @@ -369,7 +364,7 @@ MatrixCall.prototype._initWithHangup = function(event) { */ MatrixCall.prototype.answer = function() { debuglog("Answering call %s of type %s", this.callId, this.type); - var self = this; + let self = this; if (!this.localAVStream && !this.waitForLocalAVStream) { this.webRtc.getUserMedia( @@ -421,10 +416,10 @@ MatrixCall.prototype._replacedBy = function(newCall) { MatrixCall.prototype.hangup = function(reason, suppressEvent) { debuglog("Ending call " + this.callId); terminate(this, "local", reason, !suppressEvent); - var content = { + let content = { version: 0, call_id: this.callId, - reason: reason + reason: reason, }; sendEvent(this, 'm.call.hangup', content); }; @@ -497,8 +492,8 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) { return; } debuglog("_gotUserMediaForInvite -> " + this.type); - var self = this; - var videoEl = this.getLocalVideoElement(); + let self = this; + let videoEl = this.getLocalVideoElement(); if (videoEl && this.type == 'video') { videoEl.autoplay = true; @@ -507,15 +502,14 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) { this.assignElement(videoEl, this.URL.createObjectURL(this.screenSharingStream), "localVideo"); - } - else { + } else { this.assignElement(videoEl, this.URL.createObjectURL(stream), "localVideo"); } videoEl.muted = true; setTimeout(function() { - var vel = self.getLocalVideoElement(); + let vel = self.getLocalVideoElement(); if (vel.play) { self.playElement(vel, "localVideo"); } @@ -543,11 +537,11 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) { * @param {Object} stream */ MatrixCall.prototype._gotUserMediaForAnswer = function(stream) { - var self = this; + let self = this; if (self.state == 'ended') { return; } - var localVidEl = self.getLocalVideoElement(); + let localVidEl = self.getLocalVideoElement(); if (localVidEl && self.type == 'video') { localVidEl.autoplay = true; @@ -556,7 +550,7 @@ MatrixCall.prototype._gotUserMediaForAnswer = function(stream) { "localVideo"); localVidEl.muted = true; setTimeout(function() { - var vel = self.getLocalVideoElement(); + let vel = self.getLocalVideoElement(); if (vel.play) { self.playElement(vel, "localVideo"); } @@ -567,22 +561,22 @@ MatrixCall.prototype._gotUserMediaForAnswer = function(stream) { setTracksEnabled(stream.getAudioTracks(), true); self.peerConn.addStream(stream); - var constraints = { + let constraints = { 'mandatory': { 'OfferToReceiveAudio': true, - 'OfferToReceiveVideo': self.type == 'video' - } + 'OfferToReceiveVideo': self.type == 'video', + }, }; self.peerConn.createAnswer(function(description) { debuglog("Created answer: " + description); self.peerConn.setLocalDescription(description, function() { - var content = { + let content = { version: 0, call_id: self.callId, answer: { sdp: self.peerConn.localDescription.sdp, - type: self.peerConn.localDescription.type - } + type: self.peerConn.localDescription.type, + }, }; sendEvent(self, 'm.call.answer', content); setState(self, 'connecting'); @@ -608,10 +602,10 @@ 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. - var c = { + let c = { candidate: event.candidate.candidate, sdpMid: event.candidate.sdpMid, - sdpMLineIndex: event.candidate.sdpMLineIndex + sdpMLineIndex: event.candidate.sdpMLineIndex, }; sendCandidate(this, c); } @@ -645,7 +639,7 @@ MatrixCall.prototype._receivedAnswer = function(msg) { return; } - var self = this; + let self = this; this.peerConn.setRemoteDescription( new this.webRtc.RtcSessionDescription(msg.answer), hookCallback(self, self._onSetRemoteDescriptionSuccess), @@ -660,7 +654,7 @@ MatrixCall.prototype._receivedAnswer = function(msg) { * @param {Object} description */ MatrixCall.prototype._gotLocalOffer = function(description) { - var self = this; + let self = this; debuglog("Created offer: " + description); if (self.state == 'ended') { @@ -670,7 +664,7 @@ MatrixCall.prototype._gotLocalOffer = function(description) { } self.peerConn.setLocalDescription(description, function() { - var content = { + let content = { version: 0, call_id: self.callId, // OpenWebRTC appears to add extra stuff (like the DTLS fingerprint) @@ -684,9 +678,9 @@ MatrixCall.prototype._gotLocalOffer = function(description) { // Chrome (as of about m43). offer: { sdp: self.peerConn.localDescription.sdp, - type: self.peerConn.localDescription.type + type: self.peerConn.localDescription.type, }, - lifetime: MatrixCall.CALL_TIMEOUT_MS + lifetime: MatrixCall.CALL_TIMEOUT_MS, }; sendEvent(self, 'm.call.invite', content); @@ -788,7 +782,7 @@ MatrixCall.prototype._onSetRemoteDescriptionError = function(e) { MatrixCall.prototype._onAddStream = function(event) { debuglog("Stream id " + event.stream.id + " added"); - var s = event.stream; + let s = event.stream; if (s.getVideoTracks().length > 0) { this.type = 'video'; @@ -799,7 +793,7 @@ MatrixCall.prototype._onAddStream = function(event) { this.remoteAStream = s; } - var self = this; + let self = this; forAllTracksOnStream(s, function(t) { debuglog("Track id " + t.id + " added"); // not currently implemented in chrome @@ -808,8 +802,7 @@ MatrixCall.prototype._onAddStream = function(event) { if (event.stream.oninactive !== undefined) { event.stream.oninactive = hookCallback(self, self._onRemoteStreamEnded); - } - else { + } else { // onended is deprecated from Chrome 54 event.stream.onended = hookCallback(self, self._onRemoteStreamEnded); } @@ -820,8 +813,7 @@ MatrixCall.prototype._onAddStream = function(event) { if (this.type === 'video') { _tryPlayRemoteStream(this); _tryPlayRemoteAudioStream(this); - } - else { + } else { _tryPlayRemoteAudioStream(this); } }; @@ -880,14 +872,14 @@ MatrixCall.prototype._onAnsweredElsewhere = function(msg) { terminate(this, "remote", "answered_elsewhere", true); }; -var setTracksEnabled = function(tracks, enabled) { - for (var i = 0; i < tracks.length; i++) { +let setTracksEnabled = function(tracks, enabled) { + for (let i = 0; i < tracks.length; i++) { tracks[i].enabled = enabled; } }; -var isTracksEnabled = function(tracks) { - for (var i = 0; i < tracks.length; i++) { +let isTracksEnabled = function(tracks) { + for (let i = 0; i < tracks.length; i++) { if (tracks[i].enabled) { return true; // at least one track is enabled } @@ -895,8 +887,8 @@ var isTracksEnabled = function(tracks) { return false; }; -var setState = function(self, state) { - var oldState = self.state; +let setState = function(self, state) { + let oldState = self.state; self.state = state; self.emit("state", state, oldState); }; @@ -908,11 +900,11 @@ var setState = function(self, state) { * @param {Object} content * @return {Promise} */ -var sendEvent = function(self, eventType, content) { +let sendEvent = function(self, eventType, content) { return self.client.sendEvent(self.roomId, eventType, content); }; -var sendCandidate = function(self, content) { +let 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); @@ -923,7 +915,7 @@ var sendCandidate = function(self, content) { } }; -var terminate = function(self, hangupParty, hangupReason, shouldEmit) { +let terminate = function(self, hangupParty, hangupReason, shouldEmit) { if (self.getRemoteVideoElement()) { if (self.getRemoteVideoElement().pause) { self.pauseElement(self.getRemoteVideoElement(), "remoteVideo"); @@ -954,7 +946,7 @@ var terminate = function(self, hangupParty, hangupReason, shouldEmit) { } }; -var stopAllMedia = function(self) { +let stopAllMedia = function(self) { debuglog("stopAllMedia (stream=%s)", self.localAVStream); if (self.localAVStream) { forAllTracksOnStream(self.localAVStream, function(t) { @@ -994,15 +986,15 @@ var stopAllMedia = function(self) { } }; -var _tryPlayRemoteStream = function(self) { +let _tryPlayRemoteStream = function(self) { if (self.getRemoteVideoElement() && self.remoteAVStream) { - var player = self.getRemoteVideoElement(); + let player = self.getRemoteVideoElement(); player.autoplay = true; self.assignElement(player, self.URL.createObjectURL(self.remoteAVStream), "remoteVideo"); setTimeout(function() { - var vel = self.getRemoteVideoElement(); + let vel = self.getRemoteVideoElement(); if (vel.play) { self.playElement(vel, "remoteVideo"); } @@ -1014,15 +1006,15 @@ var _tryPlayRemoteStream = function(self) { } }; -var _tryPlayRemoteAudioStream = function(self) { +let _tryPlayRemoteAudioStream = function(self) { if (self.getRemoteAudioElement() && self.remoteAStream) { - var player = self.getRemoteAudioElement(); + let player = self.getRemoteAudioElement(); player.autoplay = true; self.assignElement(player, self.URL.createObjectURL(self.remoteAStream), "remoteAudio"); setTimeout(function() { - var ael = self.getRemoteAudioElement(); + let ael = self.getRemoteAudioElement(); if (ael.play) { self.playElement(ael, "remoteAudio"); } @@ -1034,7 +1026,7 @@ var _tryPlayRemoteAudioStream = function(self) { } }; -var checkForErrorListener = function(self) { +let checkForErrorListener = function(self) { if (self.listeners("error").length === 0) { throw new Error( "You MUST attach an error listener using call.on('error', function() {})" @@ -1042,37 +1034,37 @@ var checkForErrorListener = function(self) { } }; -var callError = function(code, msg) { - var e = new Error(msg); +let callError = function(code, msg) { + let e = new Error(msg); e.code = code; return e; }; -var debuglog = function() { +let debuglog = function() { if (DEBUG) { - console.log.apply(console, arguments); + console.log(...arguments); } }; -var _sendCandidateQueue = function(self) { +let _sendCandidateQueue = function(self) { if (self.candidateSendQueue.length === 0) { return; } - var cands = self.candidateSendQueue; + let cands = self.candidateSendQueue; self.candidateSendQueue = []; ++self.candidateSendTries; - var content = { + let content = { version: 0, call_id: self.callId, - candidates: cands + candidates: cands, }; debuglog("Attempting to send " + cands.length + " candidates"); sendEvent(self, 'm.call.candidates', content).then(function() { self.candidateSendTries = 0; _sendCandidateQueue(self); }, function(error) { - for (var i = 0; i < cands.length; i++) { + for (let i = 0; i < cands.length; i++) { self.candidateSendQueue.push(cands[i]); } @@ -1085,7 +1077,7 @@ var _sendCandidateQueue = function(self) { return; } - var delayMs = 500 * Math.pow(2, self.candidateSendTries); + let delayMs = 500 * Math.pow(2, self.candidateSendTries); ++self.candidateSendTries; debuglog("Failed to send candidates. Retrying in " + delayMs + "ms"); setTimeout(function() { @@ -1094,7 +1086,7 @@ var _sendCandidateQueue = function(self) { }); }; -var _placeCallWithConstraints = function(self, constraints) { +let _placeCallWithConstraints = function(self, constraints) { self.client.callList[self.callId] = self; self.webRtc.getUserMedia( constraints, @@ -1106,24 +1098,24 @@ var _placeCallWithConstraints = function(self, constraints) { self.config = constraints; }; -var _createPeerConnection = function(self) { - var servers = self.turnServers; +let _createPeerConnection = function(self) { + let servers = self.turnServers; if (self.webRtc.vendor === "mozilla") { // modify turnServers struct to match what mozilla expects. servers = []; - for (var i = 0; i < self.turnServers.length; i++) { - for (var j = 0; j < self.turnServers[i].urls.length; j++) { + for (let i = 0; i < self.turnServers.length; i++) { + for (let j = 0; j < self.turnServers[i].urls.length; j++) { servers.push({ url: self.turnServers[i].urls[j], username: self.turnServers[i].username, - credential: self.turnServers[i].credential + credential: self.turnServers[i].credential, }); } } } - var pc = new self.webRtc.RtcPeerConnection({ - iceServers: servers + let pc = new self.webRtc.RtcPeerConnection({ + iceServers: servers, }); pc.oniceconnectionstatechange = hookCallback(self, self._onIceConnectionStateChanged); pc.onsignalingstatechange = hookCallback(self, self._onSignallingStateChanged); @@ -1132,8 +1124,8 @@ var _createPeerConnection = function(self) { return pc; }; -var _getChromeScreenSharingConstraints = function(call) { - var screen = global.screen; +let _getChromeScreenSharingConstraints = function(call) { + let screen = global.screen; if (!screen) { call.emit("error", callError( MatrixCall.ERR_NO_USER_MEDIA, @@ -1150,13 +1142,13 @@ var _getChromeScreenSharingConstraints = function(call) { maxWidth: screen.width, maxHeight: screen.height, minFrameRate: 1, - maxFrameRate: 10 - } - } + maxFrameRate: 10, + }, + }, }; }; -var _getUserMediaVideoContraints = function(callType) { +let _getUserMediaVideoContraints = function(callType) { switch (callType) { case 'voice': return ({audio: true, video: false}); @@ -1166,33 +1158,33 @@ var _getUserMediaVideoContraints = function(callType) { minWidth: 640, maxWidth: 640, minHeight: 360, - maxHeight: 360 - } + maxHeight: 360, + }, }}); } }; -var hookCallback = function(call, fn) { +let hookCallback = function(call, fn) { return function() { return fn.apply(call, arguments); }; }; -var forAllVideoTracksOnStream = function(s, f) { - var tracks = s.getVideoTracks(); - for (var i = 0; i < tracks.length; i++) { +let forAllVideoTracksOnStream = function(s, f) { + let tracks = s.getVideoTracks(); + for (let i = 0; i < tracks.length; i++) { f(tracks[i]); } }; -var forAllAudioTracksOnStream = function(s, f) { - var tracks = s.getAudioTracks(); - for (var i = 0; i < tracks.length; i++) { +let forAllAudioTracksOnStream = function(s, f) { + let tracks = s.getAudioTracks(); + for (let i = 0; i < tracks.length; i++) { f(tracks[i]); } }; -var forAllTracksOnStream = function(s, f) { +let forAllTracksOnStream = function(s, f) { forAllVideoTracksOnStream(s, f); forAllAudioTracksOnStream(s, f); }; @@ -1208,25 +1200,25 @@ module.exports.MatrixCall = MatrixCall; * @return {MatrixCall} the call or null if the browser doesn't support calling. */ module.exports.createNewMatrixCall = function(client, roomId) { - var w = global.window; - var doc = global.document; + let w = global.window; + let doc = global.document; if (!w || !doc) { return null; } - var webRtc = {}; + let webRtc = {}; webRtc.isOpenWebRTC = function() { - var scripts = doc.getElementById("script"); + let scripts = doc.getElementById("script"); if (!scripts || !scripts.length) { return false; } - for (var i = 0; i < scripts.length; i++) { + for (let i = 0; i < scripts.length; i++) { if (scripts[i].src.indexOf("owr.js") > -1) { return true; } } return false; }; - var getUserMedia = ( + let getUserMedia = ( w.navigator.getUserMedia || w.navigator.webkitGetUserMedia || w.navigator.mozGetUserMedia ); @@ -1248,23 +1240,21 @@ module.exports.createNewMatrixCall = function(client, roomId) { webRtc.vendor = null; if (w.mozRTCPeerConnection) { webRtc.vendor = "mozilla"; - } - else if (w.webkitRTCPeerConnection) { + } else if (w.webkitRTCPeerConnection) { webRtc.vendor = "webkit"; - } - else if (w.RTCPeerConnection) { + } else if (w.RTCPeerConnection) { webRtc.vendor = "generic"; } if (!webRtc.RtcIceCandidate || !webRtc.RtcSessionDescription || !webRtc.RtcPeerConnection || !webRtc.getUserMedia) { return null; // WebRTC is not supported. } - var opts = { + let opts = { webRtc: webRtc, client: client, URL: w.URL, roomId: roomId, - turnServers: client.getTurnServers() + turnServers: client.getTurnServers(), }; return new MatrixCall(opts); };