1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-11-28 05:03:59 +03:00

Merge branch 'matthew/warn-unknown-devices' of git+ssh://github.com/matrix-org/matrix-js-sdk into matthew/warn-unknown-devices

This commit is contained in:
Matthew Hodgson
2017-01-25 23:35:23 +01:00
45 changed files with 470 additions and 407 deletions

View File

@@ -1,4 +1,5 @@
module.exports = { module.exports = {
parser: "babel-eslint",
parserOptions: { parserOptions: {
ecmaVersion: 6, ecmaVersion: 6,
sourceType: "module", sourceType: "module",
@@ -18,6 +19,13 @@ module.exports = {
}], }],
curly: ["error", "multi-line"], curly: ["error", "multi-line"],
"prefer-const": ["error"], "prefer-const": ["error"],
"comma-dangle": ["error", {
arrays: "always-multiline",
objects: "always-multiline",
imports: "always-multiline",
exports: "always-multiline",
functions: "always-multiline",
}],
// loosen jsdoc requirements a little // loosen jsdoc requirements a little
"require-jsdoc": ["error", { "require-jsdoc": ["error", {
@@ -48,14 +56,12 @@ module.exports = {
// we set these to warnings, and assert that the number // we set these to warnings, and assert that the number
// of warnings doesn't exceed a given threshold // of warnings doesn't exceed a given threshold
"no-var": ["warn"], "no-var": ["warn"],
"comma-dangle": ["warn"], "brace-style": ["warn", "1tbs", {"allowSingleLine": true}],
"brace-style": ["warn"],
"prefer-rest-params": ["warn"], "prefer-rest-params": ["warn"],
"prefer-spread": ["warn"], "prefer-spread": ["warn"],
"one-var": ["warn"], "one-var": ["warn"],
"padded-blocks": ["warn"], "padded-blocks": ["warn"],
"no-extend-native": ["warn"], "no-extend-native": ["warn"],
"camelcase": ["warn"], "camelcase": ["warn"],
} }
} }

1
.gitignore vendored
View File

@@ -8,6 +8,7 @@ out
reports reports
/dist /dist
/lib /lib
/specbuild
# version file and tarball created by 'npm pack' # version file and tarball created by 'npm pack'
/git-revision.txt /git-revision.txt

View File

@@ -4,8 +4,9 @@
"description": "Matrix Client-Server SDK for Javascript", "description": "Matrix Client-Server SDK for Javascript",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test": "istanbul cover --report cobertura --config .istanbul.yml -i \"lib/**/*.js\" jasmine-node -- spec --verbose --junitreport --captureExceptions", "buildtest": "babel -s -d specbuild spec",
"check": "jasmine-node spec --verbose --junitreport --captureExceptions", "test": "npm run buildtest && istanbul cover --report cobertura --config .istanbul.yml -i \"lib/**/*.js\" jasmine-node -- specbuild --verbose --junitreport --captureExceptions",
"check": "npm run buildtest && jasmine-node specbuild --verbose --junitreport --captureExceptions",
"gendoc": "jsdoc -r lib -P package.json -R README.md -d .jsdoc", "gendoc": "jsdoc -r lib -P package.json -R README.md -d .jsdoc",
"start": "babel -s -w -d lib src", "start": "babel -s -w -d lib src",
"build": "babel -s -d lib src && rimraf dist && mkdir dist && browserify --exclude olm browser-index.js -o dist/browser-matrix.js --ignore-missing && uglifyjs -c -m -o dist/browser-matrix.min.js dist/browser-matrix.js", "build": "babel -s -d lib src && rimraf dist && mkdir dist && browserify --exclude olm browser-index.js -o dist/browser-matrix.js --ignore-missing && uglifyjs -c -m -o dist/browser-matrix.min.js dist/browser-matrix.js",
@@ -52,6 +53,7 @@
}, },
"devDependencies": { "devDependencies": {
"babel-cli": "^6.18.0", "babel-cli": "^6.18.0",
"babel-eslint": "^7.1.1",
"babel-preset-es2015": "^6.18.0", "babel-preset-es2015": "^6.18.0",
"eslint": "^3.13.1", "eslint": "^3.13.1",
"eslint-config-google": "^0.7.1", "eslint-config-google": "^0.7.1",

View File

@@ -304,7 +304,7 @@ function expectBobSendMessageRequest() {
function sendMessage(client) { function sendMessage(client) {
return client.sendMessage( return client.sendMessage(
roomId, {msgtype: "m.text", body: "Hello, World"} roomId, {msgtype: "m.text", body: "Hello, World"},
); );
} }
@@ -520,7 +520,7 @@ describe("MatrixClient crypto", function() {
// request again: should be no more requests // request again: should be no more requests
return aliClient.downloadKeys(['@bob:id']); return aliClient.downloadKeys(['@bob:id']);
}).nodeify(done); }).nodeify(done);
} },
); );
it("Bob uploads without one-time keys and with one-time keys", function(done) { it("Bob uploads without one-time keys and with one-time keys", function(done) {
@@ -583,7 +583,7 @@ describe("MatrixClient crypto", function() {
q.all( q.all(
aliClient.downloadKeys([bobUserId, eveUserId]), aliClient.downloadKeys([bobUserId, eveUserId]),
aliHttpBackend.flush("/keys/query", 1) aliHttpBackend.flush("/keys/query", 1),
).then(function() { ).then(function() {
// should get an empty list // should get an empty list
expect(aliClient.listDeviceKeys(bobUserId)).toEqual([]); expect(aliClient.listDeviceKeys(bobUserId)).toEqual([]);
@@ -618,7 +618,7 @@ describe("MatrixClient crypto", function() {
q.all( q.all(
aliClient.downloadKeys([bobUserId]), aliClient.downloadKeys([bobUserId]),
aliHttpBackend.flush("/keys/query", 1) aliHttpBackend.flush("/keys/query", 1),
).then(function() { ).then(function() {
// should get an empty list // should get an empty list
expect(aliClient.listDeviceKeys(bobUserId)).toEqual([]); expect(aliClient.listDeviceKeys(bobUserId)).toEqual([]);

View File

@@ -108,7 +108,7 @@ describe("MatrixClient events", function() {
SYNC_DATA.rooms.join["!erufh:bar"].timeline.events, SYNC_DATA.rooms.join["!erufh:bar"].timeline.events,
SYNC_DATA.rooms.join["!erufh:bar"].state.events, SYNC_DATA.rooms.join["!erufh:bar"].state.events,
NEXT_SYNC_DATA.rooms.join["!erufh:bar"].timeline.events, NEXT_SYNC_DATA.rooms.join["!erufh:bar"].timeline.events,
NEXT_SYNC_DATA.rooms.join["!erufh:bar"].ephemeral.events NEXT_SYNC_DATA.rooms.join["!erufh:bar"].ephemeral.events,
); );
client.on("event", function(event) { client.on("event", function(event) {
@@ -121,7 +121,7 @@ describe("MatrixClient events", function() {
} }
} }
expect(found).toBe( expect(found).toBe(
true, "Unexpected 'event' emitted: " + event.getType() true, "Unexpected 'event' emitted: " + event.getType(),
); );
}); });
@@ -129,7 +129,7 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() { httpBackend.flush().done(function() {
expect(expectedEvents.length).toEqual( expect(expectedEvents.length).toEqual(
0, "Failed to see all events from /sync calls" 0, "Failed to see all events from /sync calls",
); );
done(); done();
}); });
@@ -149,7 +149,7 @@ describe("MatrixClient events", function() {
expect(event.event).toEqual(SYNC_DATA.presence.events[0]); expect(event.event).toEqual(SYNC_DATA.presence.events[0]);
expect(user.presence).toEqual( expect(user.presence).toEqual(
SYNC_DATA.presence.events[0].content.presence SYNC_DATA.presence.events[0].content.presence,
); );
}); });
client.startClient(); client.startClient();
@@ -182,13 +182,13 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() { httpBackend.flush().done(function() {
expect(roomInvokeCount).toEqual( expect(roomInvokeCount).toEqual(
1, "Room fired wrong number of times." 1, "Room fired wrong number of times.",
); );
expect(roomNameInvokeCount).toEqual( expect(roomNameInvokeCount).toEqual(
1, "Room.name fired wrong number of times." 1, "Room.name fired wrong number of times.",
); );
expect(timelineFireCount).toEqual( expect(timelineFireCount).toEqual(
3, "Room.timeline fired the wrong number of times" 3, "Room.timeline fired the wrong number of times",
); );
done(); done();
}); });
@@ -208,7 +208,7 @@ describe("MatrixClient events", function() {
eventsInvokeCount++; eventsInvokeCount++;
const index = roomStateEventTypes.indexOf(event.getType()); const index = roomStateEventTypes.indexOf(event.getType());
expect(index).not.toEqual( expect(index).not.toEqual(
-1, "Unexpected room state event type: " + event.getType() -1, "Unexpected room state event type: " + event.getType(),
); );
if (index >= 0) { if (index >= 0) {
roomStateEventTypes.splice(index, 1); roomStateEventTypes.splice(index, 1);
@@ -231,13 +231,13 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() { httpBackend.flush().done(function() {
expect(membersInvokeCount).toEqual( expect(membersInvokeCount).toEqual(
1, "RoomState.members fired wrong number of times" 1, "RoomState.members fired wrong number of times",
); );
expect(newMemberInvokeCount).toEqual( expect(newMemberInvokeCount).toEqual(
1, "RoomState.newMember fired wrong number of times" 1, "RoomState.newMember fired wrong number of times",
); );
expect(eventsInvokeCount).toEqual( expect(eventsInvokeCount).toEqual(
2, "RoomState.events fired wrong number of times" 2, "RoomState.events fired wrong number of times",
); );
done(); done();
}); });
@@ -270,16 +270,16 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() { httpBackend.flush().done(function() {
expect(typingInvokeCount).toEqual( expect(typingInvokeCount).toEqual(
1, "RoomMember.typing fired wrong number of times" 1, "RoomMember.typing fired wrong number of times",
); );
expect(powerLevelInvokeCount).toEqual( expect(powerLevelInvokeCount).toEqual(
0, "RoomMember.powerLevel fired wrong number of times" 0, "RoomMember.powerLevel fired wrong number of times",
); );
expect(nameInvokeCount).toEqual( expect(nameInvokeCount).toEqual(
0, "RoomMember.name fired wrong number of times" 0, "RoomMember.name fired wrong number of times",
); );
expect(membershipInvokeCount).toEqual( expect(membershipInvokeCount).toEqual(
1, "RoomMember.membership fired wrong number of times" 1, "RoomMember.membership fired wrong number of times",
); );
done(); done();
}); });
@@ -297,7 +297,7 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() { httpBackend.flush().done(function() {
expect(sessionLoggedOutCount).toEqual( expect(sessionLoggedOutCount).toEqual(
1, "Session.logged_out fired wrong number of times" 1, "Session.logged_out fired wrong number of times",
); );
done(); done();
}); });

View File

@@ -118,7 +118,7 @@ describe("getEventTimeline support", function() {
accessToken: accessToken, accessToken: accessToken,
}); });
startClient(httpBackend, client startClient(httpBackend, client,
).then(function() { ).then(function() {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
@@ -136,7 +136,7 @@ describe("getEventTimeline support", function() {
timelineSupport: true, timelineSupport: true,
}); });
startClient(httpBackend, client startClient(httpBackend, client,
).then(function() { ).then(function() {
const room = client.getRoom(roomId); const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
@@ -159,7 +159,7 @@ describe("getEventTimeline support", function() {
}); });
let room; let room;
startClient(httpBackend, client startClient(httpBackend, client,
).then(function() { ).then(function() {
room = client.getRoom(roomId); room = client.getRoom(roomId);
@@ -343,7 +343,7 @@ describe("MatrixClient event timelines", function() {
}); });
client.on("sync", function() { client.on("sync", function() {
client.getEventTimeline(timelineSet, EVENTS[2].event_id client.getEventTimeline(timelineSet, EVENTS[2].event_id,
).then(function(tl) { ).then(function(tl) {
expect(tl.getEvents().length).toEqual(4); expect(tl.getEvents().length).toEqual(4);
expect(tl.getEvents()[0].event).toEqual(EVENTS[1]); expect(tl.getEvents()[0].event).toEqual(EVENTS[1]);
@@ -420,7 +420,7 @@ describe("MatrixClient event timelines", function() {
let tl0; let tl0;
let tl3; let tl3;
client.getEventTimeline(timelineSet, EVENTS[0].event_id client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl) { ).then(function(tl) {
expect(tl.getEvents().length).toEqual(1); expect(tl.getEvents().length).toEqual(1);
tl0 = tl; tl0 = tl;
@@ -470,7 +470,7 @@ describe("MatrixClient event timelines", function() {
}; };
}); });
client.getEventTimeline(timelineSet, "event1" client.getEventTimeline(timelineSet, "event1",
).then(function(tl) { ).then(function(tl) {
// could do with a fail() // could do with a fail()
expect(true).toBeFalsy(); expect(true).toBeFalsy();
@@ -514,7 +514,7 @@ describe("MatrixClient event timelines", function() {
}); });
let tl; let tl;
client.getEventTimeline(timelineSet, EVENTS[0].event_id client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) { ).then(function(tl0) {
tl = tl0; tl = tl0;
return client.paginateEventTimeline(tl, {backwards: true}); return client.paginateEventTimeline(tl, {backwards: true});
@@ -565,7 +565,7 @@ describe("MatrixClient event timelines", function() {
}); });
let tl; let tl;
client.getEventTimeline(timelineSet, EVENTS[0].event_id client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) { ).then(function(tl0) {
tl = tl0; tl = tl0;
return client.paginateEventTimeline( return client.paginateEventTimeline(

View File

@@ -44,7 +44,7 @@ describe("MatrixClient", function() {
const buf = new Buffer('hello world'); const buf = new Buffer('hello world');
it("should upload the file", function(done) { it("should upload the file", function(done) {
httpBackend.when( httpBackend.when(
"POST", "/_matrix/media/v1/upload" "POST", "/_matrix/media/v1/upload",
).check(function(req) { ).check(function(req) {
expect(req.data).toEqual(buf); expect(req.data).toEqual(buf);
expect(req.queryParams.filename).toEqual("hi.txt"); expect(req.queryParams.filename).toEqual("hi.txt");
@@ -80,7 +80,7 @@ describe("MatrixClient", function() {
it("should parse the response if rawResponse=false", function(done) { it("should parse the response if rawResponse=false", function(done) {
httpBackend.when( httpBackend.when(
"POST", "/_matrix/media/v1/upload" "POST", "/_matrix/media/v1/upload",
).check(function(req) { ).check(function(req) {
expect(req.opts.json).toBeFalsy(); expect(req.opts.json).toBeFalsy();
}).respond(200, JSON.stringify({ "content_uri": "uri" })); }).respond(200, JSON.stringify({ "content_uri": "uri" }));
@@ -101,7 +101,7 @@ describe("MatrixClient", function() {
it("should parse errors into a MatrixError", function(done) { it("should parse errors into a MatrixError", function(done) {
// opts.json is false, so request returns unparsed json. // opts.json is false, so request returns unparsed json.
httpBackend.when( httpBackend.when(
"POST", "/_matrix/media/v1/upload" "POST", "/_matrix/media/v1/upload",
).check(function(req) { ).check(function(req) {
expect(req.data).toEqual(buf); expect(req.data).toEqual(buf);
expect(req.opts.json).toBeFalsy(); expect(req.opts.json).toBeFalsy();
@@ -188,7 +188,7 @@ describe("MatrixClient", function() {
}; };
httpBackend.when( httpBackend.when(
"GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId "GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId,
).respond(200, httpFilterDefinition); ).respond(200, httpFilterDefinition);
const storeFilter = Filter.fromJson(userId, filterId, { const storeFilter = Filter.fromJson(userId, filterId, {
@@ -211,7 +211,7 @@ describe("MatrixClient", function() {
expect(store.getFilter(userId, filterId)).toBeNull(); expect(store.getFilter(userId, filterId)).toBeNull();
httpBackend.when( httpBackend.when(
"GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId "GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId,
).respond(200, httpFilterDefinition); ).respond(200, httpFilterDefinition);
client.getFilter(userId, filterId, true).done(function(gotFilter) { client.getFilter(userId, filterId, true).done(function(gotFilter) {
expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition); expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition);
@@ -234,7 +234,7 @@ describe("MatrixClient", function() {
}; };
httpBackend.when( httpBackend.when(
"POST", "/user/" + encodeURIComponent(userId) + "/filter" "POST", "/user/" + encodeURIComponent(userId) + "/filter",
).check(function(req) { ).check(function(req) {
expect(req.data).toEqual(filterDefinition); expect(req.data).toEqual(filterDefinition);
}).respond(200, { }).respond(200, {
@@ -379,13 +379,13 @@ describe("MatrixClient", function() {
const auth = {a: 1}; const auth = {a: 1};
it("should pass through an auth dict", function(done) { it("should pass through an auth dict", function(done) {
httpBackend.when( httpBackend.when(
"DELETE", "/_matrix/client/unstable/devices/my_device" "DELETE", "/_matrix/client/unstable/devices/my_device",
).check(function(req) { ).check(function(req) {
expect(req.data).toEqual({auth: auth}); expect(req.data).toEqual({auth: auth});
}).respond(200); }).respond(200);
client.deleteDevice( client.deleteDevice(
"my_device", auth "my_device", auth,
).catch(utils.failTest).done(done); ).catch(utils.failTest).done(done);
httpBackend.flush(); httpBackend.flush();

View File

@@ -97,10 +97,10 @@ describe("MatrixClient opts", function() {
]; ];
client.on("event", function(event) { client.on("event", function(event) {
expect(expectedEventTypes.indexOf(event.getType())).not.toEqual( expect(expectedEventTypes.indexOf(event.getType())).not.toEqual(
-1, "Recv unexpected event type: " + event.getType() -1, "Recv unexpected event type: " + event.getType(),
); );
expectedEventTypes.splice( expectedEventTypes.splice(
expectedEventTypes.indexOf(event.getType()), 1 expectedEventTypes.indexOf(event.getType()), 1,
); );
}); });
httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("GET", "/pushrules").respond(200, {});
@@ -113,7 +113,7 @@ describe("MatrixClient opts", function() {
return httpBackend.flush("/sync", 1); return httpBackend.flush("/sync", 1);
}).done(function() { }).done(function() {
expect(expectedEventTypes.length).toEqual( expect(expectedEventTypes.length).toEqual(
0, "Expected to see event types: " + expectedEventTypes 0, "Expected to see event types: " + expectedEventTypes,
); );
done(); done();
}); });

View File

@@ -82,7 +82,7 @@ describe("MatrixClient room timelines", function() {
if (e.__prev_event === undefined) { if (e.__prev_event === undefined) {
throw new Error( throw new Error(
"setNextSyncData needs the prev state set to '__prev_event' " + "setNextSyncData needs the prev state set to '__prev_event' " +
"for " + e.type "for " + e.type,
); );
} }
if (e.__prev_event !== null) { if (e.__prev_event !== null) {
@@ -409,10 +409,10 @@ describe("MatrixClient room timelines", function() {
expect(index).toEqual(2); expect(index).toEqual(2);
expect(room.timeline.length).toEqual(3); expect(room.timeline.length).toEqual(3);
expect(room.timeline[2].event).toEqual( expect(room.timeline[2].event).toEqual(
eventData[1] eventData[1],
); );
expect(room.timeline[1].event).toEqual( expect(room.timeline[1].event).toEqual(
eventData[0] eventData[0],
); );
}).catch(utils.failTest).done(done); }).catch(utils.failTest).done(done);
}); });
@@ -510,11 +510,11 @@ describe("MatrixClient room timelines", function() {
expect(room.currentState.getMembers().length).toEqual(4); expect(room.currentState.getMembers().length).toEqual(4);
expect(room.currentState.getMember(userC).name).toEqual("C"); expect(room.currentState.getMember(userC).name).toEqual("C");
expect(room.currentState.getMember(userC).membership).toEqual( expect(room.currentState.getMember(userC).membership).toEqual(
"join" "join",
); );
expect(room.currentState.getMember(userD).name).toEqual(userD); expect(room.currentState.getMember(userD).name).toEqual(userD);
expect(room.currentState.getMember(userD).membership).toEqual( expect(room.currentState.getMember(userD).membership).toEqual(
"invite" "invite",
); );
}).catch(utils.failTest).done(done); }).catch(utils.failTest).done(done);
}); });
@@ -543,11 +543,11 @@ describe("MatrixClient room timelines", function() {
expect(room.currentState.getMembers().length).toEqual(2); expect(room.currentState.getMembers().length).toEqual(2);
expect(room.currentState.getMember(userId).name).toEqual(userName); expect(room.currentState.getMember(userId).name).toEqual(userName);
expect(room.currentState.getMember(userId).membership).toEqual( expect(room.currentState.getMember(userId).membership).toEqual(
"join" "join",
); );
expect(room.currentState.getMember(otherUserId).name).toEqual("Bob"); expect(room.currentState.getMember(otherUserId).name).toEqual("Bob");
expect(room.currentState.getMember(otherUserId).membership).toEqual( expect(room.currentState.getMember(otherUserId).membership).toEqual(
"join" "join",
); );
done(); done();
}); });

View File

@@ -114,7 +114,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push( syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({ utils.mkMembership({
room: roomOne, mship: "invite", user: userC, room: roomOne, mship: "invite", user: userC,
}) }),
); );
httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -122,7 +122,7 @@ describe("MatrixClient syncing", function() {
200, { 200, {
avatar_url: "mxc://flibble/wibble", avatar_url: "mxc://flibble/wibble",
displayname: "The Boss", displayname: "The Boss",
} },
); );
client.startClient({ client.startClient({
@@ -133,7 +133,7 @@ describe("MatrixClient syncing", function() {
const member = client.getRoom(roomOne).getMember(userC); const member = client.getRoom(roomOne).getMember(userC);
expect(member.name).toEqual("The Boss"); expect(member.name).toEqual("The Boss");
expect( expect(
member.getAvatarUrl("home.server.url", null, null, null, false) member.getAvatarUrl("home.server.url", null, null, null, false),
).toBeDefined(); ).toBeDefined();
done(); done();
}); });
@@ -148,7 +148,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push( syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({ utils.mkMembership({
room: roomOne, mship: "invite", user: userC, room: roomOne, mship: "invite", user: userC,
}) }),
); );
httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -173,7 +173,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push( syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({ utils.mkMembership({
room: roomOne, mship: "invite", user: userC, room: roomOne, mship: "invite", user: userC,
}) }),
); );
httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -199,7 +199,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push( syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({ utils.mkMembership({
room: roomOne, mship: "invite", user: userC, room: roomOne, mship: "invite", user: userC,
}) }),
); );
httpBackend.when("GET", "/sync").respond(200, syncData); httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -210,7 +210,7 @@ describe("MatrixClient syncing", function() {
const member = client.getRoom(roomOne).getMember(userC); const member = client.getRoom(roomOne).getMember(userC);
expect(member.name).toEqual(userC); expect(member.name).toEqual(userC);
expect( expect(
member.getAvatarUrl("home.server.url", null, null, null, false) member.getAvatarUrl("home.server.url", null, null, null, false),
).toBeNull(); ).toBeNull();
done(); done();
}); });
@@ -362,7 +362,7 @@ describe("MatrixClient syncing", function() {
const room = client.getRoom(roomOne); const room = client.getRoom(roomOne);
// should have clobbered the name to the one from /events // should have clobbered the name to the one from /events
expect(room.name).toEqual( expect(room.name).toEqual(
nextSyncData.rooms.join[roomOne].state.events[0].content.name nextSyncData.rooms.join[roomOne].state.events[0].content.name,
); );
done(); done();
}); });

View File

@@ -97,7 +97,10 @@ TestClient.prototype.start = function(existingDevices) {
}}; }};
}); });
this.client.startClient(); this.client.startClient({
// set this so that we can get hold of failed events
pendingEventOrdering: 'detached',
});
return this.httpBackend.flush(); return this.httpBackend.flush();
}; };
@@ -143,7 +146,7 @@ function createOlmSession(olmAccount, recipientTestClient) {
const session = new Olm.Session(); const session = new Olm.Session();
session.create_outbound( session.create_outbound(
olmAccount, recipientTestClient.getDeviceKey(), otk.key olmAccount, recipientTestClient.getDeviceKey(), otk.key,
); );
return session; return session;
} }
@@ -287,7 +290,7 @@ function getSyncResponse(roomMembers) {
testUtils.mkMembership({ testUtils.mkMembership({
mship: 'join', mship: 'join',
sender: roomMembers[i], sender: roomMembers[i],
}) }),
); );
} }
@@ -384,7 +387,7 @@ describe("megolm", function() {
testUtils.beforeEach(this); // eslint-disable-line no-invalid-this testUtils.beforeEach(this); // eslint-disable-line no-invalid-this
aliceTestClient = new TestClient( aliceTestClient = new TestClient(
"@alice:localhost", "xzcvb", "akjgkrgjs" "@alice:localhost", "xzcvb", "akjgkrgjs",
); );
testOlmAccount = new Olm.Account(); testOlmAccount = new Olm.Account();
@@ -533,13 +536,26 @@ describe("megolm", function() {
aliceTestClient.httpBackend.when('GET', '/sync').respond(200, syncResponse); aliceTestClient.httpBackend.when('GET', '/sync').respond(200, syncResponse);
return aliceTestClient.httpBackend.flush('/sync', 1); return aliceTestClient.httpBackend.flush('/sync', 1);
}).then(function() { }).then(function() {
let inboundGroupSession; // start out with the device unknown - the send should be rejected.
aliceTestClient.httpBackend.when('POST', '/keys/query').respond( aliceTestClient.httpBackend.when('POST', '/keys/query').respond(
200, getTestKeysQueryResponse('@bob:xyz') 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return q.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test').then(() => {
throw new Error("sendTextMessage failed on an unknown device");
}, (e) => {
expect(e.name).toEqual("UnknownDeviceError");
}),
aliceTestClient.httpBackend.flush(),
]);
}).then(function() {
// mark the device as known, and resend.
aliceTestClient.client.setDeviceKnown('@bob:xyz', 'DEVICE_ID');
let inboundGroupSession;
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/sendToDevice/m.room.encrypted/' 'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
const m = content.messages['@bob:xyz'].DEVICE_ID; const m = content.messages['@bob:xyz'].DEVICE_ID;
const ct = m.ciphertext[testSenderKey]; const ct = m.ciphertext[testSenderKey];
@@ -552,7 +568,7 @@ describe("megolm", function() {
}); });
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
const ct = content.ciphertext; const ct = content.ciphertext;
const r = inboundGroupSession.decrypt(ct); const r = inboundGroupSession.decrypt(ct);
@@ -568,8 +584,11 @@ describe("megolm", function() {
}; };
}); });
const room = aliceTestClient.client.getRoom(ROOM_ID);
const pendingMsg = room.getPendingEvents()[0];
return q.all([ return q.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'), aliceTestClient.client.resendEvent(pendingMsg, room),
aliceTestClient.httpBackend.flush(), aliceTestClient.httpBackend.flush(),
]); ]);
}).nodeify(done); }).nodeify(done);
@@ -598,7 +617,7 @@ describe("megolm", function() {
console.log("Telling alice to send a megolm message"); console.log("Telling alice to send a megolm message");
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, { ).respond(200, {
event_id: '$event_id', event_id: '$event_id',
}); });
@@ -632,7 +651,7 @@ describe("megolm", function() {
console.log('Forcing alice to download our device keys'); console.log('Forcing alice to download our device keys');
aliceTestClient.httpBackend.when('POST', '/keys/query').respond( aliceTestClient.httpBackend.when('POST', '/keys/query').respond(
200, getTestKeysQueryResponse('@bob:xyz') 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return q.all([ return q.all([
@@ -645,7 +664,7 @@ describe("megolm", function() {
console.log('Telling alice to send a megolm message'); console.log('Telling alice to send a megolm message');
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, { ).respond(200, {
event_id: '$event_id', event_id: '$event_id',
}); });
@@ -678,14 +697,23 @@ describe("megolm", function() {
return aliceTestClient.httpBackend.flush('/sync', 1); return aliceTestClient.httpBackend.flush('/sync', 1);
}).then(function() { }).then(function() {
console.log('Telling alice to send a megolm message'); console.log("Fetching bob's devices and marking known");
aliceTestClient.httpBackend.when('POST', '/keys/query').respond( aliceTestClient.httpBackend.when('POST', '/keys/query').respond(
200, getTestKeysQueryResponse('@bob:xyz') 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return q.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flush(),
]).then((keys) => {
aliceTestClient.client.setDeviceKnown('@bob:xyz', 'DEVICE_ID');
});
}).then(function() {
console.log('Telling alice to send a megolm message');
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/sendToDevice/m.room.encrypted/' 'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
console.log('sendToDevice: ', content); console.log('sendToDevice: ', content);
const m = content.messages['@bob:xyz'].DEVICE_ID; const m = content.messages['@bob:xyz'].DEVICE_ID;
@@ -699,7 +727,7 @@ describe("megolm", function() {
}); });
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
console.log('/send:', content); console.log('/send:', content);
expect(content.session_id).toEqual(megolmSessionId); expect(content.session_id).toEqual(megolmSessionId);
@@ -718,7 +746,7 @@ describe("megolm", function() {
console.log('Telling alice to send another megolm message'); console.log('Telling alice to send another megolm message');
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
console.log('/send:', content); console.log('/send:', content);
expect(content.session_id).not.toEqual(megolmSessionId); expect(content.session_id).not.toEqual(megolmSessionId);
@@ -737,14 +765,14 @@ describe("megolm", function() {
// https://github.com/vector-im/riot-web/issues/2676 // https://github.com/vector-im/riot-web/issues/2676
it("Alice should send to her other devices", function(done) { it("Alice should send to her other devices", function(done) {
// for this test, we make the testOlmAccount be another of Alice's devices. // for this test, we make the testOlmAccount be another of Alice's devices.
// it ought to get include in messages Alice sends. // it ought to get included in messages Alice sends.
let p2pSession; let p2pSession;
let inboundGroupSession; let inboundGroupSession;
let decrypted; let decrypted;
return aliceTestClient.start( return aliceTestClient.start(
getTestKeysQueryResponse(aliceTestClient.userId) getTestKeysQueryResponse(aliceTestClient.userId),
).then(function() { ).then(function() {
// an encrypted room with just alice // an encrypted room with just alice
const syncResponse = { const syncResponse = {
@@ -774,6 +802,7 @@ describe("megolm", function() {
return aliceTestClient.httpBackend.flush(); return aliceTestClient.httpBackend.flush();
}).then(function() { }).then(function() {
aliceTestClient.client.setDeviceKnown(aliceTestClient.userId, 'DEVICE_ID');
aliceTestClient.httpBackend.when('POST', '/keys/claim').respond( aliceTestClient.httpBackend.when('POST', '/keys/claim').respond(
200, function(path, content) { 200, function(path, content) {
expect(content.one_time_keys[aliceTestClient.userId].DEVICE_ID) expect(content.one_time_keys[aliceTestClient.userId].DEVICE_ID)
@@ -782,7 +811,7 @@ describe("megolm", function() {
}); });
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/sendToDevice/m.room.encrypted/' 'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
console.log("sendToDevice: ", content); console.log("sendToDevice: ", content);
const m = content.messages[aliceTestClient.userId].DEVICE_ID; const m = content.messages[aliceTestClient.userId].DEVICE_ID;
@@ -800,7 +829,7 @@ describe("megolm", function() {
}); });
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
const ct = content.ciphertext; const ct = content.ciphertext;
const r = inboundGroupSession.decrypt(ct); const r = inboundGroupSession.decrypt(ct);
@@ -832,7 +861,7 @@ describe("megolm", function() {
let sendPromise; let sendPromise;
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/sendToDevice/m.room.encrypted/' 'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
const m = content.messages['@bob:xyz'].DEVICE_ID; const m = content.messages['@bob:xyz'].DEVICE_ID;
const ct = m.ciphertext[testSenderKey]; const ct = m.ciphertext[testSenderKey];
@@ -845,7 +874,7 @@ describe("megolm", function() {
}); });
aliceTestClient.httpBackend.when( aliceTestClient.httpBackend.when(
'PUT', '/send/' 'PUT', '/send/',
).respond(200, function(path, content) { ).respond(200, function(path, content) {
const ct = content.ciphertext; const ct = content.ciphertext;
const r = inboundGroupSession.decrypt(ct); const r = inboundGroupSession.decrypt(ct);
@@ -882,12 +911,17 @@ describe("megolm", function() {
// this will block // this will block
downloadPromise = aliceTestClient.client.downloadKeys(['@bob:xyz']); downloadPromise = aliceTestClient.client.downloadKeys(['@bob:xyz']);
}).then(function() {
// so will this. // so will this.
sendPromise = aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'); sendPromise = aliceTestClient.client.sendTextMessage(ROOM_ID, 'test')
}).then(function() { .then(() => {
throw new Error("sendTextMessage failed on an unknown device");
}, (e) => {
expect(e.name).toEqual("UnknownDeviceError");
});
aliceTestClient.httpBackend.when('POST', '/keys/query').respond( aliceTestClient.httpBackend.when('POST', '/keys/query').respond(
200, getTestKeysQueryResponse('@bob:xyz') 200, getTestKeysQueryResponse('@bob:xyz'),
); );
return aliceTestClient.httpBackend.flush(); return aliceTestClient.httpBackend.flush();
@@ -902,7 +936,7 @@ describe("megolm", function() {
return aliceTestClient.start().then(() => { return aliceTestClient.start().then(() => {
const p2pSession = createOlmSession( const p2pSession = createOlmSession(
testOlmAccount, aliceTestClient testOlmAccount, aliceTestClient,
); );
const groupSession = new Olm.OutboundGroupSession(); const groupSession = new Olm.OutboundGroupSession();
@@ -953,7 +987,7 @@ describe("megolm", function() {
aliceTestClient.stop(); aliceTestClient.stop();
aliceTestClient = new TestClient( aliceTestClient = new TestClient(
"@alice:localhost", "device2", "access_token2" "@alice:localhost", "device2", "access_token2",
); );
aliceTestClient.client.importRoomKeys(exported); aliceTestClient.client.importRoomKeys(exported);

View File

@@ -43,13 +43,13 @@ HttpBackend.prototype = {
let flushed = 0; let flushed = 0;
let triedWaiting = false; let triedWaiting = false;
console.log( console.log(
"HTTP backend flushing... (path=%s numToFlush=%s)", path, numToFlush "HTTP backend flushing... (path=%s numToFlush=%s)", path, numToFlush,
); );
const tryFlush = function() { const tryFlush = function() {
// if there's more real requests and more expected requests, flush 'em. // if there's more real requests and more expected requests, flush 'em.
console.log( console.log(
" trying to flush queue => reqs=%s expected=%s [%s]", " trying to flush queue => reqs=%s expected=%s [%s]",
self.requests.length, self.expectedRequests.length, path self.requests.length, self.expectedRequests.length, path,
); );
if (self._takeFromQueue(path)) { if (self._takeFromQueue(path)) {
// try again on the next tick. // try again on the next tick.
@@ -122,7 +122,7 @@ HttpBackend.prototype = {
body = body(req.path, req.data); body = body(req.path, req.data);
} }
req.callback( req.callback(
testResponse.err, testResponse.response, body testResponse.err, testResponse.response, body,
); );
matchingReq = null; matchingReq = null;
} }
@@ -140,7 +140,7 @@ HttpBackend.prototype = {
const firstOutstandingReq = this.requests[0] || {}; const firstOutstandingReq = this.requests[0] || {};
expect(this.requests.length).toEqual(0, expect(this.requests.length).toEqual(0,
"Expected no more HTTP requests but received request to " + "Expected no more HTTP requests but received request to " +
firstOutstandingReq.path firstOutstandingReq.path,
); );
}, },
@@ -150,7 +150,7 @@ HttpBackend.prototype = {
verifyNoOutstandingExpectation: function() { verifyNoOutstandingExpectation: function() {
const firstOutstandingExpectation = this.expectedRequests[0] || {}; const firstOutstandingExpectation = this.expectedRequests[0] || {};
expect(this.expectedRequests.length).toEqual(0, expect(this.expectedRequests.length).toEqual(0,
"Expected to see HTTP request for " + firstOutstandingExpectation.path "Expected to see HTTP request for " + firstOutstandingExpectation.path,
); );
}, },

View File

@@ -14,8 +14,8 @@ describe("ContentRepo", function() {
const httpUrl = "http://example.com/image.jpeg"; const httpUrl = "http://example.com/image.jpeg";
expect( expect(
ContentRepo.getHttpUriForMxc( ContentRepo.getHttpUriForMxc(
baseUrl, httpUrl, undefined, undefined, undefined, true baseUrl, httpUrl, undefined, undefined, undefined, true,
) ),
).toEqual(httpUrl); ).toEqual(httpUrl);
}); });
@@ -28,7 +28,7 @@ describe("ContentRepo", function() {
function() { function() {
const mxcUri = "mxc://server.name/resourceid"; const mxcUri = "mxc://server.name/resourceid";
expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri)).toEqual( expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri)).toEqual(
baseUrl + "/_matrix/media/v1/download/server.name/resourceid" baseUrl + "/_matrix/media/v1/download/server.name/resourceid",
); );
}); });
@@ -41,7 +41,7 @@ describe("ContentRepo", function() {
const mxcUri = "mxc://server.name/resourceid"; const mxcUri = "mxc://server.name/resourceid";
expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32, 64, "crop")).toEqual( expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32, 64, "crop")).toEqual(
baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" + baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" +
"?width=32&height=64&method=crop" "?width=32&height=64&method=crop",
); );
}); });
@@ -50,7 +50,7 @@ describe("ContentRepo", function() {
const mxcUri = "mxc://server.name/resourceid#automade"; const mxcUri = "mxc://server.name/resourceid#automade";
expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32)).toEqual( expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32)).toEqual(
baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" + baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" +
"?width=32#automade" "?width=32#automade",
); );
}); });
@@ -58,7 +58,7 @@ describe("ContentRepo", function() {
function() { function() {
const mxcUri = "mxc://server.name/resourceid#automade"; const mxcUri = "mxc://server.name/resourceid#automade";
expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri)).toEqual( expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri)).toEqual(
baseUrl + "/_matrix/media/v1/download/server.name/resourceid#automade" baseUrl + "/_matrix/media/v1/download/server.name/resourceid#automade",
); );
}); });
}); });
@@ -71,21 +71,21 @@ describe("ContentRepo", function() {
it("should set w/h by default to 96", function() { it("should set w/h by default to 96", function() {
expect(ContentRepo.getIdenticonUri(baseUrl, "foobar")).toEqual( expect(ContentRepo.getIdenticonUri(baseUrl, "foobar")).toEqual(
baseUrl + "/_matrix/media/v1/identicon/foobar" + baseUrl + "/_matrix/media/v1/identicon/foobar" +
"?width=96&height=96" "?width=96&height=96",
); );
}); });
it("should be able to set custom w/h", function() { it("should be able to set custom w/h", function() {
expect(ContentRepo.getIdenticonUri(baseUrl, "foobar", 32, 64)).toEqual( expect(ContentRepo.getIdenticonUri(baseUrl, "foobar", 32, 64)).toEqual(
baseUrl + "/_matrix/media/v1/identicon/foobar" + baseUrl + "/_matrix/media/v1/identicon/foobar" +
"?width=32&height=64" "?width=32&height=64",
); );
}); });
it("should URL encode the identicon string", function() { it("should URL encode the identicon string", function() {
expect(ContentRepo.getIdenticonUri(baseUrl, "foo#bar", 32, 64)).toEqual( expect(ContentRepo.getIdenticonUri(baseUrl, "foo#bar", 32, 64)).toEqual(
baseUrl + "/_matrix/media/v1/identicon/foo%23bar" + baseUrl + "/_matrix/media/v1/identicon/foo%23bar" +
"?width=32&height=64" "?width=32&height=64",
); );
}); });
}); });

View File

@@ -52,10 +52,10 @@ describe("EventTimeline", function() {
]; ];
timeline.initialiseState(events); timeline.initialiseState(events);
expect(timeline._startState.setStateEvents).toHaveBeenCalledWith( expect(timeline._startState.setStateEvents).toHaveBeenCalledWith(
events events,
); );
expect(timeline._endState.setStateEvents).toHaveBeenCalledWith( expect(timeline._endState.setStateEvents).toHaveBeenCalledWith(
events events,
); );
}); });

View File

@@ -75,7 +75,7 @@ describe("MatrixClient", function() {
expect(false).toBe( expect(false).toBe(
true, ">1 pending request. You should probably handle them. " + true, ">1 pending request. You should probably handle them. " +
"PENDING: " + JSON.stringify(pendingLookup) + " JUST GOT: " + "PENDING: " + JSON.stringify(pendingLookup) + " JUST GOT: " +
method + " " + path method + " " + path,
); );
} }
pendingLookup = { pendingLookup = {
@@ -88,7 +88,7 @@ describe("MatrixClient", function() {
if (next.path === path && next.method === method) { if (next.path === path && next.method === method) {
console.log( console.log(
"MatrixClient[UT] Matched. Returning " + "MatrixClient[UT] Matched. Returning " +
(next.error ? "BAD" : "GOOD") + " response" (next.error ? "BAD" : "GOOD") + " response",
); );
if (next.expectBody) { if (next.expectBody) {
expect(next.expectBody).toEqual(data); expect(next.expectBody).toEqual(data);
@@ -290,7 +290,7 @@ describe("MatrixClient", function() {
if (state === "ERROR" && httpLookups.length > 0) { if (state === "ERROR" && httpLookups.length > 0) {
expect(httpLookups.length).toEqual(1); expect(httpLookups.length).toEqual(1);
expect(client.retryImmediately()).toBe( expect(client.retryImmediately()).toBe(
true, "retryImmediately returned false" true, "retryImmediately returned false",
); );
jasmine.Clock.tick(1); jasmine.Clock.tick(1);
} else if (state === "RECONNECTING" && httpLookups.length > 0) { } else if (state === "RECONNECTING" && httpLookups.length > 0) {
@@ -334,7 +334,7 @@ describe("MatrixClient", function() {
return function syncListener(state, old) { return function syncListener(state, old) {
const expected = expectedStates.shift(); const expected = expectedStates.shift();
console.log( console.log(
"'sync' curr=%s old=%s EXPECT=%s", state, old, expected "'sync' curr=%s old=%s EXPECT=%s", state, old, expected,
); );
if (!expected) { if (!expected) {
done(); done();

View File

@@ -210,10 +210,10 @@ describe("RoomState", function() {
state.setStateEvents([powerLevelEvent]); state.setStateEvents([powerLevelEvent]);
expect(state.members[userA].setPowerLevelEvent).toHaveBeenCalledWith( expect(state.members[userA].setPowerLevelEvent).toHaveBeenCalledWith(
powerLevelEvent powerLevelEvent,
); );
expect(state.members[userB].setPowerLevelEvent).toHaveBeenCalledWith( expect(state.members[userB].setPowerLevelEvent).toHaveBeenCalledWith(
powerLevelEvent powerLevelEvent,
); );
}); });
@@ -254,7 +254,7 @@ describe("RoomState", function() {
expect(state.members[userA].setMembershipEvent).not.toHaveBeenCalled(); expect(state.members[userA].setMembershipEvent).not.toHaveBeenCalled();
expect(state.members[userB].setMembershipEvent).toHaveBeenCalledWith( expect(state.members[userB].setMembershipEvent).toHaveBeenCalledWith(
memberEvent, state memberEvent, state,
); );
}); });
}); });
@@ -272,10 +272,10 @@ describe("RoomState", function() {
state.setTypingEvent(typingEvent); state.setTypingEvent(typingEvent);
expect(state.members[userA].setTypingEvent).toHaveBeenCalledWith( expect(state.members[userA].setTypingEvent).toHaveBeenCalledWith(
typingEvent typingEvent,
); );
expect(state.members[userB].setTypingEvent).toHaveBeenCalledWith( expect(state.members[userB].setTypingEvent).toHaveBeenCalledWith(
typingEvent typingEvent,
); );
}); });
}); });
@@ -284,7 +284,7 @@ describe("RoomState", function() {
it("should say non-joined members may not send state", it("should say non-joined members may not send state",
function() { function() {
expect(state.maySendStateEvent( expect(state.maySendStateEvent(
'm.room.name', "@nobody:nowhere" 'm.room.name', "@nobody:nowhere",
)).toEqual(false); )).toEqual(false);
}); });
@@ -367,7 +367,7 @@ describe("RoomState", function() {
it("should say non-joined members may not send events", it("should say non-joined members may not send events",
function() { function() {
expect(state.maySendEvent( expect(state.maySendEvent(
'm.room.message', "@nobody:nowhere" 'm.room.message', "@nobody:nowhere",
)).toEqual(false); )).toEqual(false);
expect(state.maySendMessage("@nobody:nowhere")).toEqual(false); expect(state.maySendMessage("@nobody:nowhere")).toEqual(false);
}); });

View File

@@ -163,10 +163,10 @@ describe("Room", function() {
]; ];
room.addLiveEvents(events); room.addLiveEvents(events);
expect(room.currentState.setStateEvents).toHaveBeenCalledWith( expect(room.currentState.setStateEvents).toHaveBeenCalledWith(
[events[0]] [events[0]],
); );
expect(room.currentState.setStateEvents).toHaveBeenCalledWith( expect(room.currentState.setStateEvents).toHaveBeenCalledWith(
[events[1]] [events[1]],
); );
expect(events[0].forwardLooking).toBe(true); expect(events[0].forwardLooking).toBe(true);
expect(events[1].forwardLooking).toBe(true); expect(events[1].forwardLooking).toBe(true);
@@ -222,7 +222,7 @@ describe("Room", function() {
break; break;
} }
callCount += 1; callCount += 1;
} },
); );
// first add the local echo // first add the local echo
@@ -368,10 +368,10 @@ describe("Room", function() {
room.addEventsToTimeline(events, true, room.getLiveTimeline()); room.addEventsToTimeline(events, true, room.getLiveTimeline());
expect(room.oldState.setStateEvents).toHaveBeenCalledWith( expect(room.oldState.setStateEvents).toHaveBeenCalledWith(
[events[0]] [events[0]],
); );
expect(room.oldState.setStateEvents).toHaveBeenCalledWith( expect(room.oldState.setStateEvents).toHaveBeenCalledWith(
[events[1]] [events[1]],
); );
expect(events[0].forwardLooking).toBe(false); expect(events[0].forwardLooking).toBe(false);
expect(events[1].forwardLooking).toBe(false); expect(events[1].forwardLooking).toBe(false);
@@ -680,7 +680,7 @@ describe("Room", function() {
}); });
room.currentState.getMember.andCallFake(function(userId) { room.currentState.getMember.andCallFake(function(userId) {
const memberEvent = room.currentState.getStateEvents( const memberEvent = room.currentState.getStateEvents(
"m.room.member", userId "m.room.member", userId,
); );
return { return {
name: memberEvent.event.content && name: memberEvent.event.content &&
@@ -1003,7 +1003,7 @@ describe("Room", function() {
mkRecord(eventToAck.getId(), "m.read", userD, ts), mkRecord(eventToAck.getId(), "m.read", userD, ts),
])); ]));
expect(room.getUsersReadUpTo(eventToAck)).toEqual( expect(room.getUsersReadUpTo(eventToAck)).toEqual(
[userB, userC, userD] [userB, userC, userD],
); );
}); });
@@ -1164,10 +1164,10 @@ describe("Room", function() {
room.addPendingEvent(eventB, "TXN1"); room.addPendingEvent(eventB, "TXN1");
room.addLiveEvents([eventC]); room.addLiveEvents([eventC]);
expect(room.timeline).toEqual( expect(room.timeline).toEqual(
[eventA, eventC] [eventA, eventC],
); );
expect(room.getPendingEvents()).toEqual( expect(room.getPendingEvents()).toEqual(
[eventB] [eventB],
); );
}); });
@@ -1190,7 +1190,7 @@ describe("Room", function() {
room.addPendingEvent(eventB, "TXN1"); room.addPendingEvent(eventB, "TXN1");
room.addLiveEvents([eventC]); room.addLiveEvents([eventC]);
expect(room.timeline).toEqual( expect(room.timeline).toEqual(
[eventA, eventB, eventC] [eventA, eventB, eventC],
); );
}); });
}); });
@@ -1208,7 +1208,7 @@ describe("Room", function() {
room.addPendingEvent(eventA, "TXN1"); room.addPendingEvent(eventA, "TXN1");
expect(room.getPendingEvents()).toEqual( expect(room.getPendingEvents()).toEqual(
[eventA] [eventA],
); );
// the event has to have been failed or queued before it can be // the event has to have been failed or queued before it can be
@@ -1242,7 +1242,7 @@ describe("Room", function() {
room.addPendingEvent(eventA, "TXN1"); room.addPendingEvent(eventA, "TXN1");
expect(room.getLiveTimeline().getEvents()).toEqual( expect(room.getLiveTimeline().getEvents()).toEqual(
[eventA] [eventA],
); );
// the event has to have been failed or queued before it can be // the event has to have been failed or queued before it can be

View File

@@ -234,7 +234,7 @@ describe("MatrixScheduler", function() {
expect(queue).toEqual([eventA, eventB]); expect(queue).toEqual([eventA, eventB]);
// modify the queue // modify the queue
const eventC = utils.mkMessage( const eventC = utils.mkMessage(
{user: "@a:bar", room: roomId, event: true} {user: "@a:bar", room: roomId, event: true},
); );
queue.push(eventC); queue.push(eventC);
const queueAgain = scheduler.getQueueForEvent(eventA); const queueAgain = scheduler.getQueueForEvent(eventA);
@@ -313,7 +313,7 @@ describe("MatrixScheduler", function() {
expect(MatrixScheduler.QUEUE_MESSAGES( expect(MatrixScheduler.QUEUE_MESSAGES(
utils.mkMembership({ utils.mkMembership({
user: "@alice:bar", room: roomId, mship: "join", event: true, user: "@alice:bar", room: roomId, mship: "join", event: true,
}) }),
)).toEqual(null); )).toEqual(null);
}); });
}); });
@@ -323,30 +323,30 @@ describe("MatrixScheduler", function() {
const res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT( const res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 1, new MatrixError({ 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."); expect(res >= 500).toBe(true, "Didn't wait long enough.");
}); });
it("should give up after 5 attempts", function() { it("should give up after 5 attempts", function() {
const res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT( const res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 5, {} eventA, 5, {},
); );
expect(res).toBe(-1, "Didn't give up."); expect(res).toBe(-1, "Didn't give up.");
}); });
it("should do exponential backoff", function() { it("should do exponential backoff", function() {
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT( expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 1, {} eventA, 1, {},
)).toEqual(2000); )).toEqual(2000);
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT( expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 2, {} eventA, 2, {},
)).toEqual(4000); )).toEqual(4000);
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT( expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 3, {} eventA, 3, {},
)).toEqual(8000); )).toEqual(8000);
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT( expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 4, {} eventA, 4, {},
)).toEqual(16000); )).toEqual(16000);
}); });
}); });

View File

@@ -46,7 +46,7 @@ function addEventsToTimeline(timeline, numEvents, atStart) {
utils.mkMessage({ utils.mkMessage({
room: ROOM_ID, user: USER_ID, room: ROOM_ID, user: USER_ID,
event: true, event: true,
}), atStart }), atStart,
); );
} }
} }

View File

@@ -14,7 +14,7 @@ describe("utils", function() {
baz: "beer@", baz: "beer@",
}; };
expect(utils.encodeParams(params)).toEqual( expect(utils.encodeParams(params)).toEqual(
"foo=bar&baz=beer%40" "foo=bar&baz=beer%40",
); );
}); });
}); });
@@ -27,7 +27,7 @@ describe("utils", function() {
"%here": "beer@", "%here": "beer@",
}; };
expect(utils.encodeUri(path, vals)).toEqual( expect(utils.encodeUri(path, vals)).toEqual(
"foo/bar/baz/beer%40" "foo/bar/baz/beer%40",
); );
}); });
}); });

View File

@@ -133,7 +133,7 @@ MatrixBaseApis.prototype.makeTxnId = function() {
MatrixBaseApis.prototype.register = function( MatrixBaseApis.prototype.register = function(
username, password, username, password,
sessionId, auth, bindEmail, guestAccessToken, sessionId, auth, bindEmail, guestAccessToken,
callback callback,
) { ) {
if (auth === undefined) { if (auth === undefined) {
auth = {}; auth = {};
@@ -189,7 +189,7 @@ MatrixBaseApis.prototype.registerRequest = function(data, kind, callback) {
} }
return this._http.request( return this._http.request(
callback, "POST", "/register", params, data callback, "POST", "/register", params, data,
); );
}; };
@@ -218,7 +218,7 @@ MatrixBaseApis.prototype.login = function(loginType, data, callback) {
utils.extend(login_data, data); utils.extend(login_data, data);
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", "/login", undefined, login_data callback, "POST", "/login", undefined, login_data,
); );
}; };
@@ -283,7 +283,7 @@ MatrixBaseApis.prototype.loginWithToken = function(token, callback) {
*/ */
MatrixBaseApis.prototype.logout = function(callback) { MatrixBaseApis.prototype.logout = function(callback) {
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", '/logout' callback, "POST", '/logout',
); );
}; };
@@ -305,7 +305,7 @@ MatrixBaseApis.prototype.deactivateAccount = function(auth, callback) {
}; };
} }
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
callback, "POST", '/account/deactivate', undefined, body, httpApi.PREFIX_UNSTABLE callback, "POST", '/account/deactivate', undefined, body, httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -347,7 +347,7 @@ MatrixBaseApis.prototype.getFallbackAuthUrl = function(loginType, authSessionId)
MatrixBaseApis.prototype.createRoom = function(options, callback) { MatrixBaseApis.prototype.createRoom = function(options, callback) {
// valid options include: room_alias_name, visibility, invite // valid options include: room_alias_name, visibility, invite
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", "/createRoom", undefined, options callback, "POST", "/createRoom", undefined, options,
); );
}; };
@@ -382,7 +382,7 @@ MatrixBaseApis.prototype.getStateEvent = function(roomId, eventType, stateKey, c
path = utils.encodeUri(path + "/$stateKey", pathParams); path = utils.encodeUri(path + "/$stateKey", pathParams);
} }
return this._http.authedRequest( return this._http.authedRequest(
callback, "GET", path callback, "GET", path,
); );
}; };
@@ -407,7 +407,7 @@ MatrixBaseApis.prototype.sendStateEvent = function(roomId, eventType, content, s
path = utils.encodeUri(path + "/$stateKey", pathParams); path = utils.encodeUri(path + "/$stateKey", pathParams);
} }
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, content callback, "PUT", path, undefined, content,
); );
}; };
@@ -438,13 +438,13 @@ MatrixBaseApis.prototype.roomInitialSync = function(roomId, limit, callback) {
callback = limit; limit = undefined; callback = limit; limit = undefined;
} }
const path = utils.encodeUri("/rooms/$roomId/initialSync", const path = utils.encodeUri("/rooms/$roomId/initialSync",
{$roomId: roomId} {$roomId: roomId},
); );
if (!limit) { if (!limit) {
limit = 30; limit = 30;
} }
return this._http.authedRequest( return this._http.authedRequest(
callback, "GET", path, { limit: limit } callback, "GET", path, { limit: limit },
); );
}; };
@@ -484,7 +484,7 @@ MatrixBaseApis.prototype.publicRooms = function(options, callback) {
return this._http.authedRequest(callback, "GET", "/publicRooms"); return this._http.authedRequest(callback, "GET", "/publicRooms");
} else { } else {
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", "/publicRooms", query_params, options callback, "POST", "/publicRooms", query_params, options,
); );
} }
}; };
@@ -505,7 +505,7 @@ MatrixBaseApis.prototype.createAlias = function(alias, roomId, callback) {
room_id: roomId, room_id: roomId,
}; };
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, data callback, "PUT", path, undefined, data,
); );
}; };
@@ -522,7 +522,7 @@ MatrixBaseApis.prototype.deleteAlias = function(alias, callback) {
$alias: alias, $alias: alias,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "DELETE", path, undefined, undefined callback, "DELETE", path, undefined, undefined,
); );
}; };
@@ -539,7 +539,7 @@ MatrixBaseApis.prototype.getRoomIdForAlias = function(alias, callback) {
$alias: alias, $alias: alias,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "GET", path callback, "GET", path,
); );
}; };
@@ -586,7 +586,7 @@ MatrixBaseApis.prototype.setRoomDirectoryVisibility =
$roomId: roomId, $roomId: roomId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, { "visibility": visibility } callback, "PUT", path, undefined, { "visibility": visibility },
); );
}; };
@@ -610,7 +610,7 @@ MatrixBaseApis.prototype.setRoomDirectoryVisibilityAppService =
$roomId: roomId, $roomId: roomId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, { "visibility": visibility } callback, "PUT", path, undefined, { "visibility": visibility },
); );
}; };
@@ -712,7 +712,7 @@ MatrixBaseApis.prototype.getProfileInfo = function(userId, info, callback) {
MatrixBaseApis.prototype.getThreePids = function(callback) { MatrixBaseApis.prototype.getThreePids = function(callback) {
const path = "/account/3pid"; const path = "/account/3pid";
return this._http.authedRequest( return this._http.authedRequest(
callback, "GET", path, undefined, undefined callback, "GET", path, undefined, undefined,
); );
}; };
@@ -730,7 +730,7 @@ MatrixBaseApis.prototype.addThreePid = function(creds, bind, callback) {
'bind': bind, 'bind': bind,
}; };
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", path, null, data callback, "POST", path, null, data,
); );
}; };
@@ -749,7 +749,7 @@ MatrixBaseApis.prototype.deleteThreePid = function(medium, address) {
'address': address, 'address': address,
}; };
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "POST", path, null, data, httpApi.PREFIX_UNSTABLE undefined, "POST", path, null, data, httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -769,7 +769,7 @@ MatrixBaseApis.prototype.setPassword = function(authDict, newPassword, callback)
}; };
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", path, null, data callback, "POST", path, null, data,
); );
}; };
@@ -786,7 +786,7 @@ MatrixBaseApis.prototype.getDevices = function() {
const path = "/devices"; const path = "/devices";
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "GET", path, undefined, undefined, undefined, "GET", path, undefined, undefined,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -806,7 +806,7 @@ MatrixBaseApis.prototype.setDeviceDetails = function(device_id, body) {
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "PUT", path, undefined, body, undefined, "PUT", path, undefined, body,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -831,7 +831,7 @@ MatrixBaseApis.prototype.deleteDevice = function(device_id, auth) {
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "DELETE", path, undefined, body, undefined, "DELETE", path, undefined, body,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -849,7 +849,7 @@ MatrixBaseApis.prototype.deleteDevice = function(device_id, auth) {
MatrixBaseApis.prototype.getPushers = function(callback) { MatrixBaseApis.prototype.getPushers = function(callback) {
const path = "/pushers"; const path = "/pushers";
return this._http.authedRequest( return this._http.authedRequest(
callback, "GET", path, undefined, undefined callback, "GET", path, undefined, undefined,
); );
}; };
@@ -864,7 +864,7 @@ MatrixBaseApis.prototype.getPushers = function(callback) {
MatrixBaseApis.prototype.setPusher = function(pusher, callback) { MatrixBaseApis.prototype.setPusher = function(pusher, callback) {
const path = "/pushers/set"; const path = "/pushers/set";
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", path, null, pusher callback, "POST", path, null, pusher,
); );
}; };
@@ -893,7 +893,7 @@ MatrixBaseApis.prototype.addPushRule = function(scope, kind, ruleId, body, callb
$ruleId: ruleId, $ruleId: ruleId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, body callback, "PUT", path, undefined, body,
); );
}; };
@@ -931,7 +931,7 @@ MatrixBaseApis.prototype.setPushRuleEnabled = function(scope, kind,
$ruleId: ruleId, $ruleId: ruleId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, {"enabled": enabled} callback, "PUT", path, undefined, {"enabled": enabled},
); );
}; };
@@ -952,7 +952,7 @@ MatrixBaseApis.prototype.setPushRuleActions = function(scope, kind,
$ruleId: ruleId, $ruleId: ruleId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, {"actions": actions} callback, "PUT", path, undefined, {"actions": actions},
); );
}; };
@@ -975,7 +975,7 @@ MatrixBaseApis.prototype.search = function(opts, callback) {
queryparams.next_batch = opts.next_batch; queryparams.next_batch = opts.next_batch;
} }
return this._http.authedRequest( return this._http.authedRequest(
callback, "POST", "/search", queryparams, opts.body callback, "POST", "/search", queryparams, opts.body,
); );
}; };
@@ -1009,7 +1009,7 @@ MatrixBaseApis.prototype.uploadKeysRequest = function(content, opts, callback) {
path = "/keys/upload"; path = "/keys/upload";
} }
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
callback, "POST", path, undefined, content, httpApi.PREFIX_UNSTABLE callback, "POST", path, undefined, content, httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -1032,7 +1032,7 @@ MatrixBaseApis.prototype.downloadKeysForUsers = function(userIds, callback) {
const content = {device_keys: downloadQuery}; const content = {device_keys: downloadQuery};
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
callback, "POST", "/keys/query", undefined, content, callback, "POST", "/keys/query", undefined, content,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -1063,7 +1063,7 @@ MatrixBaseApis.prototype.claimOneTimeKeys = function(devices, key_algorithm) {
const content = {one_time_keys: queries}; const content = {one_time_keys: queries};
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "POST", "/keys/claim", undefined, content, undefined, "POST", "/keys/claim", undefined, content,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -1101,7 +1101,7 @@ MatrixBaseApis.prototype.requestEmailToken = function(email, clientSecret,
}; };
return this._http.idServerRequest( return this._http.idServerRequest(
callback, "POST", "/validate/email/requestToken", callback, "POST", "/validate/email/requestToken",
params, httpApi.PREFIX_IDENTITY_V1 params, httpApi.PREFIX_IDENTITY_V1,
); );
}; };
@@ -1123,7 +1123,7 @@ MatrixBaseApis.prototype.lookupThreePid = function(medium, address, callback) {
}; };
return this._http.idServerRequest( return this._http.idServerRequest(
callback, "GET", "/lookup", callback, "GET", "/lookup",
params, httpApi.PREFIX_IDENTITY_V1 params, httpApi.PREFIX_IDENTITY_V1,
); );
}; };
@@ -1142,7 +1142,7 @@ MatrixBaseApis.prototype.lookupThreePid = function(medium, address, callback) {
* @return {module:client.Promise} Resolves to the result object * @return {module:client.Promise} Resolves to the result object
*/ */
MatrixBaseApis.prototype.sendToDevice = function( MatrixBaseApis.prototype.sendToDevice = function(
eventType, contentMap, txnId eventType, contentMap, txnId,
) { ) {
const path = utils.encodeUri("/sendToDevice/$eventType/$txnId", { const path = utils.encodeUri("/sendToDevice/$eventType/$txnId", {
$eventType: eventType, $eventType: eventType,
@@ -1155,7 +1155,7 @@ MatrixBaseApis.prototype.sendToDevice = function(
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "PUT", path, undefined, body, undefined, "PUT", path, undefined, body,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -1170,7 +1170,7 @@ MatrixBaseApis.prototype.sendToDevice = function(
MatrixBaseApis.prototype.getThirdpartyProtocols = function() { MatrixBaseApis.prototype.getThirdpartyProtocols = function() {
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "GET", "/thirdparty/protocols", undefined, undefined, undefined, "GET", "/thirdparty/protocols", undefined, undefined,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };
@@ -1189,7 +1189,7 @@ MatrixBaseApis.prototype.getThirdpartyLocation = function(protocol, params) {
return this._http.authedRequestWithPrefix( return this._http.authedRequestWithPrefix(
undefined, "GET", path, params, undefined, undefined, "GET", path, params, undefined,
httpApi.PREFIX_UNSTABLE httpApi.PREFIX_UNSTABLE,
); );
}; };

View File

@@ -157,7 +157,7 @@ function MatrixClient(opts) {
this._crypto = new Crypto( this._crypto = new Crypto(
this, this, this, this,
opts.sessionStore, opts.sessionStore,
userId, this.deviceId userId, this.deviceId,
); );
this.olmVersion = Crypto.getOlmVersion(); this.olmVersion = Crypto.getOlmVersion();
@@ -395,11 +395,29 @@ MatrixClient.prototype.setDeviceBlocked = function(userId, deviceId, blocked) {
_setDeviceVerification(this, userId, deviceId, null, blocked); _setDeviceVerification(this, userId, deviceId, null, blocked);
}; };
function _setDeviceVerification(client, userId, deviceId, verified, blocked) { /**
* Mark the given device as known/unknown
*
* @param {string} userId owner of the device
* @param {string} deviceId unique identifier for the device
*
* @param {boolean=} known whether to mark the device as known. defaults
* to 'true'.
*
* @fires module:client~event:MatrixClient"deviceVerificationChanged"
*/
MatrixClient.prototype.setDeviceKnown = function(userId, deviceId, known) {
if (known === undefined) {
known = true;
}
_setDeviceVerification(this, userId, deviceId, null, null, known);
};
function _setDeviceVerification(client, userId, deviceId, verified, blocked, known) {
if (!client._crypto) { if (!client._crypto) {
throw new Error("End-to-End encryption disabled"); throw new Error("End-to-End encryption disabled");
} }
client._crypto.setDeviceVerification(userId, deviceId, verified, blocked); client._crypto.setDeviceVerification(userId, deviceId, verified, blocked, known);
client.emit("deviceVerificationChanged", userId, deviceId); client.emit("deviceVerificationChanged", userId, deviceId);
} }
@@ -579,7 +597,7 @@ MatrixClient.prototype.setAccountData = function(eventType, contents, callback)
$type: eventType, $type: eventType,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, contents callback, "PUT", path, undefined, contents,
); );
}; };
@@ -629,7 +647,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
if (opts.inviteSignUrl) { if (opts.inviteSignUrl) {
sign_promise = this._http.requestOtherUrl( sign_promise = this._http.requestOtherUrl(
undefined, 'POST', undefined, 'POST',
opts.inviteSignUrl, { mxid: this.credentials.userId } opts.inviteSignUrl, { mxid: this.credentials.userId },
); );
} }
@@ -732,7 +750,7 @@ MatrixClient.prototype.getRoomTags = function(roomId, callback) {
$roomId: roomId, $roomId: roomId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "GET", path, undefined callback, "GET", path, undefined,
); );
}; };
@@ -751,7 +769,7 @@ MatrixClient.prototype.setRoomTag = function(roomId, tagName, metadata, callback
$tag: tagName, $tag: tagName,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, metadata callback, "PUT", path, undefined, metadata,
); );
}; };
@@ -769,7 +787,7 @@ MatrixClient.prototype.deleteRoomTag = function(roomId, tagName, callback) {
$tag: tagName, $tag: tagName,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "DELETE", path, undefined, undefined callback, "DELETE", path, undefined, undefined,
); );
}; };
@@ -789,7 +807,7 @@ MatrixClient.prototype.setRoomAccountData = function(roomId, eventType,
$type: eventType, $type: eventType,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, content callback, "PUT", path, undefined, content,
); );
}; };
@@ -818,7 +836,7 @@ MatrixClient.prototype.setPowerLevel = function(roomId, userId, powerLevel,
$roomId: roomId, $roomId: roomId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, content callback, "PUT", path, undefined, content,
); );
}; };
@@ -958,12 +976,12 @@ function _sendEventHttpRequest(client, event) {
path = utils.encodeUri(pathTemplate, pathParams); path = utils.encodeUri(pathTemplate, pathParams);
} else { } else {
path = utils.encodeUri( path = utils.encodeUri(
"/rooms/$roomId/send/$eventType/$txnId", pathParams "/rooms/$roomId/send/$eventType/$txnId", pathParams,
); );
} }
return client._http.authedRequest( return client._http.authedRequest(
undefined, "PUT", path, undefined, event.getWireContent() undefined, "PUT", path, undefined, event.getWireContent(),
); );
} }
@@ -980,7 +998,7 @@ MatrixClient.prototype.sendMessage = function(roomId, content, txnId, callback)
callback = txnId; txnId = undefined; callback = txnId; txnId = undefined;
} }
return this.sendEvent( return this.sendEvent(
roomId, "m.room.message", content, txnId, callback roomId, "m.room.message", content, txnId, callback,
); );
}; };
@@ -1130,7 +1148,7 @@ MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) {
$eventId: event.getId(), $eventId: event.getId(),
}); });
const promise = this._http.authedRequest( const promise = this._http.authedRequest(
callback, "POST", path, undefined, {} callback, "POST", path, undefined, {},
); );
const room = this.getRoom(event.getRoomId()); const room = this.getRoom(event.getRoomId());
@@ -1179,7 +1197,7 @@ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
callback, "GET", "/preview_url", { callback, "GET", "/preview_url", {
url: url, url: url,
ts: ts, ts: ts,
}, undefined, httpApi.PREFIX_MEDIA_R0 }, undefined, httpApi.PREFIX_MEDIA_R0,
).then(function(response) { ).then(function(response) {
// TODO: expire cache occasionally // TODO: expire cache occasionally
self.urlPreviewCache[key] = response; self.urlPreviewCache[key] = response;
@@ -1211,7 +1229,7 @@ MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callba
data.timeout = timeoutMs ? timeoutMs : 20000; data.timeout = timeoutMs ? timeoutMs : 20000;
} }
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, data callback, "PUT", path, undefined, data,
); );
}; };
@@ -1237,7 +1255,7 @@ MatrixClient.prototype.invite = function(roomId, userId, callback) {
*/ */
MatrixClient.prototype.inviteByEmail = function(roomId, email, callback) { MatrixClient.prototype.inviteByEmail = function(roomId, email, callback) {
return this.inviteByThreePid( return this.inviteByThreePid(
roomId, "email", email, callback roomId, "email", email, callback,
); );
}; };
@@ -1253,7 +1271,7 @@ MatrixClient.prototype.inviteByEmail = function(roomId, email, callback) {
MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, callback) { MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, callback) {
const path = utils.encodeUri( const path = utils.encodeUri(
"/rooms/$roomId/invite", "/rooms/$roomId/invite",
{ $roomId: roomId } { $roomId: roomId },
); );
let identityServerUrl = this.getIdentityServerUrl(); let identityServerUrl = this.getIdentityServerUrl();
@@ -1335,7 +1353,7 @@ MatrixClient.prototype.forget = function(roomId, deleteRoom, callback) {
MatrixClient.prototype.unban = function(roomId, userId, callback) { MatrixClient.prototype.unban = function(roomId, userId, callback) {
// unbanning = set their state to leave // unbanning = set their state to leave
return _setMembershipState( return _setMembershipState(
this, roomId, userId, "leave", undefined, callback this, roomId, userId, "leave", undefined, callback,
); );
}; };
@@ -1349,7 +1367,7 @@ MatrixClient.prototype.unban = function(roomId, userId, callback) {
*/ */
MatrixClient.prototype.kick = function(roomId, userId, reason, callback) { MatrixClient.prototype.kick = function(roomId, userId, reason, callback) {
return _setMembershipState( return _setMembershipState(
this, roomId, userId, "leave", reason, callback this, roomId, userId, "leave", reason, callback,
); );
}; };
@@ -1372,7 +1390,7 @@ function _setMembershipState(client, roomId, userId, membershipValue, reason,
const path = utils.encodeUri( const path = utils.encodeUri(
"/rooms/$roomId/state/m.room.member/$userId", "/rooms/$roomId/state/m.room.member/$userId",
{ $roomId: roomId, $userId: userId} { $roomId: roomId, $userId: userId},
); );
return client._http.authedRequest(callback, "PUT", path, undefined, { return client._http.authedRequest(callback, "PUT", path, undefined, {
@@ -1405,7 +1423,7 @@ function _membershipChange(client, roomId, userId, membership, reason, callback)
callback, "POST", path, undefined, { callback, "POST", path, undefined, {
user_id: userId, // may be undefined e.g. on leave user_id: userId, // may be undefined e.g. on leave
reason: reason, reason: reason,
} },
); );
} }
@@ -1439,7 +1457,7 @@ MatrixClient.prototype.setProfileInfo = function(info, data, callback) {
$info: info, $info: info,
}); });
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, data callback, "PUT", path, undefined, data,
); );
}; };
@@ -1451,7 +1469,7 @@ MatrixClient.prototype.setProfileInfo = function(info, data, callback) {
*/ */
MatrixClient.prototype.setDisplayName = function(name, callback) { MatrixClient.prototype.setDisplayName = function(name, callback) {
return this.setProfileInfo( return this.setProfileInfo(
"displayname", { displayname: name }, callback "displayname", { displayname: name }, callback,
); );
}; };
@@ -1463,7 +1481,7 @@ MatrixClient.prototype.setDisplayName = function(name, callback) {
*/ */
MatrixClient.prototype.setAvatarUrl = function(url, callback) { MatrixClient.prototype.setAvatarUrl = function(url, callback) {
return this.setProfileInfo( return this.setProfileInfo(
"avatar_url", { avatar_url: url }, callback "avatar_url", { avatar_url: url }, callback,
); );
}; };
@@ -1483,7 +1501,7 @@ MatrixClient.prototype.setAvatarUrl = function(url, callback) {
MatrixClient.prototype.mxcUrlToHttp = MatrixClient.prototype.mxcUrlToHttp =
function(mxcUrl, width, height, resizeMethod, allowDirectLinks) { function(mxcUrl, width, height, resizeMethod, allowDirectLinks) {
return contentRepo.getHttpUriForMxc( return contentRepo.getHttpUriForMxc(
this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks,
); );
}; };
@@ -1510,7 +1528,7 @@ MatrixClient.prototype.setPresence = function(opts, callback) {
throw new Error("Bad presence value: " + opts.presence); throw new Error("Bad presence value: " + opts.presence);
} }
return this._http.authedRequest( return this._http.authedRequest(
callback, "PUT", path, undefined, opts callback, "PUT", path, undefined, opts,
); );
}; };
@@ -1600,7 +1618,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
limit = limit - numAdded; limit = limit - numAdded;
const path = utils.encodeUri( const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: room.roomId} "/rooms/$roomId/messages", {$roomId: room.roomId},
); );
const params = { const params = {
from: room.oldState.paginationToken, from: room.oldState.paginationToken,
@@ -1670,7 +1688,7 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
} }
const path = utils.encodeUri( const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: eventContext.getEvent().getRoomId()} "/rooms/$roomId/messages", {$roomId: eventContext.getEvent().getRoomId()},
); );
const params = { const params = {
from: token, from: token,
@@ -1680,7 +1698,7 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
const self = this; const self = this;
const promise = const promise =
self._http.authedRequest(undefined, "GET", path, params self._http.authedRequest(undefined, "GET", path, params,
).then(function(res) { ).then(function(res) {
let token = res.end; let token = res.end;
if (res.chunk.length === 0) { if (res.chunk.length === 0) {
@@ -1734,14 +1752,14 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
"/rooms/$roomId/context/$eventId", { "/rooms/$roomId/context/$eventId", {
$roomId: timelineSet.room.roomId, $roomId: timelineSet.room.roomId,
$eventId: eventId, $eventId: eventId,
} },
); );
// TODO: we should implement a backoff (as per scrollback()) to deal more // TODO: we should implement a backoff (as per scrollback()) to deal more
// nicely with HTTP errors. // nicely with HTTP errors.
const self = this; const self = this;
const promise = const promise =
self._http.authedRequest(undefined, "GET", path self._http.authedRequest(undefined, "GET", path,
).then(function(res) { ).then(function(res) {
if (!res.event) { if (!res.event) {
throw new Error("'event' not in '/context' result - homeserver too old?"); throw new Error("'event' not in '/context' result - homeserver too old?");
@@ -1841,7 +1859,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
promise = promise =
this._http.authedRequestWithPrefix(undefined, "GET", path, params, this._http.authedRequestWithPrefix(undefined, "GET", path, params,
undefined, httpApi.PREFIX_UNSTABLE undefined, httpApi.PREFIX_UNSTABLE,
).then(function(res) { ).then(function(res) {
const token = res.next_token; const token = res.next_token;
const matrixEvents = []; const matrixEvents = [];
@@ -1850,7 +1868,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
const notification = res.notifications[i]; const notification = res.notifications[i];
const event = self.getEventMapper()(notification.event); const event = self.getEventMapper()(notification.event);
event.setPushActions( event.setPushActions(
PushProcessor.actionListToActionsObject(notification.actions) PushProcessor.actionListToActionsObject(notification.actions),
); );
event.event.room_id = notification.room_id; // XXX: gutwrenching event.event.room_id = notification.room_id; // XXX: gutwrenching
matrixEvents[i] = event; matrixEvents[i] = event;
@@ -1877,7 +1895,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
} }
path = utils.encodeUri( path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: eventTimeline.getRoomId()} "/rooms/$roomId/messages", {$roomId: eventTimeline.getRoomId()},
); );
params = { params = {
from: token, from: token,
@@ -1893,7 +1911,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
} }
promise = promise =
this._http.authedRequest(undefined, "GET", path, params this._http.authedRequest(undefined, "GET", path, params,
).then(function(res) { ).then(function(res) {
const token = res.end; const token = res.end;
const matrixEvents = utils.map(res.chunk, self.getEventMapper()); const matrixEvents = utils.map(res.chunk, self.getEventMapper());
@@ -2029,7 +2047,7 @@ MatrixClient.prototype.requestRegisterEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) { sendAttempt, nextLink, callback) {
return this._requestTokenFromEndpoint( return this._requestTokenFromEndpoint(
"/register/email/requestToken", "/register/email/requestToken",
email, clientSecret, sendAttempt, nextLink, callback email, clientSecret, sendAttempt, nextLink, callback,
); );
}; };
@@ -2057,7 +2075,7 @@ MatrixClient.prototype.requestAdd3pidEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) { sendAttempt, nextLink, callback) {
return this._requestTokenFromEndpoint( return this._requestTokenFromEndpoint(
"/account/3pid/email/requestToken", "/account/3pid/email/requestToken",
email, clientSecret, sendAttempt, nextLink, callback email, clientSecret, sendAttempt, nextLink, callback,
); );
}; };
@@ -2084,7 +2102,7 @@ MatrixClient.prototype.requestPasswordEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) { sendAttempt, nextLink, callback) {
return this._requestTokenFromEndpoint( return this._requestTokenFromEndpoint(
"/account/password/email/requestToken", "/account/password/email/requestToken",
email, clientSecret, sendAttempt, nextLink, callback email, clientSecret, sendAttempt, nextLink, callback,
); );
}; };
@@ -2117,7 +2135,7 @@ MatrixClient.prototype._requestTokenFromEndpoint = function(endpoint,
}; };
return this._http.request( return this._http.request(
callback, "POST", endpoint, undefined, callback, "POST", endpoint, undefined,
params params,
); );
}; };
@@ -2143,7 +2161,7 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) {
} }
} else { } else {
throw new Error( throw new Error(
"SyncApi.sync() must be done before accessing to push rules." "SyncApi.sync() must be done before accessing to push rules.",
); );
} }
}; };
@@ -2295,7 +2313,7 @@ MatrixClient.prototype.searchRoomEvents = function(opts) {
}; };
return this.search({body: body}).then( return this.search({body: body}).then(
this._processRoomEventsSearch.bind(this, searchResults) this._processRoomEventsSearch.bind(this, searchResults),
); );
}; };
@@ -2325,7 +2343,7 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) {
}; };
const promise = this.search(searchOpts).then( const promise = this.search(searchOpts).then(
this._processRoomEventsSearch.bind(this, searchResults) this._processRoomEventsSearch.bind(this, searchResults),
).finally(function() { ).finally(function() {
searchResults.pendingRequest = null; searchResults.pendingRequest = null;
}); });
@@ -2415,11 +2433,11 @@ MatrixClient.prototype.createFilter = function(content) {
$userId: this.credentials.userId, $userId: this.credentials.userId,
}); });
return this._http.authedRequest( return this._http.authedRequest(
undefined, "POST", path, undefined, content undefined, "POST", path, undefined, content,
).then(function(response) { ).then(function(response) {
// persist the filter // persist the filter
const filter = Filter.fromJson( const filter = Filter.fromJson(
self.credentials.userId, response.filter_id, content self.credentials.userId, response.filter_id, content,
); );
self.store.storeFilter(filter); self.store.storeFilter(filter);
return filter; return filter;
@@ -2450,11 +2468,11 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
}); });
return this._http.authedRequest( return this._http.authedRequest(
undefined, "GET", path, undefined, undefined undefined, "GET", path, undefined, undefined,
).then(function(response) { ).then(function(response) {
// persist the filter // persist the filter
const filter = Filter.fromJson( const filter = Filter.fromJson(
userId, filterId, response userId, filterId, response,
); );
self.store.storeFilter(filter); self.store.storeFilter(filter);
return filter; return filter;
@@ -2474,7 +2492,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
if (filterId) { if (filterId) {
// check that the existing filter matches our expectations // check that the existing filter matches our expectations
promise = self.getFilter(self.credentials.userId, promise = self.getFilter(self.credentials.userId,
filterId, true filterId, true,
).then(function(existingFilter) { ).then(function(existingFilter) {
const oldDef = existingFilter.getDefinition(); const oldDef = existingFilter.getDefinition();
const newDef = filter.getDefinition(); const newDef = filter.getDefinition();
@@ -2516,7 +2534,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
} }
// create a new filter // create a new filter
return self.createFilter(filter.getDefinition() return self.createFilter(filter.getDefinition(),
).then(function(createdFilter) { ).then(function(createdFilter) {
// debuglog("Created new filter ID %s: %s", createdFilter.filterId, // debuglog("Created new filter ID %s: %s", createdFilter.filterId,
// JSON.stringify(createdFilter.getDefinition())); // JSON.stringify(createdFilter.getDefinition()));
@@ -2540,7 +2558,7 @@ MatrixClient.prototype.getOpenIdToken = function() {
}); });
return this._http.authedRequest( return this._http.authedRequest(
undefined, "POST", path, undefined, {} undefined, "POST", path, undefined, {},
); );
}; };
@@ -2730,7 +2748,7 @@ function setupCallEventHandler(client) {
console.log( console.log(
"WARN: Already have a MatrixCall with id %s but got an " + "WARN: Already have a MatrixCall with id %s but got an " +
"invite. Clobbering.", "invite. Clobbering.",
content.call_id content.call_id,
); );
} }
@@ -2738,7 +2756,7 @@ function setupCallEventHandler(client) {
if (!call) { if (!call) {
console.log( console.log(
"Incoming call ID " + content.call_id + " but this client " + "Incoming call ID " + content.call_id + " but this client " +
"doesn't support WebRTC" "doesn't support WebRTC",
); );
// don't hang up the call: there could be other clients // don't hang up the call: there could be other clients
// connected that do support WebRTC and declining the // connected that do support WebRTC and declining the
@@ -2754,7 +2772,7 @@ function setupCallEventHandler(client) {
if (candidatesByCall[call.callId]) { if (candidatesByCall[call.callId]) {
for (i = 0; i < candidatesByCall[call.callId].length; i++) { for (i = 0; i < candidatesByCall[call.callId].length; i++) {
call._gotRemoteIceCandidate( call._gotRemoteIceCandidate(
candidatesByCall[call.callId][i] candidatesByCall[call.callId][i],
); );
} }
} }
@@ -2783,14 +2801,14 @@ function setupCallEventHandler(client) {
existingCall.callId > call.callId) { existingCall.callId > call.callId) {
console.log( console.log(
"Glare detected: answering incoming call " + call.callId + "Glare detected: answering incoming call " + call.callId +
" and canceling outgoing call " + existingCall.callId " and canceling outgoing call " + existingCall.callId,
); );
existingCall._replacedBy(call); existingCall._replacedBy(call);
call.answer(); call.answer();
} else { } else {
console.log( console.log(
"Glare detected: rejecting incoming call " + call.callId + "Glare detected: rejecting incoming call " + call.callId +
" and keeping outgoing call " + existingCall.callId " and keeping outgoing call " + existingCall.callId,
); );
call.hangup(); call.hangup();
} }

View File

@@ -191,7 +191,7 @@ OlmDevice.prototype._getSession = function(deviceKey, sessionId, func) {
OlmDevice.prototype._saveSession = function(deviceKey, session) { OlmDevice.prototype._saveSession = function(deviceKey, session) {
const pickledSession = session.pickle(this._pickleKey); const pickledSession = session.pickle(this._pickleKey);
this._sessionStore.storeEndToEndSession( this._sessionStore.storeEndToEndSession(
deviceKey, session.session_id(), pickledSession deviceKey, session.session_id(), pickledSession,
); );
}; };
@@ -284,7 +284,7 @@ OlmDevice.prototype.generateOneTimeKeys = function(numKeys) {
* @return {string} sessionId for the outbound session. * @return {string} sessionId for the outbound session.
*/ */
OlmDevice.prototype.createOutboundSession = function( OlmDevice.prototype.createOutboundSession = function(
theirIdentityKey, theirOneTimeKey theirIdentityKey, theirOneTimeKey,
) { ) {
const self = this; const self = this;
return this._getAccount(function(account) { return this._getAccount(function(account) {
@@ -314,7 +314,7 @@ OlmDevice.prototype.createOutboundSession = function(
* didn't use a valid one-time key). * didn't use a valid one-time key).
*/ */
OlmDevice.prototype.createInboundSession = function( OlmDevice.prototype.createInboundSession = function(
theirDeviceIdentityKey, message_type, ciphertext theirDeviceIdentityKey, message_type, ciphertext,
) { ) {
if (message_type !== 0) { if (message_type !== 0) {
throw new Error("Need message_type == 0 to create inbound session"); throw new Error("Need message_type == 0 to create inbound session");
@@ -352,7 +352,7 @@ OlmDevice.prototype.createInboundSession = function(
*/ */
OlmDevice.prototype.getSessionIdsForDevice = function(theirDeviceIdentityKey) { OlmDevice.prototype.getSessionIdsForDevice = function(theirDeviceIdentityKey) {
const sessions = this._sessionStore.getEndToEndSessions( const sessions = this._sessionStore.getEndToEndSessions(
theirDeviceIdentityKey theirDeviceIdentityKey,
); );
return utils.keys(sessions); return utils.keys(sessions);
}; };
@@ -417,7 +417,7 @@ OlmDevice.prototype.getSessionInfoForDevice = function(deviceIdentityKey) {
* @return {string} ciphertext * @return {string} ciphertext
*/ */
OlmDevice.prototype.encryptMessage = function( OlmDevice.prototype.encryptMessage = function(
theirDeviceIdentityKey, sessionId, payloadString theirDeviceIdentityKey, sessionId, payloadString,
) { ) {
const self = this; const self = this;
@@ -442,7 +442,7 @@ OlmDevice.prototype.encryptMessage = function(
* @return {string} decrypted payload. * @return {string} decrypted payload.
*/ */
OlmDevice.prototype.decryptMessage = function( OlmDevice.prototype.decryptMessage = function(
theirDeviceIdentityKey, sessionId, message_type, ciphertext theirDeviceIdentityKey, sessionId, message_type, ciphertext,
) { ) {
const self = this; const self = this;
@@ -467,7 +467,7 @@ OlmDevice.prototype.decryptMessage = function(
* the given session. * the given session.
*/ */
OlmDevice.prototype.matchesSession = function( OlmDevice.prototype.matchesSession = function(
theirDeviceIdentityKey, sessionId, message_type, ciphertext theirDeviceIdentityKey, sessionId, message_type, ciphertext,
) { ) {
if (message_type !== 0) { if (message_type !== 0) {
return false; return false;
@@ -588,7 +588,7 @@ OlmDevice.prototype.getOutboundGroupSessionKey = function(sessionId) {
* @private * @private
*/ */
OlmDevice.prototype._saveInboundGroupSession = function( OlmDevice.prototype._saveInboundGroupSession = function(
roomId, senderCurve25519Key, sessionId, session, keysClaimed roomId, senderCurve25519Key, sessionId, session, keysClaimed,
) { ) {
const r = { const r = {
room_id: roomId, room_id: roomId,
@@ -597,7 +597,7 @@ OlmDevice.prototype._saveInboundGroupSession = function(
}; };
this._sessionStore.storeEndToEndInboundGroupSession( this._sessionStore.storeEndToEndInboundGroupSession(
senderCurve25519Key, sessionId, JSON.stringify(r) senderCurve25519Key, sessionId, JSON.stringify(r),
); );
}; };
@@ -618,10 +618,10 @@ OlmDevice.prototype._saveInboundGroupSession = function(
* @template {T} * @template {T}
*/ */
OlmDevice.prototype._getInboundGroupSession = function( OlmDevice.prototype._getInboundGroupSession = function(
roomId, senderKey, sessionId, func roomId, senderKey, sessionId, func,
) { ) {
let r = this._sessionStore.getEndToEndInboundGroupSession( let r = this._sessionStore.getEndToEndInboundGroupSession(
senderKey, sessionId senderKey, sessionId,
); );
if (r === null) { if (r === null) {
@@ -635,7 +635,7 @@ OlmDevice.prototype._getInboundGroupSession = function(
if (roomId !== r.room_id) { if (roomId !== r.room_id) {
throw new Error( throw new Error(
"Mismatched room_id for inbound group session (expected " + r.room_id + "Mismatched room_id for inbound group session (expected " + r.room_id +
", was " + roomId + ")" ", was " + roomId + ")",
); );
} }
@@ -658,7 +658,7 @@ OlmDevice.prototype._getInboundGroupSession = function(
* @param {Object<string, string>} keysClaimed Other keys the sender claims. * @param {Object<string, string>} keysClaimed Other keys the sender claims.
*/ */
OlmDevice.prototype.addInboundGroupSession = function( OlmDevice.prototype.addInboundGroupSession = function(
roomId, senderKey, sessionId, sessionKey, keysClaimed roomId, senderKey, sessionId, sessionKey, keysClaimed,
) { ) {
const self = this; const self = this;
@@ -671,7 +671,7 @@ OlmDevice.prototype.addInboundGroupSession = function(
} }
const r = this._getInboundGroupSession( const r = this._getInboundGroupSession(
roomId, senderKey, sessionId, updateSession roomId, senderKey, sessionId, updateSession,
); );
if (r !== null) { if (r !== null) {
@@ -684,11 +684,11 @@ OlmDevice.prototype.addInboundGroupSession = function(
session.create(sessionKey); session.create(sessionKey);
if (sessionId != session.session_id()) { if (sessionId != session.session_id()) {
throw new Error( throw new Error(
"Mismatched group session ID from senderKey: " + senderKey "Mismatched group session ID from senderKey: " + senderKey,
); );
} }
self._saveInboundGroupSession( self._saveInboundGroupSession(
roomId, senderKey, sessionId, session, keysClaimed roomId, senderKey, sessionId, session, keysClaimed,
); );
} finally { } finally {
session.free(); session.free();
@@ -712,7 +712,7 @@ OlmDevice.prototype.importInboundGroupSession = function(data) {
} }
const r = this._getInboundGroupSession( const r = this._getInboundGroupSession(
data.room_id, data.sender_key, data.session_id, updateSession data.room_id, data.sender_key, data.session_id, updateSession,
); );
if (r !== null) { if (r !== null) {
@@ -725,12 +725,12 @@ OlmDevice.prototype.importInboundGroupSession = function(data) {
session.import_session(data.session_key); session.import_session(data.session_key);
if (data.session_id != session.session_id()) { if (data.session_id != session.session_id()) {
throw new Error( throw new Error(
"Mismatched group session ID from senderKey: " + data.sender_key "Mismatched group session ID from senderKey: " + data.sender_key,
); );
} }
this._saveInboundGroupSession( this._saveInboundGroupSession(
data.room_id, data.sender_key, data.session_id, session, data.room_id, data.sender_key, data.session_id, session,
data.sender_claimed_keys data.sender_claimed_keys,
); );
} finally { } finally {
session.free(); session.free();
@@ -751,7 +751,7 @@ OlmDevice.prototype.importInboundGroupSession = function(data) {
* Object<string, string>}} result * Object<string, string>}} result
*/ */
OlmDevice.prototype.decryptGroupMessage = function( OlmDevice.prototype.decryptGroupMessage = function(
roomId, senderKey, sessionId, body roomId, senderKey, sessionId, body,
) { ) {
const self = this; const self = this;
@@ -768,7 +768,7 @@ OlmDevice.prototype.decryptGroupMessage = function(
if (messageIndexKey in self._inboundGroupSessionMessageIndexes) { if (messageIndexKey in self._inboundGroupSessionMessageIndexes) {
throw new Error( throw new Error(
"Duplicate message index, possible replay attack: " + "Duplicate message index, possible replay attack: " +
messageIndexKey messageIndexKey,
); );
} }
self._inboundGroupSessionMessageIndexes[messageIndexKey] = true; self._inboundGroupSessionMessageIndexes[messageIndexKey] = true;
@@ -779,7 +779,7 @@ OlmDevice.prototype.decryptGroupMessage = function(
const keysProved = {curve25519: senderKey}; const keysProved = {curve25519: senderKey};
self._saveInboundGroupSession( self._saveInboundGroupSession(
roomId, senderKey, sessionId, session, keysClaimed roomId, senderKey, sessionId, session, keysClaimed,
); );
return { return {
result: plaintext, result: plaintext,
@@ -789,7 +789,7 @@ OlmDevice.prototype.decryptGroupMessage = function(
} }
return this._getInboundGroupSession( return this._getInboundGroupSession(
roomId, senderKey, sessionId, decrypt roomId, senderKey, sessionId, decrypt,
); );
}; };
@@ -802,7 +802,7 @@ OlmDevice.prototype.decryptGroupMessage = function(
*/ */
OlmDevice.prototype.exportInboundGroupSession = function(senderKey, sessionId) { OlmDevice.prototype.exportInboundGroupSession = function(senderKey, sessionId) {
const s = this._sessionStore.getEndToEndInboundGroupSession( const s = this._sessionStore.getEndToEndInboundGroupSession(
senderKey, sessionId senderKey, sessionId,
); );
if (s === null) { if (s === null) {
@@ -844,7 +844,7 @@ OlmDevice.prototype.exportInboundGroupSession = function(senderKey, sessionId) {
* was invalid then the message will be "OLM.BAD_MESSAGE_MAC". * was invalid then the message will be "OLM.BAD_MESSAGE_MAC".
*/ */
OlmDevice.prototype.verifySignature = function( OlmDevice.prototype.verifySignature = function(
key, message, signature key, message, signature,
) { ) {
this._getUtility(function(util) { this._getUtility(function(util) {
util.ed25519_verify(key, message, signature); util.ed25519_verify(key, message, signature);

View File

@@ -85,7 +85,7 @@ module.exports.EncryptionAlgorithm = EncryptionAlgorithm;
* @param {string=} oldMembership previous membership * @param {string=} oldMembership previous membership
*/ */
EncryptionAlgorithm.prototype.onRoomMembership = function( EncryptionAlgorithm.prototype.onRoomMembership = function(
event, member, oldMembership event, member, oldMembership,
) {}; ) {};
/** /**

View File

@@ -57,7 +57,7 @@ function OutboundSessionInfo(sessionId) {
* @return {Boolean} * @return {Boolean}
*/ */
OutboundSessionInfo.prototype.needsRotation = function( OutboundSessionInfo.prototype.needsRotation = function(
rotationPeriodMsgs, rotationPeriodMs rotationPeriodMsgs, rotationPeriodMs,
) { ) {
const sessionLifetime = new Date().getTime() - this.creationTime; const sessionLifetime = new Date().getTime() - this.creationTime;
@@ -66,7 +66,7 @@ OutboundSessionInfo.prototype.needsRotation = function(
) { ) {
console.log( console.log(
"Rotating megolm session after " + this.useCount + "Rotating megolm session after " + this.useCount +
" messages, " + sessionLifetime + "ms" " messages, " + sessionLifetime + "ms",
); );
return true; return true;
} }
@@ -86,7 +86,7 @@ OutboundSessionInfo.prototype.needsRotation = function(
* in devicesInRoom. * in devicesInRoom.
*/ */
OutboundSessionInfo.prototype.sharedWithTooManyDevices = function( OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
devicesInRoom devicesInRoom,
) { ) {
for (const userId in this.sharedWithDevices) { for (const userId in this.sharedWithDevices) {
if (!this.sharedWithDevices.hasOwnProperty(userId)) { if (!this.sharedWithDevices.hasOwnProperty(userId)) {
@@ -106,7 +106,7 @@ OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
if (!devicesInRoom[userId].hasOwnProperty(deviceId)) { if (!devicesInRoom[userId].hasOwnProperty(deviceId)) {
console.log( console.log(
"Starting new session because we shared with " + "Starting new session because we shared with " +
userId + ":" + deviceId userId + ":" + deviceId,
); );
return true; return true;
} }
@@ -220,7 +220,7 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) {
} }
return self._shareKeyWithDevices( return self._shareKeyWithDevices(
session, shareMap session, shareMap,
); );
} }
@@ -250,7 +250,7 @@ MegolmEncryption.prototype._prepareNewSession = function() {
this._olmDevice.addInboundGroupSession( this._olmDevice.addInboundGroupSession(
this._roomId, this._olmDevice.deviceCurve25519Key, session_id, this._roomId, this._olmDevice.deviceCurve25519Key, session_id,
key.key, {ed25519: this._olmDevice.deviceEd25519Key} key.key, {ed25519: this._olmDevice.deviceEd25519Key},
); );
return new OutboundSessionInfo(session_id); return new OutboundSessionInfo(session_id);
@@ -285,7 +285,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
const contentMap = {}; const contentMap = {};
return olmlib.ensureOlmSessionsForDevices( return olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, devicesByUser this._olmDevice, this._baseApis, devicesByUser,
).then(function(devicemap) { ).then(function(devicemap) {
let haveTargets = false; let haveTargets = false;
@@ -318,7 +318,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
} }
console.log( console.log(
"sharing keys with device " + userId + ":" + deviceId "sharing keys with device " + userId + ":" + deviceId,
); );
const encryptedContent = { const encryptedContent = {
@@ -334,7 +334,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
self._olmDevice, self._olmDevice,
userId, userId,
deviceInfo, deviceInfo,
payload payload,
); );
if (!contentMap[userId]) { if (!contentMap[userId]) {
@@ -401,7 +401,7 @@ MegolmEncryption.prototype.encryptMessage = function(room, eventType, content) {
}; };
const ciphertext = self._olmDevice.encryptGroupMessage( const ciphertext = self._olmDevice.encryptGroupMessage(
session.sessionId, JSON.stringify(payloadJson) session.sessionId, JSON.stringify(payloadJson),
); );
const encryptedContent = { const encryptedContent = {
@@ -473,8 +473,10 @@ MegolmEncryption.prototype._getDevicesInRoom = function(room) {
// with them, which means that they will have announced any new devices via // with them, which means that they will have announced any new devices via
// an m.new_device. // an m.new_device.
// //
// XXX: what if the cache is stale, and the user left the room we had in common // XXX: what if the cache is stale, and the user left the room we had in
// and then added new devices before joining this one? --Matthew // common and then added new devices before joining this one? --Matthew
//
// yup, see https://github.com/vector-im/riot-web/issues/2305 --richvdh
return this._crypto.downloadKeys(roomMembers, false).then(function(devices) { return this._crypto.downloadKeys(roomMembers, false).then(function(devices) {
// remove any blocked devices // remove any blocked devices
for (const userId in devices) { for (const userId in devices) {
@@ -535,7 +537,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
let res; let res;
try { try {
res = this._olmDevice.decryptGroupMessage( res = this._olmDevice.decryptGroupMessage(
event.getRoomId(), content.sender_key, content.session_id, content.ciphertext event.getRoomId(), content.sender_key, content.session_id, content.ciphertext,
); );
} catch (e) { } catch (e) {
if (e.message === 'OLM.UNKNOWN_MESSAGE_INDEX') { if (e.message === 'OLM.UNKNOWN_MESSAGE_INDEX') {
@@ -548,7 +550,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
// We've got a message for a session we don't have. // We've got a message for a session we don't have.
this._addEventToPendingList(event); this._addEventToPendingList(event);
throw new base.DecryptionError( throw new base.DecryptionError(
"The sender's device has not sent us the keys for this message." "The sender's device has not sent us the keys for this message.",
); );
} }
@@ -559,7 +561,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
// room, so neither the sender nor a MITM can lie about the room_id). // room, so neither the sender nor a MITM can lie about the room_id).
if (payload.room_id !== event.getRoomId()) { if (payload.room_id !== event.getRoomId()) {
throw new base.DecryptionError( throw new base.DecryptionError(
"Message intended for room " + payload.room_id "Message intended for room " + payload.room_id,
); );
} }
@@ -603,7 +605,7 @@ MegolmDecryption.prototype.onRoomKeyEvent = function(event) {
this._olmDevice.addInboundGroupSession( this._olmDevice.addInboundGroupSession(
content.room_id, event.getSenderKey(), content.session_id, content.room_id, event.getSenderKey(), content.session_id,
content.session_key, event.getKeysClaimed() content.session_key, event.getKeysClaimed(),
); );
// have another go at decrypting events sent with this session. // have another go at decrypting events sent with this session.
@@ -650,5 +652,5 @@ MegolmDecryption.prototype._retryDecryption = function(senderKey, sessionId) {
}; };
base.registerAlgorithm( base.registerAlgorithm(
olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption,
); );

View File

@@ -126,7 +126,7 @@ OlmEncryption.prototype.encryptMessage = function(room, eventType, content) {
olmlib.encryptMessageForDevice( olmlib.encryptMessageForDevice(
encryptedContent.ciphertext, encryptedContent.ciphertext,
self._userId, self._deviceId, self._olmDevice, self._userId, self._deviceId, self._olmDevice,
userId, deviceInfo, payloadFields userId, deviceInfo, payloadFields,
); );
} }
} }
@@ -177,7 +177,7 @@ OlmDecryption.prototype.decryptEvent = function(event) {
console.warn( console.warn(
"Failed to decrypt Olm event (id=" + "Failed to decrypt Olm event (id=" +
event.getId() + ") from " + deviceKey + event.getId() + ") from " + deviceKey +
": " + e.message ": " + e.message,
); );
throw new base.DecryptionError("Bad Encrypted Message"); throw new base.DecryptionError("Bad Encrypted Message");
} }
@@ -189,10 +189,10 @@ OlmDecryption.prototype.decryptEvent = function(event) {
if (payload.recipient != this._userId) { if (payload.recipient != this._userId) {
console.warn( console.warn(
"Event " + event.getId() + ": Intended recipient " + "Event " + event.getId() + ": Intended recipient " +
payload.recipient + " does not match our id " + this._userId payload.recipient + " does not match our id " + this._userId,
); );
throw new base.DecryptionError( throw new base.DecryptionError(
"Message was intented for " + payload.recipient "Message was intented for " + payload.recipient,
); );
} }
@@ -200,7 +200,7 @@ OlmDecryption.prototype.decryptEvent = function(event) {
this._olmDevice.deviceEd25519Key) { this._olmDevice.deviceEd25519Key) {
console.warn( console.warn(
"Event " + event.getId() + ": Intended recipient ed25519 key " + "Event " + event.getId() + ": Intended recipient ed25519 key " +
payload.recipient_keys.ed25519 + " did not match ours" payload.recipient_keys.ed25519 + " did not match ours",
); );
throw new base.DecryptionError("Message not intended for this device"); throw new base.DecryptionError("Message not intended for this device");
} }
@@ -212,10 +212,10 @@ OlmDecryption.prototype.decryptEvent = function(event) {
if (payload.sender != event.getSender()) { if (payload.sender != event.getSender()) {
console.warn( console.warn(
"Event " + event.getId() + ": original sender " + payload.sender + "Event " + event.getId() + ": original sender " + payload.sender +
" does not match reported sender " + event.getSender() " does not match reported sender " + event.getSender(),
); );
throw new base.DecryptionError( throw new base.DecryptionError(
"Message forwarded from " + payload.sender "Message forwarded from " + payload.sender,
); );
} }
@@ -223,10 +223,10 @@ OlmDecryption.prototype.decryptEvent = function(event) {
if (payload.room_id !== event.getRoomId()) { if (payload.room_id !== event.getRoomId()) {
console.warn( console.warn(
"Event " + event.getId() + ": original room " + payload.room_id + "Event " + event.getId() + ": original room " + payload.room_id +
" does not match reported room " + event.room_id " does not match reported room " + event.room_id,
); );
throw new base.DecryptionError( throw new base.DecryptionError(
"Message intended for room " + payload.room_id "Message intended for room " + payload.room_id,
); );
} }
@@ -251,16 +251,16 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa
const sessionId = sessionIds[i]; const sessionId = sessionIds[i];
try { try {
const payload = this._olmDevice.decryptMessage( const payload = this._olmDevice.decryptMessage(
theirDeviceIdentityKey, sessionId, message.type, message.body theirDeviceIdentityKey, sessionId, message.type, message.body,
); );
console.log( console.log(
"Decrypted Olm message from " + theirDeviceIdentityKey + "Decrypted Olm message from " + theirDeviceIdentityKey +
" with session " + sessionId " with session " + sessionId,
); );
return payload; return payload;
} catch (e) { } catch (e) {
const foundSession = this._olmDevice.matchesSession( const foundSession = this._olmDevice.matchesSession(
theirDeviceIdentityKey, sessionId, message.type, message.body theirDeviceIdentityKey, sessionId, message.type, message.body,
); );
if (foundSession) { if (foundSession) {
@@ -268,7 +268,7 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa
// session, so it should have worked. // session, so it should have worked.
throw new Error( throw new Error(
"Error decrypting prekey message with existing session id " + "Error decrypting prekey message with existing session id " +
sessionId + ": " + e.message sessionId + ": " + e.message,
); );
} }
@@ -288,7 +288,7 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa
throw new Error( throw new Error(
"Error decrypting non-prekey message with existing sessions: " + "Error decrypting non-prekey message with existing sessions: " +
JSON.stringify(decryptionErrors) JSON.stringify(decryptionErrors),
); );
} }
@@ -298,19 +298,19 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa
let res; let res;
try { try {
res = this._olmDevice.createInboundSession( res = this._olmDevice.createInboundSession(
theirDeviceIdentityKey, message.type, message.body theirDeviceIdentityKey, message.type, message.body,
); );
} catch (e) { } catch (e) {
decryptionErrors["(new)"] = e.message; decryptionErrors["(new)"] = e.message;
throw new Error( throw new Error(
"Error decrypting prekey message: " + "Error decrypting prekey message: " +
JSON.stringify(decryptionErrors) JSON.stringify(decryptionErrors),
); );
} }
console.log( console.log(
"created new inbound Olm session ID " + "created new inbound Olm session ID " +
res.session_id + " with " + theirDeviceIdentityKey res.session_id + " with " + theirDeviceIdentityKey,
); );
return res.payload; return res.payload;
}; };

View File

@@ -69,7 +69,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
this._roomDecryptors = {}; this._roomDecryptors = {};
this._supportedAlgorithms = utils.keys( this._supportedAlgorithms = utils.keys(
algorithms.DECRYPTION_CLASSES algorithms.DECRYPTION_CLASSES,
); );
// build our device keys: these will later be uploaded // build our device keys: these will later be uploaded
@@ -80,7 +80,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
this._olmDevice.deviceCurve25519Key; this._olmDevice.deviceCurve25519Key;
let myDevices = this._sessionStore.getEndToEndDevicesForUser( let myDevices = this._sessionStore.getEndToEndDevicesForUser(
this._userId this._userId,
); );
if (!myDevices) { if (!myDevices) {
@@ -100,7 +100,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
myDevices[this._deviceId] = deviceInfo; myDevices[this._deviceId] = deviceInfo;
this._sessionStore.storeEndToEndDevicesForUser( this._sessionStore.storeEndToEndDevicesForUser(
this._userId, myDevices this._userId, myDevices,
); );
} }
@@ -381,7 +381,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
}); });
this._baseApis.downloadKeysForUsers( this._baseApis.downloadKeysForUsers(
downloadUsers downloadUsers,
).done(function(res) { ).done(function(res) {
const dk = res.device_keys || {}; const dk = res.device_keys || {};
@@ -412,7 +412,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
} }
_updateStoredDeviceKeysForUser( _updateStoredDeviceKeysForUser(
self._olmDevice, userId, userStore, dk[userId] self._olmDevice, userId, userStore, dk[userId],
); );
// update the session store // update the session store
@@ -425,7 +425,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
storage[deviceId] = userStore[deviceId].toStorage(); storage[deviceId] = userStore[deviceId].toStorage();
} }
self._sessionStore.storeEndToEndDevicesForUser( self._sessionStore.storeEndToEndDevicesForUser(
userId, storage userId, storage,
); );
deferMap[userId].resolve(); deferMap[userId].resolve();
@@ -711,7 +711,7 @@ Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified,
} }
let knownStatus = dev.known; let knownStatus = dev.known;
if (known !== null) { if (known !== null && known !== undefined) {
knownStatus = known; knownStatus = known;
} }
@@ -775,7 +775,7 @@ Crypto.prototype.getEventSenderDeviceInfo = function(event) {
// identity key of the device which set up the Megolm session. // identity key of the device which set up the Megolm session.
const device = this.getDeviceByIdentityKey( const device = this.getDeviceByIdentityKey(
event.getSender(), algorithm, sender_key event.getSender(), algorithm, sender_key,
); );
if (device === null) { if (device === null) {
@@ -894,7 +894,7 @@ Crypto.prototype.ensureOlmSessionsForUsers = function(users) {
} }
return olmlib.ensureOlmSessionsForDevices( return olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, devicesByUser this._olmDevice, this._baseApis, devicesByUser,
); );
}; };
@@ -919,13 +919,13 @@ Crypto.prototype.exportRoomKeys = function() {
this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map( this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map(
(s) => { (s) => {
const sess = this._olmDevice.exportInboundGroupSession( const sess = this._olmDevice.exportInboundGroupSession(
s.senderKey, s.sessionId s.senderKey, s.sessionId,
); );
sess.algorithm = olmlib.MEGOLM_ALGORITHM; sess.algorithm = olmlib.MEGOLM_ALGORITHM;
return sess; return sess;
} },
) ),
); );
}; };
@@ -980,7 +980,7 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
throw new Error( throw new Error(
"Room was previously configured to use encryption, but is " + "Room was previously configured to use encryption, but is " +
"no longer. Perhaps the homeserver is hiding the " + "no longer. Perhaps the homeserver is hiding the " +
"configuration event." "configuration event.",
); );
} }
return null; return null;
@@ -995,7 +995,7 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
}; };
return alg.encryptMessage( return alg.encryptMessage(
room, event.getType(), event.getContent() room, event.getType(), event.getContent(),
).then(function(encryptedContent) { ).then(function(encryptedContent) {
event.makeEncrypted("m.room.encrypted", encryptedContent, myKeys); event.makeEncrypted("m.room.encrypted", encryptedContent, myKeys);
}); });
@@ -1098,7 +1098,7 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) {
const self = this; const self = this;
this._baseApis.sendToDevice( this._baseApis.sendToDevice(
"m.new_device", // OH HAI! "m.new_device", // OH HAI!
content content,
).done(function() { ).done(function() {
self._sessionStore.setDeviceAnnounced(); self._sessionStore.setDeviceAnnounced();
}); });
@@ -1206,7 +1206,7 @@ Crypto.prototype._flushNewDeviceRequests = function() {
users.map(function(u) { users.map(function(u) {
r[u] = r[u].catch(function(e) { r[u] = r[u].catch(function(e) {
console.error( console.error(
'Error updating device keys for user ' + u + ':', e 'Error updating device keys for user ' + u + ':', e,
); );
// reinstate the pending flags on any users which failed; this will // reinstate the pending flags on any users which failed; this will
@@ -1258,7 +1258,7 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) {
const AlgClass = algorithms.DECRYPTION_CLASSES[algorithm]; const AlgClass = algorithms.DECRYPTION_CLASSES[algorithm];
if (!AlgClass) { if (!AlgClass) {
throw new algorithms.DecryptionError( throw new algorithms.DecryptionError(
'Unknown encryption algorithm "' + algorithm + '".' 'Unknown encryption algorithm "' + algorithm + '".',
); );
} }
alg = new AlgClass({ alg = new AlgClass({

View File

@@ -52,7 +52,7 @@ module.exports.MEGOLM_ALGORITHM = "m.megolm.v1.aes-sha2";
module.exports.encryptMessageForDevice = function( module.exports.encryptMessageForDevice = function(
resultsObject, resultsObject,
ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice, ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice,
payloadFields payloadFields,
) { ) {
const deviceKey = recipientDevice.getIdentityKey(); const deviceKey = recipientDevice.getIdentityKey();
const sessionId = olmDevice.getSessionIdForDevice(deviceKey); const sessionId = olmDevice.getSessionIdForDevice(deviceKey);
@@ -64,7 +64,7 @@ module.exports.encryptMessageForDevice = function(
console.log( console.log(
"Using sessionid " + sessionId + " for device " + "Using sessionid " + sessionId + " for device " +
recipientUserId + ":" + recipientDevice.deviceId recipientUserId + ":" + recipientDevice.deviceId,
); );
const payload = { const payload = {
@@ -100,7 +100,7 @@ module.exports.encryptMessageForDevice = function(
utils.extend(payload, payloadFields); utils.extend(payload, payloadFields);
resultsObject[deviceKey] = olmDevice.encryptMessage( resultsObject[deviceKey] = olmDevice.encryptMessage(
deviceKey, sessionId, JSON.stringify(payload) deviceKey, sessionId, JSON.stringify(payload),
); );
}; };
@@ -119,7 +119,7 @@ module.exports.encryptMessageForDevice = function(
* {@link module:crypto~OlmSessionResult} * {@link module:crypto~OlmSessionResult}
*/ */
module.exports.ensureOlmSessionsForDevices = function( module.exports.ensureOlmSessionsForDevices = function(
olmDevice, baseApis, devicesByUser olmDevice, baseApis, devicesByUser,
) { ) {
const devicesWithoutSession = [ const devicesWithoutSession = [
// [userId, deviceId], ... // [userId, deviceId], ...
@@ -159,7 +159,7 @@ module.exports.ensureOlmSessionsForDevices = function(
const oneTimeKeyAlgorithm = "signed_curve25519"; const oneTimeKeyAlgorithm = "signed_curve25519";
return baseApis.claimOneTimeKeys( return baseApis.claimOneTimeKeys(
devicesWithoutSession, oneTimeKeyAlgorithm devicesWithoutSession, oneTimeKeyAlgorithm,
).then(function(res) { ).then(function(res) {
const otk_res = res.one_time_keys || {}; const otk_res = res.one_time_keys || {};
for (const userId in devicesByUser) { for (const userId in devicesByUser) {
@@ -187,13 +187,13 @@ module.exports.ensureOlmSessionsForDevices = function(
if (!oneTimeKey) { if (!oneTimeKey) {
console.warn( console.warn(
"No one-time keys (alg=" + oneTimeKeyAlgorithm + "No one-time keys (alg=" + oneTimeKeyAlgorithm +
") for device " + userId + ":" + deviceId ") for device " + userId + ":" + deviceId,
); );
continue; continue;
} }
const sid = _verifyKeyAndStartSession( const sid = _verifyKeyAndStartSession(
olmDevice, oneTimeKey, userId, deviceInfo olmDevice, oneTimeKey, userId, deviceInfo,
); );
result[userId][deviceId].sessionId = sid; result[userId][deviceId].sessionId = sid;
} }
@@ -208,12 +208,12 @@ function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) {
try { try {
_verifySignature( _verifySignature(
olmDevice, oneTimeKey, userId, deviceId, olmDevice, oneTimeKey, userId, deviceId,
deviceInfo.getFingerprint() deviceInfo.getFingerprint(),
); );
} catch (e) { } catch (e) {
console.error( console.error(
"Unable to verify signature on one-time key for device " + "Unable to verify signature on one-time key for device " +
userId + ":" + deviceId + ":", e userId + ":" + deviceId + ":", e,
); );
return null; return null;
} }
@@ -221,7 +221,7 @@ function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) {
let sid; let sid;
try { try {
sid = olmDevice.createOutboundSession( sid = olmDevice.createOutboundSession(
deviceInfo.getIdentityKey(), oneTimeKey.key deviceInfo.getIdentityKey(), oneTimeKey.key,
); );
} catch (e) { } catch (e) {
// possibly a bad key // possibly a bad key
@@ -251,7 +251,7 @@ function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) {
* @param {string} signingKey base64-ed ed25519 public key * @param {string} signingKey base64-ed ed25519 public key
*/ */
const _verifySignature = module.exports.verifySignature = function( const _verifySignature = module.exports.verifySignature = function(
olmDevice, obj, signingUserId, signingDeviceId, signingKey olmDevice, obj, signingUserId, signingDeviceId, signingKey,
) { ) {
const signKeyId = "ed25519:" + signingDeviceId; const signKeyId = "ed25519:" + signingDeviceId;
const signatures = obj.signatures || {}; const signatures = obj.signatures || {};
@@ -268,6 +268,6 @@ const _verifySignature = module.exports.verifySignature = function(
const json = anotherjson.stringify(obj); const json = anotherjson.stringify(obj);
olmDevice.verifySignature( olmDevice.verifySignature(
signingKey, json, signature signingKey, json, signature,
); );
}; };

View File

@@ -70,7 +70,7 @@ FilterComponent.prototype.check = function(event) {
event.getRoomId(), event.getRoomId(),
event.getSender(), event.getSender(),
event.getType(), event.getType(),
event.getContent() ? event.getContent().url !== undefined : false event.getContent() ? event.getContent().url !== undefined : false,
); );
}; };

View File

@@ -123,7 +123,7 @@ Filter.prototype.setDefinition = function(definition) {
this._room_filter = new FilterComponent(room_filter_fields); this._room_filter = new FilterComponent(room_filter_fields);
this._room_timeline_filter = new FilterComponent( this._room_timeline_filter = new FilterComponent(
room_filter_json ? (room_filter_json.timeline || {}) : {} room_filter_json ? (room_filter_json.timeline || {}) : {},
); );
// don't bother porting this from synapse yet: // don't bother porting this from synapse yet:

View File

@@ -163,7 +163,7 @@ module.exports.MatrixHttpApi.prototype = {
"Returning the raw JSON from uploadContent(). Future " + "Returning the raw JSON from uploadContent(). Future " +
"versions of the js-sdk will change this default, to " + "versions of the js-sdk will change this default, to " +
"return the parsed object. Set opts.rawResponse=false " + "return the parsed object. Set opts.rawResponse=false " +
"to change this behaviour now." "to change this behaviour now.",
); );
rawResponse = true; rawResponse = true;
} }
@@ -176,7 +176,7 @@ module.exports.MatrixHttpApi.prototype = {
"Returning only the content-uri from uploadContent(). " + "Returning only the content-uri from uploadContent(). " +
"Future versions of the js-sdk will change this " + "Future versions of the js-sdk will change this " +
"default, to return the whole response object. Set " + "default, to return the whole response object. Set " +
"opts.onlyContentUri=false to change this behaviour now." "opts.onlyContentUri=false to change this behaviour now.",
); );
onlyContentUri = true; onlyContentUri = true;
} else { } else {
@@ -279,7 +279,7 @@ module.exports.MatrixHttpApi.prototype = {
headers: {"Content-Type": contentType}, headers: {"Content-Type": contentType},
json: false, json: false,
bodyParser: bodyParser, bodyParser: bodyParser,
} },
); );
} }
@@ -321,7 +321,7 @@ module.exports.MatrixHttpApi.prototype = {
if (callback !== undefined && !utils.isFunction(callback)) { if (callback !== undefined && !utils.isFunction(callback)) {
throw Error( throw Error(
"Expected callback to be a function but got " + typeof callback "Expected callback to be a function but got " + typeof callback,
); );
} }
@@ -341,7 +341,7 @@ module.exports.MatrixHttpApi.prototype = {
const defer = q.defer(); const defer = q.defer();
this.opts.request( this.opts.request(
opts, opts,
requestCallback(defer, callback, this.opts.onlyData) requestCallback(defer, callback, this.opts.onlyData),
); );
// ID server does not always take JSON, so we can't use requests' 'json' // ID server does not always take JSON, so we can't use requests' 'json'
// option as we do with the home server, but it does return JSON, so // option as we do with the home server, but it does return JSON, so
@@ -390,7 +390,7 @@ module.exports.MatrixHttpApi.prototype = {
} }
const request_promise = this.request( const request_promise = this.request(
callback, method, path, queryParams, data, opts callback, method, path, queryParams, data, opts,
); );
const self = this; const self = this;
@@ -441,7 +441,7 @@ module.exports.MatrixHttpApi.prototype = {
const fullUri = this.opts.baseUrl + prefix + path; const fullUri = this.opts.baseUrl + prefix + path;
return this.requestOtherUrl( return this.requestOtherUrl(
callback, method, fullUri, queryParams, data, opts callback, method, fullUri, queryParams, data, opts,
); );
}, },
@@ -476,7 +476,7 @@ module.exports.MatrixHttpApi.prototype = {
callback, method, path, queryParams, data, { callback, method, path, queryParams, data, {
localTimeoutMs: localTimeoutMs, localTimeoutMs: localTimeoutMs,
prefix: prefix, prefix: prefix,
} },
); );
}, },
@@ -511,7 +511,7 @@ module.exports.MatrixHttpApi.prototype = {
callback, method, path, queryParams, data, { callback, method, path, queryParams, data, {
localTimeoutMs: localTimeoutMs, localTimeoutMs: localTimeoutMs,
prefix: prefix, prefix: prefix,
} },
); );
}, },
@@ -556,7 +556,7 @@ module.exports.MatrixHttpApi.prototype = {
} }
return this._request( return this._request(
callback, method, uri, queryParams, data, opts callback, method, uri, queryParams, data, opts,
); );
}, },
@@ -608,7 +608,7 @@ module.exports.MatrixHttpApi.prototype = {
_request: function(callback, method, uri, queryParams, data, opts) { _request: function(callback, method, uri, queryParams, data, opts) {
if (callback !== undefined && !utils.isFunction(callback)) { if (callback !== undefined && !utils.isFunction(callback)) {
throw Error( throw Error(
"Expected callback to be a function but got " + typeof callback "Expected callback to be a function but got " + typeof callback,
); );
} }
opts = opts || {}; opts = opts || {};
@@ -674,10 +674,10 @@ module.exports.MatrixHttpApi.prototype = {
const handlerFn = requestCallback( const handlerFn = requestCallback(
defer, callback, self.opts.onlyData, defer, callback, self.opts.onlyData,
parseErrorJson, parseErrorJson,
opts.bodyParser opts.bodyParser,
); );
handlerFn(err, response, body); handlerFn(err, response, body);
} },
); );
if (req && req.abort) { if (req && req.abort) {
// FIXME: This is EVIL, but I can't think of a better way to expose // FIXME: This is EVIL, but I can't think of a better way to expose
@@ -707,7 +707,7 @@ module.exports.MatrixHttpApi.prototype = {
*/ */
const requestCallback = function( const requestCallback = function(
defer, userDefinedCallback, onlyData, defer, userDefinedCallback, onlyData,
parseErrorJson, bodyParser parseErrorJson, bodyParser,
) { ) {
userDefinedCallback = userDefinedCallback || function() {}; userDefinedCallback = userDefinedCallback || function() {};

View File

@@ -154,7 +154,7 @@ InteractiveAuth.prototype = {
} }
self._data = error.data; self._data = error.data;
self._startNextAuthStage(); self._startNextAuthStage();
} },
).catch(this._completionDeferred.reject).done(); ).catch(this._completionDeferred.reject).done();
}, },

View File

@@ -259,14 +259,14 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
timeline, paginationToken) { timeline, paginationToken) {
if (!timeline) { if (!timeline) {
throw new Error( throw new Error(
"'timeline' not specified for EventTimelineSet.addEventsToTimeline" "'timeline' not specified for EventTimelineSet.addEventsToTimeline",
); );
} }
if (!toStartOfTimeline && timeline == this._liveTimeline) { if (!toStartOfTimeline && timeline == this._liveTimeline) {
throw new Error( throw new Error(
"EventTimelineSet.addEventsToTimeline cannot be used for adding events to " + "EventTimelineSet.addEventsToTimeline cannot be used for adding events to " +
"the live timeline - use Room.addLiveEvents instead" "the live timeline - use Room.addLiveEvents instead",
); );
} }
@@ -440,7 +440,7 @@ EventTimelineSet.prototype.addLiveEvent = function(event, duplicateStrategy) {
EventTimeline.setEventMetadata( EventTimeline.setEventMetadata(
event, event,
timeline.getState(EventTimeline.FORWARDS), timeline.getState(EventTimeline.FORWARDS),
false false,
); );
if (!tlEvents[j].encryptedType) { if (!tlEvents[j].encryptedType) {

View File

@@ -79,7 +79,7 @@ EventTimeline.prototype.initialiseState = function(stateEvents) {
utils.deepCopy( utils.deepCopy(
stateEvents.map(function(mxEvent) { stateEvents.map(function(mxEvent) {
return mxEvent.event; return mxEvent.event;
}) }),
), ),
function(ev) { function(ev) {
return new MatrixEvent(ev); return new MatrixEvent(ev);
@@ -288,11 +288,11 @@ EventTimeline.prototype.addEvent = function(event, atStart) {
EventTimeline.setEventMetadata = function(event, stateContext, toStartOfTimeline) { EventTimeline.setEventMetadata = function(event, stateContext, toStartOfTimeline) {
// set sender and target properties // set sender and target properties
event.sender = stateContext.getSentinelMember( event.sender = stateContext.getSentinelMember(
event.getSender() event.getSender(),
); );
if (event.getType() === "m.room.member") { if (event.getType() === "m.room.member") {
event.target = stateContext.getSentinelMember( event.target = stateContext.getSentinelMember(
event.getStateKey() event.getStateKey(),
); );
} }
if (event.isState()) { if (event.isState()) {

View File

@@ -70,7 +70,7 @@ module.exports.EventStatus = {
* Default: true. <strong>This property is experimental and may change.</strong> * Default: true. <strong>This property is experimental and may change.</strong>
*/ */
module.exports.MatrixEvent = function MatrixEvent( module.exports.MatrixEvent = function MatrixEvent(
event event,
) { ) {
this.event = event || {}; this.event = event || {};
this.sender = null; this.sender = null;

View File

@@ -197,13 +197,13 @@ RoomMember.prototype.getAvatarUrl =
} }
const rawUrl = this.events.member ? this.events.member.getContent().avatar_url : null; const rawUrl = this.events.member ? this.events.member.getContent().avatar_url : null;
const httpUrl = ContentRepo.getHttpUriForMxc( const httpUrl = ContentRepo.getHttpUriForMxc(
baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks,
); );
if (httpUrl) { if (httpUrl) {
return httpUrl; return httpUrl;
} else if (allowDefault) { } else if (allowDefault) {
return ContentRepo.getIdenticonUri( return ContentRepo.getIdenticonUri(
baseUrl, this.userId, width, height baseUrl, this.userId, width, height,
); );
} }
return null; return null;

View File

@@ -133,7 +133,7 @@ RoomState.prototype.setStateEvents = function(stateEvents) {
self.events[event.getType()][event.getStateKey()] = event; self.events[event.getType()][event.getStateKey()] = event;
if (event.getType() === "m.room.member") { if (event.getType() === "m.room.member") {
_updateDisplayNameCache( _updateDisplayNameCache(
self, event.getStateKey(), event.getContent().displayname self, event.getStateKey(), event.getContent().displayname,
); );
_updateThirdPartyTokenCache(self, event); _updateThirdPartyTokenCache(self, event);
} }
@@ -360,7 +360,7 @@ function _updateThirdPartyTokenCache(roomState, memberEvent) {
return; return;
} }
const threePidInvite = roomState.getStateEvents( const threePidInvite = roomState.getStateEvents(
"m.room.third_party_invite", token "m.room.third_party_invite", token,
); );
if (!threePidInvite) { if (!threePidInvite) {
return; return;

View File

@@ -108,7 +108,7 @@ function Room(roomId, opts) {
if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) { if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) {
throw new Error( throw new Error(
"opts.pendingEventOrdering MUST be either 'chronological' or " + "opts.pendingEventOrdering MUST be either 'chronological' or " +
"'detached'. Got: '" + opts.pendingEventOrdering + "'" "'detached'. Got: '" + opts.pendingEventOrdering + "'",
); );
} }
@@ -319,11 +319,11 @@ Room.prototype.getAvatarUrl = function(baseUrl, width, height, resizeMethod,
const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null; const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;
if (mainUrl) { if (mainUrl) {
return ContentRepo.getHttpUriForMxc( return ContentRepo.getHttpUriForMxc(
baseUrl, mainUrl, width, height, resizeMethod baseUrl, mainUrl, width, height, resizeMethod,
); );
} else if (allowDefault) { } else if (allowDefault) {
return ContentRepo.getIdenticonUri( return ContentRepo.getIdenticonUri(
baseUrl, this.roomId, width, height baseUrl, this.roomId, width, height,
); );
} }
@@ -345,7 +345,7 @@ Room.prototype.getAliases = function() {
const alias_event = alias_events[i]; const alias_event = alias_events[i];
if (utils.isArray(alias_event.getContent().aliases)) { if (utils.isArray(alias_event.getContent().aliases)) {
Array.prototype.push.apply( Array.prototype.push.apply(
alias_strings, alias_event.getContent().aliases alias_strings, alias_event.getContent().aliases,
); );
} }
} }
@@ -390,7 +390,7 @@ Room.prototype.addEventsToTimeline = function(events, toStartOfTimeline,
timeline, paginationToken) { timeline, paginationToken) {
timeline.getTimelineSet().addEventsToTimeline( timeline.getTimelineSet().addEventsToTimeline(
events, toStartOfTimeline, events, toStartOfTimeline,
timeline, paginationToken timeline, paginationToken,
); );
}; };
@@ -488,7 +488,7 @@ Room.prototype.getOrCreateFilteredTimelineSet = function(filter) {
timelineSet.getLiveTimeline().setPaginationToken( timelineSet.getLiveTimeline().setPaginationToken(
timeline.getPaginationToken(EventTimeline.BACKWARDS), timeline.getPaginationToken(EventTimeline.BACKWARDS),
EventTimeline.BACKWARDS EventTimeline.BACKWARDS,
); );
// alternatively, we could try to do something like this to try and re-paginate // alternatively, we could try to do something like this to try and re-paginate
@@ -569,7 +569,7 @@ Room.prototype._addLiveEvent = function(event, duplicateStrategy) {
// pointing to an event that wasn't yet in the timeline // pointing to an event that wasn't yet in the timeline
if (event.sender) { if (event.sender) {
this.addReceipt(synthesizeReceipt( this.addReceipt(synthesizeReceipt(
event.sender.userId, event, "m.read" event.sender.userId, event, "m.read",
), true); ), true);
// Any live events from a user could be taken as implicit // Any live events from a user could be taken as implicit
@@ -616,7 +616,7 @@ Room.prototype.addPendingEvent = function(event, txnId) {
EventTimeline.setEventMetadata( EventTimeline.setEventMetadata(
event, event,
this.getLiveTimeline().getState(EventTimeline.FORWARDS), this.getLiveTimeline().getState(EventTimeline.FORWARDS),
false false,
); );
this._txnToEvent[txnId] = event; this._txnToEvent[txnId] = event;
@@ -669,7 +669,7 @@ Room.prototype._handleRemoteEcho = function(remoteEvent, localEvent) {
this._pendingEventList, this._pendingEventList,
function(ev) { function(ev) {
return ev.getId() == oldEventId; return ev.getId() == oldEventId;
}, false }, false,
); );
} }
@@ -778,7 +778,7 @@ Room.prototype.updatePendingEvent = function(event, newStatus, newEventId) {
this._pendingEventList, this._pendingEventList,
function(ev) { function(ev) {
return ev.getId() == oldEventId; return ev.getId() == oldEventId;
}, false }, false,
); );
} }
this.removeEvent(oldEventId); this.removeEvent(oldEventId);
@@ -816,13 +816,13 @@ Room.prototype.addLiveEvents = function(events, duplicateStrategy) {
if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) { if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {
throw new Error( throw new Error(
"live timeline " + i + " is no longer live - it has a pagination token " + "live timeline " + i + " is no longer live - it has a pagination token " +
"(" + liveTimeline.getPaginationToken(EventTimeline.FORWARDS) + ")" "(" + liveTimeline.getPaginationToken(EventTimeline.FORWARDS) + ")",
); );
} }
if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) { if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {
throw new Error( throw new Error(
"live timeline " + i + " is no longer live - " + "live timeline " + i + " is no longer live - " +
"it has a neighbouring timeline" "it has a neighbouring timeline",
); );
} }
} }
@@ -884,13 +884,13 @@ Room.prototype.recalculate = function(userId) {
// consistent elsewhere. // consistent elsewhere.
const self = this; const self = this;
const membershipEvent = this.currentState.getStateEvents( const membershipEvent = this.currentState.getStateEvents(
"m.room.member", userId "m.room.member", userId,
); );
if (membershipEvent && membershipEvent.getContent().membership === "invite") { if (membershipEvent && membershipEvent.getContent().membership === "invite") {
const strippedStateEvents = membershipEvent.event.invite_room_state || []; const strippedStateEvents = membershipEvent.event.invite_room_state || [];
utils.forEach(strippedStateEvents, function(strippedEvent) { utils.forEach(strippedStateEvents, function(strippedEvent) {
const existingEvent = self.currentState.getStateEvents( const existingEvent = self.currentState.getStateEvents(
strippedEvent.type, strippedEvent.state_key strippedEvent.type, strippedEvent.state_key,
); );
if (!existingEvent) { if (!existingEvent) {
// set the fake stripped event instead // set the fake stripped event instead
@@ -1173,7 +1173,7 @@ function calculateRoomName(room, userId, ignoreRoomNameEvent) {
if (room.currentState.getMember(myMemberEvent.sender)) { if (room.currentState.getMember(myMemberEvent.sender)) {
// extract who invited us to the room // extract who invited us to the room
return "Invite from " + room.currentState.getMember( return "Invite from " + room.currentState.getMember(
myMemberEvent.sender myMemberEvent.sender,
).name; ).name;
} else if (allMembers[0].events.member) { } else if (allMembers[0].events.member) {
// use the sender field from the invite event, although this only // use the sender field from the invite event, although this only

View File

@@ -88,7 +88,7 @@ module.exports.setTimeout = function(func, delayMs) {
const idx = binarySearch( const idx = binarySearch(
_callbackList, function(el) { _callbackList, function(el) {
return el.runAt - runAt; return el.runAt - runAt;
} },
); );
_callbackList.splice(idx, 0, data); _callbackList.splice(idx, 0, data);

View File

@@ -126,7 +126,7 @@ MatrixScheduler.prototype.queueEvent = function(event) {
}); });
debuglog( debuglog(
"Queue algorithm dumped event %s into queue '%s'", "Queue algorithm dumped event %s into queue '%s'",
event.getId(), queueName event.getId(), queueName,
); );
_startProcessingQueues(this); _startProcessingQueues(this);
return defer.promise; return defer.promise;
@@ -213,7 +213,7 @@ function _processQueue(scheduler, queueName) {
} }
debuglog( debuglog(
"Queue '%s' has %s pending events", "Queue '%s' has %s pending events",
queueName, scheduler._queues[queueName].length queueName, scheduler._queues[queueName].length,
); );
// fire the process function and if it resolves, resolve the deferred. Else // fire the process function and if it resolves, resolve the deferred. Else
// invoke the retry algorithm. // invoke the retry algorithm.
@@ -230,11 +230,11 @@ function _processQueue(scheduler, queueName) {
const waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err); const waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);
debuglog( debuglog(
"retry(%s) err=%s event_id=%s waitTime=%s", "retry(%s) err=%s event_id=%s waitTime=%s",
obj.attempts, err, obj.event.getId(), waitTimeMs obj.attempts, err, obj.event.getId(), waitTimeMs,
); );
if (waitTimeMs === -1) { // give up (you quitter!) if (waitTimeMs === -1) { // give up (you quitter!)
debuglog( debuglog(
"Queue '%s' giving up on event %s", queueName, obj.event.getId() "Queue '%s' giving up on event %s", queueName, obj.event.getId(),
); );
// remove this from the queue // remove this from the queue
_removeNextEvent(scheduler, queueName); _removeNextEvent(scheduler, queueName);

View File

@@ -102,7 +102,7 @@ module.exports.MatrixInMemoryStore.prototype = {
user.setDisplayName(member.name); user.setDisplayName(member.name);
if (member.events.member) { if (member.events.member) {
user.setRawDisplayName( user.setRawDisplayName(
member.events.member.getDirectionalContent().displayname member.events.member.getDirectionalContent().displayname,
); );
} }
} }

View File

@@ -42,7 +42,7 @@ function WebStorageSessionStore(webStore) {
typeof(webStore.length) !== 'number' typeof(webStore.length) !== 'number'
) { ) {
throw new Error( throw new Error(
"Supplied webStore does not meet the WebStorage API interface" "Supplied webStore does not meet the WebStorage API interface",
); );
} }
} }
@@ -109,7 +109,7 @@ WebStorageSessionStore.prototype = {
const sessions = this.getEndToEndSessions(deviceKey) || {}; const sessions = this.getEndToEndSessions(deviceKey) || {};
sessions[sessionId] = session; sessions[sessionId] = session;
setJsonItem( setJsonItem(
this.store, keyEndToEndSessions(deviceKey), sessions this.store, keyEndToEndSessions(deviceKey), sessions,
); );
}, },

View File

@@ -122,7 +122,7 @@ SyncApi.prototype._registerStateListeners = function(room) {
[ [
"RoomMember.name", "RoomMember.typing", "RoomMember.powerLevel", "RoomMember.name", "RoomMember.typing", "RoomMember.powerLevel",
"RoomMember.membership", "RoomMember.membership",
] ],
); );
}); });
}; };
@@ -158,11 +158,11 @@ SyncApi.prototype.syncLeftRooms = function() {
}; };
return client.getOrCreateFilter( return client.getOrCreateFilter(
getFilterName(client.credentials.userId, "LEFT_ROOMS"), filter getFilterName(client.credentials.userId, "LEFT_ROOMS"), filter,
).then(function(filterId) { ).then(function(filterId) {
qps.filter = filterId; qps.filter = filterId;
return client._http.authedRequest( return client._http.authedRequest(
undefined, "GET", "/sync", qps, undefined, localTimeoutMs undefined, "GET", "/sync", qps, undefined, localTimeoutMs,
); );
}).then(function(data) { }).then(function(data) {
let leaveRooms = []; let leaveRooms = [];
@@ -226,13 +226,13 @@ SyncApi.prototype.peek = function(roomId) {
// FIXME: Mostly duplicated from _processRoomEvents but not entirely // FIXME: Mostly duplicated from _processRoomEvents but not entirely
// because "state" in this API is at the BEGINNING of the chunk // because "state" in this API is at the BEGINNING of the chunk
const oldStateEvents = utils.map( const oldStateEvents = utils.map(
utils.deepCopy(response.state), client.getEventMapper() utils.deepCopy(response.state), client.getEventMapper(),
); );
const stateEvents = utils.map( const stateEvents = utils.map(
response.state, client.getEventMapper() response.state, client.getEventMapper(),
); );
const messages = utils.map( const messages = utils.map(
response.messages.chunk, client.getEventMapper() response.messages.chunk, client.getEventMapper(),
); );
// XXX: copypasted from /sync until we kill off this // XXX: copypasted from /sync until we kill off this
@@ -401,7 +401,7 @@ SyncApi.prototype.sync = function() {
} }
client.getOrCreateFilter( client.getOrCreateFilter(
getFilterName(client.credentials.userId), filter getFilterName(client.credentials.userId), filter,
).done(function(filterId) { ).done(function(filterId) {
// reset the notifications timeline to prepare it to paginate from // reset the notifications timeline to prepare it to paginate from
// the current point in time. // the current point in time.
@@ -511,7 +511,7 @@ SyncApi.prototype._sync = function(syncOptions) {
const clientSideTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; const clientSideTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;
this._currentSyncRequest = client._http.authedRequest( this._currentSyncRequest = client._http.authedRequest(
undefined, "GET", "/sync", qps, undefined, clientSideTimeoutMs undefined, "GET", "/sync", qps, undefined, clientSideTimeoutMs,
); );
this._currentSyncRequest.done(function(data) { this._currentSyncRequest.done(function(data) {
@@ -644,7 +644,7 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
} }
client.emit("accountData", accountDataEvent); client.emit("accountData", accountDataEvent);
return accountDataEvent; return accountDataEvent;
} },
); );
} }
@@ -660,13 +660,13 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
content.msgtype == "m.bad.encrypted" content.msgtype == "m.bad.encrypted"
) { ) {
console.warn( console.warn(
"Unable to decrypt to-device event: " + content.body "Unable to decrypt to-device event: " + content.body,
); );
return; return;
} }
client.emit("toDeviceEvent", toDeviceEvent); client.emit("toDeviceEvent", toDeviceEvent);
} },
); );
} }
@@ -718,10 +718,10 @@ SyncApi.prototype._processSyncResponse = function(syncToken, data) {
// we do this first so it's correct when any of the events fire // we do this first so it's correct when any of the events fire
if (joinObj.unread_notifications) { if (joinObj.unread_notifications) {
room.setUnreadNotificationCount( room.setUnreadNotificationCount(
'total', joinObj.unread_notifications.notification_count 'total', joinObj.unread_notifications.notification_count,
); );
room.setUnreadNotificationCount( room.setUnreadNotificationCount(
'highlight', joinObj.unread_notifications.highlight_count 'highlight', joinObj.unread_notifications.highlight_count,
); );
} }
@@ -880,7 +880,7 @@ SyncApi.prototype._startKeepAlives = function(delay) {
if (delay > 0) { if (delay > 0) {
self._keepAliveTimer = setTimeout( self._keepAliveTimer = setTimeout(
self._pokeKeepAlive.bind(self), self._pokeKeepAlive.bind(self),
delay delay,
); );
} else { } else {
self._pokeKeepAlive(); self._pokeKeepAlive();
@@ -912,7 +912,7 @@ SyncApi.prototype._pokeKeepAlive = function() {
{ {
prefix: '', prefix: '',
localTimeoutMs: 15 * 1000, localTimeoutMs: 15 * 1000,
} },
).done(function() { ).done(function() {
success(); success();
}, function(err) { }, function(err) {
@@ -926,7 +926,7 @@ SyncApi.prototype._pokeKeepAlive = function() {
} else { } else {
self._keepAliveTimer = setTimeout( self._keepAliveTimer = setTimeout(
self._pokeKeepAlive.bind(self), self._pokeKeepAlive.bind(self),
5000 + Math.floor(Math.random() * 5000) 5000 + Math.floor(Math.random() * 5000),
); );
// A keepalive has failed, so we emit the // A keepalive has failed, so we emit the
// error state (whether or not this is the // error state (whether or not this is the
@@ -1045,8 +1045,8 @@ SyncApi.prototype._processRoomEvents = function(room, stateEventList,
utils.deepCopy( utils.deepCopy(
stateEventList.map(function(mxEvent) { stateEventList.map(function(mxEvent) {
return mxEvent.event; return mxEvent.event;
}) }),
), client.getEventMapper() ), client.getEventMapper(),
); );
const stateEvents = stateEventList; const stateEvents = stateEventList;

View File

@@ -51,7 +51,7 @@ module.exports.encodeUri = function(pathTemplate, variables) {
continue; continue;
} }
pathTemplate = pathTemplate.replace( pathTemplate = pathTemplate.replace(
key, encodeURIComponent(variables[key]) key, encodeURIComponent(variables[key]),
); );
} }
return pathTemplate; return pathTemplate;

View File

@@ -141,8 +141,8 @@ MatrixCall.prototype.placeScreenSharingCall =
self.emit("error", self.emit("error",
callError( callError(
MatrixCall.ERR_NO_USER_MEDIA, MatrixCall.ERR_NO_USER_MEDIA,
"Failed to get screen-sharing stream: " + err "Failed to get screen-sharing stream: " + err,
) ),
); );
}); });
this.type = 'video'; this.type = 'video';
@@ -311,7 +311,7 @@ MatrixCall.prototype._initWithInvite = function(event) {
this.peerConn.setRemoteDescription( this.peerConn.setRemoteDescription(
new this.webRtc.RtcSessionDescription(this.msg.offer), new this.webRtc.RtcSessionDescription(this.msg.offer),
hookCallback(self, self._onSetRemoteDescriptionSuccess), hookCallback(self, self._onSetRemoteDescriptionSuccess),
hookCallback(self, self._onSetRemoteDescriptionError) hookCallback(self, self._onSetRemoteDescriptionError),
); );
} }
setState(this, 'ringing'); setState(this, 'ringing');
@@ -370,7 +370,7 @@ MatrixCall.prototype.answer = function() {
this.webRtc.getUserMedia( this.webRtc.getUserMedia(
_getUserMediaVideoContraints(this.type), _getUserMediaVideoContraints(this.type),
hookCallback(self, self._gotUserMediaForAnswer), hookCallback(self, self._gotUserMediaForAnswer),
hookCallback(self, self._getUserMediaFailed) hookCallback(self, self._getUserMediaFailed),
); );
setState(this, 'wait_local_media'); setState(this, 'wait_local_media');
} else if (this.localAVStream) { } else if (this.localAVStream) {
@@ -528,7 +528,7 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) {
this.peerConn.addStream(stream); this.peerConn.addStream(stream);
this.peerConn.createOffer( this.peerConn.createOffer(
hookCallback(self, self._gotLocalOffer), hookCallback(self, self._gotLocalOffer),
hookCallback(self, self._getLocalOfferFailed) hookCallback(self, self._getLocalOfferFailed),
); );
setState(self, 'create_offer'); setState(self, 'create_offer');
}; };
@@ -600,7 +600,7 @@ MatrixCall.prototype._gotLocalIceCandidate = function(event) {
if (event.candidate) { if (event.candidate) {
debuglog( debuglog(
"Got local ICE " + event.candidate.sdpMid + " candidate: " + "Got local ICE " + event.candidate.sdpMid + " candidate: " +
event.candidate.candidate event.candidate.candidate,
); );
// As with the offer, note we need to make a copy of this object, not // As with the offer, note we need to make a copy of this object, not
// pass the original: that broke in Chrome ~m43. // pass the original: that broke in Chrome ~m43.
@@ -627,7 +627,7 @@ MatrixCall.prototype._gotRemoteIceCandidate = function(cand) {
this.peerConn.addIceCandidate( this.peerConn.addIceCandidate(
new this.webRtc.RtcIceCandidate(cand), new this.webRtc.RtcIceCandidate(cand),
function() {}, function() {},
function(e) {} function(e) {},
); );
}; };
@@ -645,7 +645,7 @@ MatrixCall.prototype._receivedAnswer = function(msg) {
this.peerConn.setRemoteDescription( this.peerConn.setRemoteDescription(
new this.webRtc.RtcSessionDescription(msg.answer), new this.webRtc.RtcSessionDescription(msg.answer),
hookCallback(self, self._onSetRemoteDescriptionSuccess), hookCallback(self, self._onSetRemoteDescriptionSuccess),
hookCallback(self, self._onSetRemoteDescriptionError) hookCallback(self, self._onSetRemoteDescriptionError),
); );
setState(self, 'connecting'); setState(self, 'connecting');
}; };
@@ -705,7 +705,7 @@ MatrixCall.prototype._gotLocalOffer = function(description) {
MatrixCall.prototype._getLocalOfferFailed = function(error) { MatrixCall.prototype._getLocalOfferFailed = function(error) {
this.emit( this.emit(
"error", "error",
callError(MatrixCall.ERR_LOCAL_OFFER_FAILED, "Failed to start audio for call!") callError(MatrixCall.ERR_LOCAL_OFFER_FAILED, "Failed to start audio for call!"),
); );
}; };
@@ -720,8 +720,8 @@ MatrixCall.prototype._getUserMediaFailed = function(error) {
callError( callError(
MatrixCall.ERR_NO_USER_MEDIA, MatrixCall.ERR_NO_USER_MEDIA,
"Couldn't start capturing media! Is your microphone set up and " + "Couldn't start capturing media! Is your microphone set up and " +
"does this app have permission?" "does this app have permission?",
) ),
); );
this.hangup("user_media_failed"); this.hangup("user_media_failed");
}; };
@@ -735,7 +735,7 @@ MatrixCall.prototype._onIceConnectionStateChanged = function() {
return; // because ICE can still complete as we're ending the call return; // because ICE can still complete as we're ending the call
} }
debuglog( debuglog(
"Ice connection state changed to: " + this.peerConn.iceConnectionState "Ice connection state changed to: " + this.peerConn.iceConnectionState,
); );
// ideally we'd consider the call to be connected when we get media but // ideally we'd consider the call to be connected when we get media but
// chrome doesn't implement any of the 'onstarted' events yet // chrome doesn't implement any of the 'onstarted' events yet
@@ -755,7 +755,7 @@ MatrixCall.prototype._onIceConnectionStateChanged = function() {
MatrixCall.prototype._onSignallingStateChanged = function() { MatrixCall.prototype._onSignallingStateChanged = function() {
debuglog( debuglog(
"call " + this.callId + ": Signalling state changed to: " + "call " + this.callId + ": Signalling state changed to: " +
this.peerConn.signalingState this.peerConn.signalingState,
); );
}; };
@@ -1031,7 +1031,7 @@ const _tryPlayRemoteAudioStream = function(self) {
const checkForErrorListener = function(self) { const checkForErrorListener = function(self) {
if (self.listeners("error").length === 0) { if (self.listeners("error").length === 0) {
throw new Error( throw new Error(
"You MUST attach an error listener using call.on('error', function() {})" "You MUST attach an error listener using call.on('error', function() {})",
); );
} }
}; };
@@ -1073,7 +1073,7 @@ const _sendCandidateQueue = function(self) {
if (self.candidateSendTries > 5) { if (self.candidateSendTries > 5) {
debuglog( debuglog(
"Failed to send candidates on attempt %s. Giving up for now.", "Failed to send candidates on attempt %s. Giving up for now.",
self.candidateSendTries self.candidateSendTries,
); );
self.candidateSendTries = 0; self.candidateSendTries = 0;
return; return;
@@ -1093,7 +1093,7 @@ const _placeCallWithConstraints = function(self, constraints) {
self.webRtc.getUserMedia( self.webRtc.getUserMedia(
constraints, constraints,
hookCallback(self, self._gotUserMediaForInvite), hookCallback(self, self._gotUserMediaForInvite),
hookCallback(self, self._getUserMediaFailed) hookCallback(self, self._getUserMediaFailed),
); );
setState(self, 'wait_local_media'); setState(self, 'wait_local_media');
self.direction = 'outbound'; self.direction = 'outbound';
@@ -1131,7 +1131,7 @@ const _getChromeScreenSharingConstraints = function(call) {
if (!screen) { if (!screen) {
call.emit("error", callError( call.emit("error", callError(
MatrixCall.ERR_NO_USER_MEDIA, MatrixCall.ERR_NO_USER_MEDIA,
"Couldn't determine screen sharing constaints." "Couldn't determine screen sharing constaints.",
)); ));
return; return;
} }