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

Merge branch 'matthew/warn-unknown-devices' into matthew/blacklist-unverified

This commit is contained in:
Richard van der Hoff
2017-01-26 13:25:10 +00:00
47 changed files with 504 additions and 413 deletions

View File

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

1
.gitignore vendored
View File

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

View File

@@ -0,0 +1,31 @@
Random notes from Matthew on the two possible approaches for warning users about unexpected
unverified devices popping up in their rooms....
Original idea...
================
Warn when an existing user adds an unknown device to a room.
Warn when a user joins the room with unverified or unknown devices.
Warn when you initial sync if the room has any unverified devices in it.
^ this is good enough if we're doing local storage.
OR, better:
Warn when you initial sync if the room has any new undefined devices since you were last there.
=> This means persisting the rooms that devices are in, across initial syncs.
Updated idea...
===============
Warn when the user tries to send a message:
- If the room has unverified devices which the user has not yet been told about in the context of this room
...or in the context of this user? currently all verification is per-user, not per-room.
...this should be good enough.
- so track whether we have warned the user or not about unverified devices - blocked, unverified, verified, unverified_warned.
throw an error when trying to encrypt if there are pure unverified devices there
app will have to search for the devices which are pure unverified to warn about them - have to do this from MembersList anyway?
- or megolm could warn which devices are causing the problems.
Why do we wait to establish outbound sessions? It just makes a horrible pause when we first try to send a message... but could otherwise unnecessarily consume resources?

View File

@@ -4,8 +4,9 @@
"description": "Matrix Client-Server SDK for Javascript",
"main": "index.js",
"scripts": {
"test": "istanbul cover --report cobertura --config .istanbul.yml -i \"lib/**/*.js\" jasmine-node -- spec --verbose --junitreport --captureExceptions",
"check": "jasmine-node spec --verbose --junitreport --captureExceptions",
"buildtest": "babel -s -d specbuild spec",
"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",
"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",
@@ -52,6 +53,7 @@
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-eslint": "^7.1.1",
"babel-preset-es2015": "^6.18.0",
"eslint": "^3.13.1",
"eslint-config-google": "^0.7.1",

View File

@@ -304,7 +304,7 @@ function expectBobSendMessageRequest() {
function sendMessage(client) {
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
return aliClient.downloadKeys(['@bob:id']);
}).nodeify(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(
aliClient.downloadKeys([bobUserId, eveUserId]),
aliHttpBackend.flush("/keys/query", 1)
aliHttpBackend.flush("/keys/query", 1),
).then(function() {
// should get an empty list
expect(aliClient.listDeviceKeys(bobUserId)).toEqual([]);
@@ -618,7 +618,7 @@ describe("MatrixClient crypto", function() {
q.all(
aliClient.downloadKeys([bobUserId]),
aliHttpBackend.flush("/keys/query", 1)
aliHttpBackend.flush("/keys/query", 1),
).then(function() {
// should get an empty list
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"].state.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) {
@@ -121,7 +121,7 @@ describe("MatrixClient events", function() {
}
}
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() {
expect(expectedEvents.length).toEqual(
0, "Failed to see all events from /sync calls"
0, "Failed to see all events from /sync calls",
);
done();
});
@@ -149,7 +149,7 @@ describe("MatrixClient events", function() {
expect(event.event).toEqual(SYNC_DATA.presence.events[0]);
expect(user.presence).toEqual(
SYNC_DATA.presence.events[0].content.presence
SYNC_DATA.presence.events[0].content.presence,
);
});
client.startClient();
@@ -182,13 +182,13 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() {
expect(roomInvokeCount).toEqual(
1, "Room fired wrong number of times."
1, "Room fired wrong number of times.",
);
expect(roomNameInvokeCount).toEqual(
1, "Room.name fired wrong number of times."
1, "Room.name fired wrong number of times.",
);
expect(timelineFireCount).toEqual(
3, "Room.timeline fired the wrong number of times"
3, "Room.timeline fired the wrong number of times",
);
done();
});
@@ -208,7 +208,7 @@ describe("MatrixClient events", function() {
eventsInvokeCount++;
const index = roomStateEventTypes.indexOf(event.getType());
expect(index).not.toEqual(
-1, "Unexpected room state event type: " + event.getType()
-1, "Unexpected room state event type: " + event.getType(),
);
if (index >= 0) {
roomStateEventTypes.splice(index, 1);
@@ -231,13 +231,13 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() {
expect(membersInvokeCount).toEqual(
1, "RoomState.members fired wrong number of times"
1, "RoomState.members fired wrong number of times",
);
expect(newMemberInvokeCount).toEqual(
1, "RoomState.newMember fired wrong number of times"
1, "RoomState.newMember fired wrong number of times",
);
expect(eventsInvokeCount).toEqual(
2, "RoomState.events fired wrong number of times"
2, "RoomState.events fired wrong number of times",
);
done();
});
@@ -270,16 +270,16 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() {
expect(typingInvokeCount).toEqual(
1, "RoomMember.typing fired wrong number of times"
1, "RoomMember.typing fired wrong number of times",
);
expect(powerLevelInvokeCount).toEqual(
0, "RoomMember.powerLevel fired wrong number of times"
0, "RoomMember.powerLevel fired wrong number of times",
);
expect(nameInvokeCount).toEqual(
0, "RoomMember.name fired wrong number of times"
0, "RoomMember.name fired wrong number of times",
);
expect(membershipInvokeCount).toEqual(
1, "RoomMember.membership fired wrong number of times"
1, "RoomMember.membership fired wrong number of times",
);
done();
});
@@ -297,7 +297,7 @@ describe("MatrixClient events", function() {
httpBackend.flush().done(function() {
expect(sessionLoggedOutCount).toEqual(
1, "Session.logged_out fired wrong number of times"
1, "Session.logged_out fired wrong number of times",
);
done();
});

View File

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

View File

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

View File

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

View File

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

View File

@@ -114,7 +114,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({
room: roomOne, mship: "invite", user: userC,
})
}),
);
httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -122,7 +122,7 @@ describe("MatrixClient syncing", function() {
200, {
avatar_url: "mxc://flibble/wibble",
displayname: "The Boss",
}
},
);
client.startClient({
@@ -133,7 +133,7 @@ describe("MatrixClient syncing", function() {
const member = client.getRoom(roomOne).getMember(userC);
expect(member.name).toEqual("The Boss");
expect(
member.getAvatarUrl("home.server.url", null, null, null, false)
member.getAvatarUrl("home.server.url", null, null, null, false),
).toBeDefined();
done();
});
@@ -148,7 +148,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({
room: roomOne, mship: "invite", user: userC,
})
}),
);
httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -173,7 +173,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({
room: roomOne, mship: "invite", user: userC,
})
}),
);
httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -199,7 +199,7 @@ describe("MatrixClient syncing", function() {
syncData.rooms.join[roomOne].state.events.push(
utils.mkMembership({
room: roomOne, mship: "invite", user: userC,
})
}),
);
httpBackend.when("GET", "/sync").respond(200, syncData);
@@ -210,7 +210,7 @@ describe("MatrixClient syncing", function() {
const member = client.getRoom(roomOne).getMember(userC);
expect(member.name).toEqual(userC);
expect(
member.getAvatarUrl("home.server.url", null, null, null, false)
member.getAvatarUrl("home.server.url", null, null, null, false),
).toBeNull();
done();
});
@@ -362,7 +362,7 @@ describe("MatrixClient syncing", function() {
const room = client.getRoom(roomOne);
// should have clobbered the name to the one from /events
expect(room.name).toEqual(
nextSyncData.rooms.join[roomOne].state.events[0].content.name
nextSyncData.rooms.join[roomOne].state.events[0].content.name,
);
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();
};
@@ -143,7 +146,7 @@ function createOlmSession(olmAccount, recipientTestClient) {
const session = new Olm.Session();
session.create_outbound(
olmAccount, recipientTestClient.getDeviceKey(), otk.key
olmAccount, recipientTestClient.getDeviceKey(), otk.key,
);
return session;
}
@@ -287,7 +290,7 @@ function getSyncResponse(roomMembers) {
testUtils.mkMembership({
mship: 'join',
sender: roomMembers[i],
})
}),
);
}
@@ -384,7 +387,7 @@ describe("megolm", function() {
testUtils.beforeEach(this); // eslint-disable-line no-invalid-this
aliceTestClient = new TestClient(
"@alice:localhost", "xzcvb", "akjgkrgjs"
"@alice:localhost", "xzcvb", "akjgkrgjs",
);
testOlmAccount = new Olm.Account();
@@ -533,13 +536,26 @@ describe("megolm", function() {
aliceTestClient.httpBackend.when('GET', '/sync').respond(200, syncResponse);
return aliceTestClient.httpBackend.flush('/sync', 1);
}).then(function() {
let inboundGroupSession;
// start out with the device unknown - the send should be rejected.
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(
'PUT', '/sendToDevice/m.room.encrypted/'
'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) {
const m = content.messages['@bob:xyz'].DEVICE_ID;
const ct = m.ciphertext[testSenderKey];
@@ -552,7 +568,7 @@ describe("megolm", function() {
});
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, function(path, content) {
const ct = content.ciphertext;
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([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.client.resendEvent(pendingMsg, room),
aliceTestClient.httpBackend.flush(),
]);
}).nodeify(done);
@@ -598,7 +617,7 @@ describe("megolm", function() {
console.log("Telling alice to send a megolm message");
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, {
event_id: '$event_id',
});
@@ -632,7 +651,7 @@ describe("megolm", function() {
console.log('Forcing alice to download our device keys');
aliceTestClient.httpBackend.when('POST', '/keys/query').respond(
200, getTestKeysQueryResponse('@bob:xyz')
200, getTestKeysQueryResponse('@bob:xyz'),
);
return q.all([
@@ -645,7 +664,7 @@ describe("megolm", function() {
console.log('Telling alice to send a megolm message');
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, {
event_id: '$event_id',
});
@@ -678,14 +697,23 @@ describe("megolm", function() {
return aliceTestClient.httpBackend.flush('/sync', 1);
}).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(
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(
'PUT', '/sendToDevice/m.room.encrypted/'
'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) {
console.log('sendToDevice: ', content);
const m = content.messages['@bob:xyz'].DEVICE_ID;
@@ -699,7 +727,7 @@ describe("megolm", function() {
});
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, function(path, content) {
console.log('/send:', content);
expect(content.session_id).toEqual(megolmSessionId);
@@ -718,7 +746,7 @@ describe("megolm", function() {
console.log('Telling alice to send another megolm message');
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, function(path, content) {
console.log('/send:', content);
expect(content.session_id).not.toEqual(megolmSessionId);
@@ -737,14 +765,14 @@ describe("megolm", function() {
// https://github.com/vector-im/riot-web/issues/2676
it("Alice should send to her other devices", function(done) {
// 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 inboundGroupSession;
let decrypted;
return aliceTestClient.start(
getTestKeysQueryResponse(aliceTestClient.userId)
getTestKeysQueryResponse(aliceTestClient.userId),
).then(function() {
// an encrypted room with just alice
const syncResponse = {
@@ -774,6 +802,7 @@ describe("megolm", function() {
return aliceTestClient.httpBackend.flush();
}).then(function() {
aliceTestClient.client.setDeviceKnown(aliceTestClient.userId, 'DEVICE_ID');
aliceTestClient.httpBackend.when('POST', '/keys/claim').respond(
200, function(path, content) {
expect(content.one_time_keys[aliceTestClient.userId].DEVICE_ID)
@@ -782,7 +811,7 @@ describe("megolm", function() {
});
aliceTestClient.httpBackend.when(
'PUT', '/sendToDevice/m.room.encrypted/'
'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) {
console.log("sendToDevice: ", content);
const m = content.messages[aliceTestClient.userId].DEVICE_ID;
@@ -800,7 +829,7 @@ describe("megolm", function() {
});
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, function(path, content) {
const ct = content.ciphertext;
const r = inboundGroupSession.decrypt(ct);
@@ -832,7 +861,7 @@ describe("megolm", function() {
let sendPromise;
aliceTestClient.httpBackend.when(
'PUT', '/sendToDevice/m.room.encrypted/'
'PUT', '/sendToDevice/m.room.encrypted/',
).respond(200, function(path, content) {
const m = content.messages['@bob:xyz'].DEVICE_ID;
const ct = m.ciphertext[testSenderKey];
@@ -845,7 +874,7 @@ describe("megolm", function() {
});
aliceTestClient.httpBackend.when(
'PUT', '/send/'
'PUT', '/send/',
).respond(200, function(path, content) {
const ct = content.ciphertext;
const r = inboundGroupSession.decrypt(ct);
@@ -882,12 +911,17 @@ describe("megolm", function() {
// this will block
downloadPromise = aliceTestClient.client.downloadKeys(['@bob:xyz']);
}).then(function() {
// so will this.
sendPromise = aliceTestClient.client.sendTextMessage(ROOM_ID, 'test');
}).then(function() {
sendPromise = aliceTestClient.client.sendTextMessage(ROOM_ID, 'test')
.then(() => {
throw new Error("sendTextMessage failed on an unknown device");
}, (e) => {
expect(e.name).toEqual("UnknownDeviceError");
});
aliceTestClient.httpBackend.when('POST', '/keys/query').respond(
200, getTestKeysQueryResponse('@bob:xyz')
200, getTestKeysQueryResponse('@bob:xyz'),
);
return aliceTestClient.httpBackend.flush();
@@ -902,7 +936,7 @@ describe("megolm", function() {
return aliceTestClient.start().then(() => {
const p2pSession = createOlmSession(
testOlmAccount, aliceTestClient
testOlmAccount, aliceTestClient,
);
const groupSession = new Olm.OutboundGroupSession();
@@ -953,7 +987,7 @@ describe("megolm", function() {
aliceTestClient.stop();
aliceTestClient = new TestClient(
"@alice:localhost", "device2", "access_token2"
"@alice:localhost", "device2", "access_token2",
);
aliceTestClient.client.importRoomKeys(exported);

View File

@@ -43,13 +43,13 @@ HttpBackend.prototype = {
let flushed = 0;
let triedWaiting = false;
console.log(
"HTTP backend flushing... (path=%s numToFlush=%s)", path, numToFlush
"HTTP backend flushing... (path=%s numToFlush=%s)", path, numToFlush,
);
const tryFlush = function() {
// if there's more real requests and more expected requests, flush 'em.
console.log(
" trying to flush queue => reqs=%s expected=%s [%s]",
self.requests.length, self.expectedRequests.length, path
self.requests.length, self.expectedRequests.length, path,
);
if (self._takeFromQueue(path)) {
// try again on the next tick.
@@ -122,7 +122,7 @@ HttpBackend.prototype = {
body = body(req.path, req.data);
}
req.callback(
testResponse.err, testResponse.response, body
testResponse.err, testResponse.response, body,
);
matchingReq = null;
}
@@ -140,7 +140,7 @@ HttpBackend.prototype = {
const firstOutstandingReq = this.requests[0] || {};
expect(this.requests.length).toEqual(0,
"Expected no more HTTP requests but received request to " +
firstOutstandingReq.path
firstOutstandingReq.path,
);
},
@@ -150,7 +150,7 @@ HttpBackend.prototype = {
verifyNoOutstandingExpectation: function() {
const firstOutstandingExpectation = this.expectedRequests[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";
expect(
ContentRepo.getHttpUriForMxc(
baseUrl, httpUrl, undefined, undefined, undefined, true
)
baseUrl, httpUrl, undefined, undefined, undefined, true,
),
).toEqual(httpUrl);
});
@@ -28,7 +28,7 @@ describe("ContentRepo", function() {
function() {
const mxcUri = "mxc://server.name/resourceid";
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";
expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32, 64, "crop")).toEqual(
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";
expect(ContentRepo.getHttpUriForMxc(baseUrl, mxcUri, 32)).toEqual(
baseUrl + "/_matrix/media/v1/thumbnail/server.name/resourceid" +
"?width=32#automade"
"?width=32#automade",
);
});
@@ -58,7 +58,7 @@ describe("ContentRepo", function() {
function() {
const mxcUri = "mxc://server.name/resourceid#automade";
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() {
expect(ContentRepo.getIdenticonUri(baseUrl, "foobar")).toEqual(
baseUrl + "/_matrix/media/v1/identicon/foobar" +
"?width=96&height=96"
"?width=96&height=96",
);
});
it("should be able to set custom w/h", function() {
expect(ContentRepo.getIdenticonUri(baseUrl, "foobar", 32, 64)).toEqual(
baseUrl + "/_matrix/media/v1/identicon/foobar" +
"?width=32&height=64"
"?width=32&height=64",
);
});
it("should URL encode the identicon string", function() {
expect(ContentRepo.getIdenticonUri(baseUrl, "foo#bar", 32, 64)).toEqual(
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);
expect(timeline._startState.setStateEvents).toHaveBeenCalledWith(
events
events,
);
expect(timeline._endState.setStateEvents).toHaveBeenCalledWith(
events
events,
);
});

View File

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

View File

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

View File

@@ -163,10 +163,10 @@ describe("Room", function() {
];
room.addLiveEvents(events);
expect(room.currentState.setStateEvents).toHaveBeenCalledWith(
[events[0]]
[events[0]],
);
expect(room.currentState.setStateEvents).toHaveBeenCalledWith(
[events[1]]
[events[1]],
);
expect(events[0].forwardLooking).toBe(true);
expect(events[1].forwardLooking).toBe(true);
@@ -222,7 +222,7 @@ describe("Room", function() {
break;
}
callCount += 1;
}
},
);
// first add the local echo
@@ -368,10 +368,10 @@ describe("Room", function() {
room.addEventsToTimeline(events, true, room.getLiveTimeline());
expect(room.oldState.setStateEvents).toHaveBeenCalledWith(
[events[0]]
[events[0]],
);
expect(room.oldState.setStateEvents).toHaveBeenCalledWith(
[events[1]]
[events[1]],
);
expect(events[0].forwardLooking).toBe(false);
expect(events[1].forwardLooking).toBe(false);
@@ -680,7 +680,7 @@ describe("Room", function() {
});
room.currentState.getMember.andCallFake(function(userId) {
const memberEvent = room.currentState.getStateEvents(
"m.room.member", userId
"m.room.member", userId,
);
return {
name: memberEvent.event.content &&
@@ -1003,7 +1003,7 @@ describe("Room", function() {
mkRecord(eventToAck.getId(), "m.read", userD, ts),
]));
expect(room.getUsersReadUpTo(eventToAck)).toEqual(
[userB, userC, userD]
[userB, userC, userD],
);
});
@@ -1164,10 +1164,10 @@ describe("Room", function() {
room.addPendingEvent(eventB, "TXN1");
room.addLiveEvents([eventC]);
expect(room.timeline).toEqual(
[eventA, eventC]
[eventA, eventC],
);
expect(room.getPendingEvents()).toEqual(
[eventB]
[eventB],
);
});
@@ -1190,7 +1190,7 @@ describe("Room", function() {
room.addPendingEvent(eventB, "TXN1");
room.addLiveEvents([eventC]);
expect(room.timeline).toEqual(
[eventA, eventB, eventC]
[eventA, eventB, eventC],
);
});
});
@@ -1208,7 +1208,7 @@ describe("Room", function() {
room.addPendingEvent(eventA, "TXN1");
expect(room.getPendingEvents()).toEqual(
[eventA]
[eventA],
);
// the event has to have been failed or queued before it can be
@@ -1242,7 +1242,7 @@ describe("Room", function() {
room.addPendingEvent(eventA, "TXN1");
expect(room.getLiveTimeline().getEvents()).toEqual(
[eventA]
[eventA],
);
// 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]);
// modify the queue
const eventC = utils.mkMessage(
{user: "@a:bar", room: roomId, event: true}
{user: "@a:bar", room: roomId, event: true},
);
queue.push(eventC);
const queueAgain = scheduler.getQueueForEvent(eventA);
@@ -313,7 +313,7 @@ describe("MatrixScheduler", function() {
expect(MatrixScheduler.QUEUE_MESSAGES(
utils.mkMembership({
user: "@alice:bar", room: roomId, mship: "join", event: true,
})
}),
)).toEqual(null);
});
});
@@ -323,30 +323,30 @@ describe("MatrixScheduler", function() {
const res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 1, new MatrixError({
errcode: "M_LIMIT_EXCEEDED", retry_after_ms: 5000,
})
}),
);
expect(res >= 500).toBe(true, "Didn't wait long enough.");
});
it("should give up after 5 attempts", function() {
const res = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 5, {}
eventA, 5, {},
);
expect(res).toBe(-1, "Didn't give up.");
});
it("should do exponential backoff", function() {
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 1, {}
eventA, 1, {},
)).toEqual(2000);
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 2, {}
eventA, 2, {},
)).toEqual(4000);
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 3, {}
eventA, 3, {},
)).toEqual(8000);
expect(MatrixScheduler.RETRY_BACKOFF_RATELIMIT(
eventA, 4, {}
eventA, 4, {},
)).toEqual(16000);
});
});

View File

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

View File

@@ -14,7 +14,7 @@ describe("utils", function() {
baz: "beer@",
};
expect(utils.encodeParams(params)).toEqual(
"foo=bar&baz=beer%40"
"foo=bar&baz=beer%40",
);
});
});
@@ -27,7 +27,7 @@ describe("utils", function() {
"%here": "beer@",
};
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(
username, password,
sessionId, auth, bindEmail, guestAccessToken,
callback
callback,
) {
if (auth === undefined) {
auth = {};
@@ -189,7 +189,7 @@ MatrixBaseApis.prototype.registerRequest = function(data, kind, callback) {
}
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);
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) {
return this._http.authedRequest(
callback, "POST", '/logout'
callback, "POST", '/logout',
);
};
@@ -305,7 +305,7 @@ MatrixBaseApis.prototype.deactivateAccount = function(auth, callback) {
};
}
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) {
// valid options include: room_alias_name, visibility, invite
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);
}
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);
}
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;
}
const path = utils.encodeUri("/rooms/$roomId/initialSync",
{$roomId: roomId}
{$roomId: roomId},
);
if (!limit) {
limit = 30;
}
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");
} else {
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,
};
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,
});
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,
});
return this._http.authedRequest(
callback, "GET", path
callback, "GET", path,
);
};
@@ -586,7 +586,7 @@ MatrixBaseApis.prototype.setRoomDirectoryVisibility =
$roomId: roomId,
});
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,
});
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) {
const path = "/account/3pid";
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,
};
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,
};
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(
callback, "POST", path, null, data
callback, "POST", path, null, data,
);
};
@@ -786,7 +786,7 @@ MatrixBaseApis.prototype.getDevices = function() {
const path = "/devices";
return this._http.authedRequestWithPrefix(
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(
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(
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) {
const path = "/pushers";
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) {
const path = "/pushers/set";
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,
});
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,
});
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,
});
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;
}
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";
}
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};
return this._http.authedRequestWithPrefix(
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};
return this._http.authedRequestWithPrefix(
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(
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(
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
*/
MatrixBaseApis.prototype.sendToDevice = function(
eventType, contentMap, txnId
eventType, contentMap, txnId,
) {
const path = utils.encodeUri("/sendToDevice/$eventType/$txnId", {
$eventType: eventType,
@@ -1155,7 +1155,7 @@ MatrixBaseApis.prototype.sendToDevice = function(
return this._http.authedRequestWithPrefix(
undefined, "PUT", path, undefined, body,
httpApi.PREFIX_UNSTABLE
httpApi.PREFIX_UNSTABLE,
);
};
@@ -1170,7 +1170,7 @@ MatrixBaseApis.prototype.sendToDevice = function(
MatrixBaseApis.prototype.getThirdpartyProtocols = function() {
return this._http.authedRequestWithPrefix(
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(
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, this,
opts.sessionStore,
userId, this.deviceId
userId, this.deviceId,
);
this.olmVersion = Crypto.getOlmVersion();
@@ -395,11 +395,29 @@ MatrixClient.prototype.setDeviceBlocked = function(userId, deviceId, 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) {
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);
}
@@ -605,7 +623,7 @@ MatrixClient.prototype.setAccountData = function(eventType, contents, callback)
$type: eventType,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, contents
callback, "PUT", path, undefined, contents,
);
};
@@ -655,7 +673,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
if (opts.inviteSignUrl) {
sign_promise = this._http.requestOtherUrl(
undefined, 'POST',
opts.inviteSignUrl, { mxid: this.credentials.userId }
opts.inviteSignUrl, { mxid: this.credentials.userId },
);
}
@@ -758,7 +776,7 @@ MatrixClient.prototype.getRoomTags = function(roomId, callback) {
$roomId: roomId,
});
return this._http.authedRequest(
callback, "GET", path, undefined
callback, "GET", path, undefined,
);
};
@@ -777,7 +795,7 @@ MatrixClient.prototype.setRoomTag = function(roomId, tagName, metadata, callback
$tag: tagName,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, metadata
callback, "PUT", path, undefined, metadata,
);
};
@@ -795,7 +813,7 @@ MatrixClient.prototype.deleteRoomTag = function(roomId, tagName, callback) {
$tag: tagName,
});
return this._http.authedRequest(
callback, "DELETE", path, undefined, undefined
callback, "DELETE", path, undefined, undefined,
);
};
@@ -815,7 +833,7 @@ MatrixClient.prototype.setRoomAccountData = function(roomId, eventType,
$type: eventType,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, content
callback, "PUT", path, undefined, content,
);
};
@@ -844,7 +862,7 @@ MatrixClient.prototype.setPowerLevel = function(roomId, userId, powerLevel,
$roomId: roomId,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, content
callback, "PUT", path, undefined, content,
);
};
@@ -984,12 +1002,12 @@ function _sendEventHttpRequest(client, event) {
path = utils.encodeUri(pathTemplate, pathParams);
} else {
path = utils.encodeUri(
"/rooms/$roomId/send/$eventType/$txnId", pathParams
"/rooms/$roomId/send/$eventType/$txnId", pathParams,
);
}
return client._http.authedRequest(
undefined, "PUT", path, undefined, event.getWireContent()
undefined, "PUT", path, undefined, event.getWireContent(),
);
}
@@ -1006,7 +1024,7 @@ MatrixClient.prototype.sendMessage = function(roomId, content, txnId, callback)
callback = txnId; txnId = undefined;
}
return this.sendEvent(
roomId, "m.room.message", content, txnId, callback
roomId, "m.room.message", content, txnId, callback,
);
};
@@ -1156,7 +1174,7 @@ MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) {
$eventId: event.getId(),
});
const promise = this._http.authedRequest(
callback, "POST", path, undefined, {}
callback, "POST", path, undefined, {},
);
const room = this.getRoom(event.getRoomId());
@@ -1205,7 +1223,7 @@ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
callback, "GET", "/preview_url", {
url: url,
ts: ts,
}, undefined, httpApi.PREFIX_MEDIA_R0
}, undefined, httpApi.PREFIX_MEDIA_R0,
).then(function(response) {
// TODO: expire cache occasionally
self.urlPreviewCache[key] = response;
@@ -1237,7 +1255,7 @@ MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callba
data.timeout = timeoutMs ? timeoutMs : 20000;
}
return this._http.authedRequest(
callback, "PUT", path, undefined, data
callback, "PUT", path, undefined, data,
);
};
@@ -1263,7 +1281,7 @@ MatrixClient.prototype.invite = function(roomId, userId, callback) {
*/
MatrixClient.prototype.inviteByEmail = function(roomId, email, callback) {
return this.inviteByThreePid(
roomId, "email", email, callback
roomId, "email", email, callback,
);
};
@@ -1279,7 +1297,7 @@ MatrixClient.prototype.inviteByEmail = function(roomId, email, callback) {
MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, callback) {
const path = utils.encodeUri(
"/rooms/$roomId/invite",
{ $roomId: roomId }
{ $roomId: roomId },
);
let identityServerUrl = this.getIdentityServerUrl();
@@ -1361,7 +1379,7 @@ MatrixClient.prototype.forget = function(roomId, deleteRoom, callback) {
MatrixClient.prototype.unban = function(roomId, userId, callback) {
// unbanning = set their state to leave
return _setMembershipState(
this, roomId, userId, "leave", undefined, callback
this, roomId, userId, "leave", undefined, callback,
);
};
@@ -1375,7 +1393,7 @@ MatrixClient.prototype.unban = function(roomId, userId, callback) {
*/
MatrixClient.prototype.kick = function(roomId, userId, reason, callback) {
return _setMembershipState(
this, roomId, userId, "leave", reason, callback
this, roomId, userId, "leave", reason, callback,
);
};
@@ -1398,7 +1416,7 @@ function _setMembershipState(client, roomId, userId, membershipValue, reason,
const path = utils.encodeUri(
"/rooms/$roomId/state/m.room.member/$userId",
{ $roomId: roomId, $userId: userId}
{ $roomId: roomId, $userId: userId},
);
return client._http.authedRequest(callback, "PUT", path, undefined, {
@@ -1431,7 +1449,7 @@ function _membershipChange(client, roomId, userId, membership, reason, callback)
callback, "POST", path, undefined, {
user_id: userId, // may be undefined e.g. on leave
reason: reason,
}
},
);
}
@@ -1465,7 +1483,7 @@ MatrixClient.prototype.setProfileInfo = function(info, data, callback) {
$info: info,
});
return this._http.authedRequest(
callback, "PUT", path, undefined, data
callback, "PUT", path, undefined, data,
);
};
@@ -1477,7 +1495,7 @@ MatrixClient.prototype.setProfileInfo = function(info, data, callback) {
*/
MatrixClient.prototype.setDisplayName = function(name, callback) {
return this.setProfileInfo(
"displayname", { displayname: name }, callback
"displayname", { displayname: name }, callback,
);
};
@@ -1489,7 +1507,7 @@ MatrixClient.prototype.setDisplayName = function(name, callback) {
*/
MatrixClient.prototype.setAvatarUrl = function(url, callback) {
return this.setProfileInfo(
"avatar_url", { avatar_url: url }, callback
"avatar_url", { avatar_url: url }, callback,
);
};
@@ -1509,7 +1527,7 @@ MatrixClient.prototype.setAvatarUrl = function(url, callback) {
MatrixClient.prototype.mxcUrlToHttp =
function(mxcUrl, width, height, resizeMethod, allowDirectLinks) {
return contentRepo.getHttpUriForMxc(
this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks
this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks,
);
};
@@ -1536,7 +1554,7 @@ MatrixClient.prototype.setPresence = function(opts, callback) {
throw new Error("Bad presence value: " + opts.presence);
}
return this._http.authedRequest(
callback, "PUT", path, undefined, opts
callback, "PUT", path, undefined, opts,
);
};
@@ -1626,7 +1644,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
limit = limit - numAdded;
const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: room.roomId}
"/rooms/$roomId/messages", {$roomId: room.roomId},
);
const params = {
from: room.oldState.paginationToken,
@@ -1696,7 +1714,7 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
}
const path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: eventContext.getEvent().getRoomId()}
"/rooms/$roomId/messages", {$roomId: eventContext.getEvent().getRoomId()},
);
const params = {
from: token,
@@ -1706,7 +1724,7 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
const self = this;
const promise =
self._http.authedRequest(undefined, "GET", path, params
self._http.authedRequest(undefined, "GET", path, params,
).then(function(res) {
let token = res.end;
if (res.chunk.length === 0) {
@@ -1760,14 +1778,14 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
"/rooms/$roomId/context/$eventId", {
$roomId: timelineSet.room.roomId,
$eventId: eventId,
}
},
);
// TODO: we should implement a backoff (as per scrollback()) to deal more
// nicely with HTTP errors.
const self = this;
const promise =
self._http.authedRequest(undefined, "GET", path
self._http.authedRequest(undefined, "GET", path,
).then(function(res) {
if (!res.event) {
throw new Error("'event' not in '/context' result - homeserver too old?");
@@ -1867,7 +1885,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
promise =
this._http.authedRequestWithPrefix(undefined, "GET", path, params,
undefined, httpApi.PREFIX_UNSTABLE
undefined, httpApi.PREFIX_UNSTABLE,
).then(function(res) {
const token = res.next_token;
const matrixEvents = [];
@@ -1876,7 +1894,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
const notification = res.notifications[i];
const event = self.getEventMapper()(notification.event);
event.setPushActions(
PushProcessor.actionListToActionsObject(notification.actions)
PushProcessor.actionListToActionsObject(notification.actions),
);
event.event.room_id = notification.room_id; // XXX: gutwrenching
matrixEvents[i] = event;
@@ -1903,7 +1921,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
}
path = utils.encodeUri(
"/rooms/$roomId/messages", {$roomId: eventTimeline.getRoomId()}
"/rooms/$roomId/messages", {$roomId: eventTimeline.getRoomId()},
);
params = {
from: token,
@@ -1919,7 +1937,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
}
promise =
this._http.authedRequest(undefined, "GET", path, params
this._http.authedRequest(undefined, "GET", path, params,
).then(function(res) {
const token = res.end;
const matrixEvents = utils.map(res.chunk, self.getEventMapper());
@@ -2055,7 +2073,7 @@ MatrixClient.prototype.requestRegisterEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) {
return this._requestTokenFromEndpoint(
"/register/email/requestToken",
email, clientSecret, sendAttempt, nextLink, callback
email, clientSecret, sendAttempt, nextLink, callback,
);
};
@@ -2083,7 +2101,7 @@ MatrixClient.prototype.requestAdd3pidEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) {
return this._requestTokenFromEndpoint(
"/account/3pid/email/requestToken",
email, clientSecret, sendAttempt, nextLink, callback
email, clientSecret, sendAttempt, nextLink, callback,
);
};
@@ -2110,7 +2128,7 @@ MatrixClient.prototype.requestPasswordEmailToken = function(email, clientSecret,
sendAttempt, nextLink, callback) {
return this._requestTokenFromEndpoint(
"/account/password/email/requestToken",
email, clientSecret, sendAttempt, nextLink, callback
email, clientSecret, sendAttempt, nextLink, callback,
);
};
@@ -2143,7 +2161,7 @@ MatrixClient.prototype._requestTokenFromEndpoint = function(endpoint,
};
return this._http.request(
callback, "POST", endpoint, undefined,
params
params,
);
};
@@ -2169,7 +2187,7 @@ MatrixClient.prototype.getRoomPushRule = function(scope, roomId) {
}
} else {
throw new Error(
"SyncApi.sync() must be done before accessing to push rules."
"SyncApi.sync() must be done before accessing to push rules.",
);
}
};
@@ -2321,7 +2339,7 @@ MatrixClient.prototype.searchRoomEvents = function(opts) {
};
return this.search({body: body}).then(
this._processRoomEventsSearch.bind(this, searchResults)
this._processRoomEventsSearch.bind(this, searchResults),
);
};
@@ -2351,7 +2369,7 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) {
};
const promise = this.search(searchOpts).then(
this._processRoomEventsSearch.bind(this, searchResults)
this._processRoomEventsSearch.bind(this, searchResults),
).finally(function() {
searchResults.pendingRequest = null;
});
@@ -2441,11 +2459,11 @@ MatrixClient.prototype.createFilter = function(content) {
$userId: this.credentials.userId,
});
return this._http.authedRequest(
undefined, "POST", path, undefined, content
undefined, "POST", path, undefined, content,
).then(function(response) {
// persist the filter
const filter = Filter.fromJson(
self.credentials.userId, response.filter_id, content
self.credentials.userId, response.filter_id, content,
);
self.store.storeFilter(filter);
return filter;
@@ -2476,11 +2494,11 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
});
return this._http.authedRequest(
undefined, "GET", path, undefined, undefined
undefined, "GET", path, undefined, undefined,
).then(function(response) {
// persist the filter
const filter = Filter.fromJson(
userId, filterId, response
userId, filterId, response,
);
self.store.storeFilter(filter);
return filter;
@@ -2500,7 +2518,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
if (filterId) {
// check that the existing filter matches our expectations
promise = self.getFilter(self.credentials.userId,
filterId, true
filterId, true,
).then(function(existingFilter) {
const oldDef = existingFilter.getDefinition();
const newDef = filter.getDefinition();
@@ -2542,7 +2560,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
}
// create a new filter
return self.createFilter(filter.getDefinition()
return self.createFilter(filter.getDefinition(),
).then(function(createdFilter) {
// debuglog("Created new filter ID %s: %s", createdFilter.filterId,
// JSON.stringify(createdFilter.getDefinition()));
@@ -2566,7 +2584,7 @@ MatrixClient.prototype.getOpenIdToken = function() {
});
return this._http.authedRequest(
undefined, "POST", path, undefined, {}
undefined, "POST", path, undefined, {},
);
};
@@ -2756,7 +2774,7 @@ function setupCallEventHandler(client) {
console.log(
"WARN: Already have a MatrixCall with id %s but got an " +
"invite. Clobbering.",
content.call_id
content.call_id,
);
}
@@ -2764,7 +2782,7 @@ function setupCallEventHandler(client) {
if (!call) {
console.log(
"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
// connected that do support WebRTC and declining the
@@ -2780,7 +2798,7 @@ function setupCallEventHandler(client) {
if (candidatesByCall[call.callId]) {
for (i = 0; i < candidatesByCall[call.callId].length; i++) {
call._gotRemoteIceCandidate(
candidatesByCall[call.callId][i]
candidatesByCall[call.callId][i],
);
}
}
@@ -2809,14 +2827,14 @@ function setupCallEventHandler(client) {
existingCall.callId > call.callId) {
console.log(
"Glare detected: answering incoming call " + call.callId +
" and canceling outgoing call " + existingCall.callId
" and canceling outgoing call " + existingCall.callId,
);
existingCall._replacedBy(call);
call.answer();
} else {
console.log(
"Glare detected: rejecting incoming call " + call.callId +
" and keeping outgoing call " + existingCall.callId
" and keeping outgoing call " + existingCall.callId,
);
call.hangup();
}

View File

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

View File

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

View File

@@ -57,7 +57,7 @@ function OutboundSessionInfo(sessionId) {
* @return {Boolean}
*/
OutboundSessionInfo.prototype.needsRotation = function(
rotationPeriodMsgs, rotationPeriodMs
rotationPeriodMsgs, rotationPeriodMs,
) {
const sessionLifetime = new Date().getTime() - this.creationTime;
@@ -66,7 +66,7 @@ OutboundSessionInfo.prototype.needsRotation = function(
) {
console.log(
"Rotating megolm session after " + this.useCount +
" messages, " + sessionLifetime + "ms"
" messages, " + sessionLifetime + "ms",
);
return true;
}
@@ -86,7 +86,7 @@ OutboundSessionInfo.prototype.needsRotation = function(
* in devicesInRoom.
*/
OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
devicesInRoom
devicesInRoom,
) {
for (const userId in this.sharedWithDevices) {
if (!this.sharedWithDevices.hasOwnProperty(userId)) {
@@ -106,7 +106,7 @@ OutboundSessionInfo.prototype.sharedWithTooManyDevices = function(
if (!devicesInRoom[userId].hasOwnProperty(deviceId)) {
console.log(
"Starting new session because we shared with " +
userId + ":" + deviceId
userId + ":" + deviceId,
);
return true;
}
@@ -220,7 +220,7 @@ MegolmEncryption.prototype._ensureOutboundSession = function(devicesInRoom) {
}
return self._shareKeyWithDevices(
session, shareMap
session, shareMap,
);
}
@@ -250,7 +250,7 @@ MegolmEncryption.prototype._prepareNewSession = function() {
this._olmDevice.addInboundGroupSession(
this._roomId, this._olmDevice.deviceCurve25519Key, session_id,
key.key, {ed25519: this._olmDevice.deviceEd25519Key}
key.key, {ed25519: this._olmDevice.deviceEd25519Key},
);
return new OutboundSessionInfo(session_id);
@@ -285,7 +285,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
const contentMap = {};
return olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, devicesByUser
this._olmDevice, this._baseApis, devicesByUser,
).then(function(devicemap) {
let haveTargets = false;
@@ -318,7 +318,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
}
console.log(
"sharing keys with device " + userId + ":" + deviceId
"sharing keys with device " + userId + ":" + deviceId,
);
const encryptedContent = {
@@ -334,7 +334,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
self._olmDevice,
userId,
deviceInfo,
payload
payload,
);
if (!contentMap[userId]) {
@@ -401,7 +401,7 @@ MegolmEncryption.prototype.encryptMessage = function(room, eventType, content) {
};
const ciphertext = self._olmDevice.encryptGroupMessage(
session.sessionId, JSON.stringify(payloadJson)
session.sessionId, JSON.stringify(payloadJson),
);
const encryptedContent = {
@@ -434,10 +434,6 @@ MegolmEncryption.prototype._checkForUnknownDevices = function(devicesInRoom) {
Object.keys(devicesInRoom[userId]).forEach((deviceId)=>{
const device = devicesInRoom[userId][deviceId];
if (device.isUnverified() && !device.isKnown()) {
// mark the devices as known to the user, given we're about to
// yell at them.
this._crypto.setDeviceVerification(userId, device.deviceId,
undefined, undefined, true);
if (!unknownDevices[userId]) {
unknownDevices[userId] = {};
}
@@ -473,11 +469,13 @@ MegolmEncryption.prototype._getDevicesInRoom = function(room) {
// with them, which means that they will have announced any new devices via
// an m.new_device.
//
// XXX: what if the cache is stale, and the user left the room we had in common
// and then added new devices before joining this one? --Matthew
// XXX: what if the cache is stale, and the user left the room we had in
// common and then added new devices before joining this one? --Matthew
//
// yup, see https://github.com/vector-im/riot-web/issues/2305 --richvdh
var self = this;
return self._crypto.downloadKeys(roomMembers, false).then(function(devices) {
// remove any blocked (aka blacklisted) devices
// remove any blocked devices
for (const userId in devices) {
if (!devices.hasOwnProperty(userId)) {
continue;
@@ -541,7 +539,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
let res;
try {
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) {
if (e.message === 'OLM.UNKNOWN_MESSAGE_INDEX') {
@@ -554,7 +552,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
// We've got a message for a session we don't have.
this._addEventToPendingList(event);
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.",
);
}
@@ -565,7 +563,7 @@ MegolmDecryption.prototype.decryptEvent = function(event) {
// room, so neither the sender nor a MITM can lie about the room_id).
if (payload.room_id !== event.getRoomId()) {
throw new base.DecryptionError(
"Message intended for room " + payload.room_id
"Message intended for room " + payload.room_id,
);
}
@@ -609,7 +607,7 @@ MegolmDecryption.prototype.onRoomKeyEvent = function(event) {
this._olmDevice.addInboundGroupSession(
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.
@@ -656,5 +654,5 @@ MegolmDecryption.prototype._retryDecryption = function(senderKey, sessionId) {
};
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(
encryptedContent.ciphertext,
self._userId, self._deviceId, self._olmDevice,
userId, deviceInfo, payloadFields
userId, deviceInfo, payloadFields,
);
}
}
@@ -177,7 +177,7 @@ OlmDecryption.prototype.decryptEvent = function(event) {
console.warn(
"Failed to decrypt Olm event (id=" +
event.getId() + ") from " + deviceKey +
": " + e.message
": " + e.message,
);
throw new base.DecryptionError("Bad Encrypted Message");
}
@@ -189,10 +189,10 @@ OlmDecryption.prototype.decryptEvent = function(event) {
if (payload.recipient != this._userId) {
console.warn(
"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(
"Message was intented for " + payload.recipient
"Message was intented for " + payload.recipient,
);
}
@@ -200,7 +200,7 @@ OlmDecryption.prototype.decryptEvent = function(event) {
this._olmDevice.deviceEd25519Key) {
console.warn(
"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");
}
@@ -212,10 +212,10 @@ OlmDecryption.prototype.decryptEvent = function(event) {
if (payload.sender != event.getSender()) {
console.warn(
"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(
"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()) {
console.warn(
"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(
"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];
try {
const payload = this._olmDevice.decryptMessage(
theirDeviceIdentityKey, sessionId, message.type, message.body
theirDeviceIdentityKey, sessionId, message.type, message.body,
);
console.log(
"Decrypted Olm message from " + theirDeviceIdentityKey +
" with session " + sessionId
" with session " + sessionId,
);
return payload;
} catch (e) {
const foundSession = this._olmDevice.matchesSession(
theirDeviceIdentityKey, sessionId, message.type, message.body
theirDeviceIdentityKey, sessionId, message.type, message.body,
);
if (foundSession) {
@@ -268,7 +268,7 @@ OlmDecryption.prototype._decryptMessage = function(theirDeviceIdentityKey, messa
// session, so it should have worked.
throw new Error(
"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(
"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;
try {
res = this._olmDevice.createInboundSession(
theirDeviceIdentityKey, message.type, message.body
theirDeviceIdentityKey, message.type, message.body,
);
} catch (e) {
decryptionErrors["(new)"] = e.message;
throw new Error(
"Error decrypting prekey message: " +
JSON.stringify(decryptionErrors)
JSON.stringify(decryptionErrors),
);
}
console.log(
"created new inbound Olm session ID " +
res.session_id + " with " + theirDeviceIdentityKey
res.session_id + " with " + theirDeviceIdentityKey,
);
return res.payload;
};

View File

@@ -86,6 +86,7 @@ DeviceInfo.prototype.toStorage = function() {
algorithms: this.algorithms,
keys: this.keys,
verified: this.verified,
known: this.known,
unsigned: this.unsigned,
};
};

View File

@@ -69,7 +69,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
this._roomDecryptors = {};
this._supportedAlgorithms = utils.keys(
algorithms.DECRYPTION_CLASSES
algorithms.DECRYPTION_CLASSES,
);
// build our device keys: these will later be uploaded
@@ -82,7 +82,7 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
this._globalBlacklistUnverifiedDevices = false;
let myDevices = this._sessionStore.getEndToEndDevicesForUser(
this._userId
this._userId,
);
if (!myDevices) {
@@ -98,11 +98,12 @@ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) {
keys: this._deviceKeys,
algorithms: this._supportedAlgorithms,
verified: DeviceVerification.VERIFIED,
known: true,
};
myDevices[this._deviceId] = deviceInfo;
this._sessionStore.storeEndToEndDevicesForUser(
this._userId, myDevices
this._userId, myDevices,
);
}
@@ -402,7 +403,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
});
this._baseApis.downloadKeysForUsers(
downloadUsers
downloadUsers,
).done(function(res) {
const dk = res.device_keys || {};
@@ -433,7 +434,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
}
_updateStoredDeviceKeysForUser(
self._olmDevice, userId, userStore, dk[userId]
self._olmDevice, userId, userStore, dk[userId],
);
// update the session store
@@ -446,7 +447,7 @@ Crypto.prototype._doKeyDownloadForUsers = function(downloadUsers) {
storage[deviceId] = userStore[deviceId].toStorage();
}
self._sessionStore.storeEndToEndDevicesForUser(
userId, storage
userId, storage,
);
deferMap[userId].resolve();
@@ -732,7 +733,7 @@ Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified,
}
let knownStatus = dev.known;
if (known !== null) {
if (known !== null && known !== undefined) {
knownStatus = known;
}
@@ -796,7 +797,7 @@ Crypto.prototype.getEventSenderDeviceInfo = function(event) {
// identity key of the device which set up the Megolm session.
const device = this.getDeviceByIdentityKey(
event.getSender(), algorithm, sender_key
event.getSender(), algorithm, sender_key,
);
if (device === null) {
@@ -915,7 +916,7 @@ Crypto.prototype.ensureOlmSessionsForUsers = function(users) {
}
return olmlib.ensureOlmSessionsForDevices(
this._olmDevice, this._baseApis, devicesByUser
this._olmDevice, this._baseApis, devicesByUser,
);
};
@@ -940,13 +941,13 @@ Crypto.prototype.exportRoomKeys = function() {
this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map(
(s) => {
const sess = this._olmDevice.exportInboundGroupSession(
s.senderKey, s.sessionId
s.senderKey, s.sessionId,
);
sess.algorithm = olmlib.MEGOLM_ALGORITHM;
return sess;
}
)
},
),
);
};
@@ -1001,7 +1002,7 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
throw new Error(
"Room was previously configured to use encryption, but is " +
"no longer. Perhaps the homeserver is hiding the " +
"configuration event."
"configuration event.",
);
}
return null;
@@ -1016,7 +1017,7 @@ Crypto.prototype.encryptEventIfNeeded = function(event, room) {
};
return alg.encryptMessage(
room, event.getType(), event.getContent()
room, event.getType(), event.getContent(),
).then(function(encryptedContent) {
event.makeEncrypted("m.room.encrypted", encryptedContent, myKeys);
});
@@ -1119,7 +1120,7 @@ Crypto.prototype._onInitialSyncCompleted = function(rooms) {
const self = this;
this._baseApis.sendToDevice(
"m.new_device", // OH HAI!
content
content,
).done(function() {
self._sessionStore.setDeviceAnnounced();
});
@@ -1227,7 +1228,7 @@ Crypto.prototype._flushNewDeviceRequests = function() {
users.map(function(u) {
r[u] = r[u].catch(function(e) {
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
@@ -1279,7 +1280,7 @@ Crypto.prototype._getRoomDecryptor = function(roomId, algorithm) {
const AlgClass = algorithms.DECRYPTION_CLASSES[algorithm];
if (!AlgClass) {
throw new algorithms.DecryptionError(
'Unknown encryption algorithm "' + algorithm + '".'
'Unknown encryption algorithm "' + algorithm + '".',
);
}
alg = new AlgClass({

View File

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

View File

@@ -70,7 +70,7 @@ FilterComponent.prototype.check = function(event) {
event.getRoomId(),
event.getSender(),
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_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:

View File

@@ -163,7 +163,7 @@ module.exports.MatrixHttpApi.prototype = {
"Returning the raw JSON from uploadContent(). Future " +
"versions of the js-sdk will change this default, to " +
"return the parsed object. Set opts.rawResponse=false " +
"to change this behaviour now."
"to change this behaviour now.",
);
rawResponse = true;
}
@@ -176,7 +176,7 @@ module.exports.MatrixHttpApi.prototype = {
"Returning only the content-uri from uploadContent(). " +
"Future versions of the js-sdk will change this " +
"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;
} else {
@@ -279,7 +279,7 @@ module.exports.MatrixHttpApi.prototype = {
headers: {"Content-Type": contentType},
json: false,
bodyParser: bodyParser,
}
},
);
}
@@ -321,7 +321,7 @@ module.exports.MatrixHttpApi.prototype = {
if (callback !== undefined && !utils.isFunction(callback)) {
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();
this.opts.request(
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'
// 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(
callback, method, path, queryParams, data, opts
callback, method, path, queryParams, data, opts,
);
const self = this;
@@ -441,7 +441,7 @@ module.exports.MatrixHttpApi.prototype = {
const fullUri = this.opts.baseUrl + prefix + path;
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, {
localTimeoutMs: localTimeoutMs,
prefix: prefix,
}
},
);
},
@@ -511,7 +511,7 @@ module.exports.MatrixHttpApi.prototype = {
callback, method, path, queryParams, data, {
localTimeoutMs: localTimeoutMs,
prefix: prefix,
}
},
);
},
@@ -556,7 +556,7 @@ module.exports.MatrixHttpApi.prototype = {
}
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) {
if (callback !== undefined && !utils.isFunction(callback)) {
throw Error(
"Expected callback to be a function but got " + typeof callback
"Expected callback to be a function but got " + typeof callback,
);
}
opts = opts || {};
@@ -674,10 +674,10 @@ module.exports.MatrixHttpApi.prototype = {
const handlerFn = requestCallback(
defer, callback, self.opts.onlyData,
parseErrorJson,
opts.bodyParser
opts.bodyParser,
);
handlerFn(err, response, body);
}
},
);
if (req && req.abort) {
// 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(
defer, userDefinedCallback, onlyData,
parseErrorJson, bodyParser
parseErrorJson, bodyParser,
) {
userDefinedCallback = userDefinedCallback || function() {};

View File

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

View File

@@ -259,14 +259,14 @@ EventTimelineSet.prototype.addEventsToTimeline = function(events, toStartOfTimel
timeline, paginationToken) {
if (!timeline) {
throw new Error(
"'timeline' not specified for EventTimelineSet.addEventsToTimeline"
"'timeline' not specified for EventTimelineSet.addEventsToTimeline",
);
}
if (!toStartOfTimeline && timeline == this._liveTimeline) {
throw new Error(
"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(
event,
timeline.getState(EventTimeline.FORWARDS),
false
false,
);
if (!tlEvents[j].encryptedType) {

View File

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

View File

@@ -70,7 +70,7 @@ module.exports.EventStatus = {
* Default: true. <strong>This property is experimental and may change.</strong>
*/
module.exports.MatrixEvent = function MatrixEvent(
event
event,
) {
this.event = event || {};
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 httpUrl = ContentRepo.getHttpUriForMxc(
baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks
baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks,
);
if (httpUrl) {
return httpUrl;
} else if (allowDefault) {
return ContentRepo.getIdenticonUri(
baseUrl, this.userId, width, height
baseUrl, this.userId, width, height,
);
}
return null;

View File

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

View File

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

View File

@@ -126,7 +126,7 @@ MatrixScheduler.prototype.queueEvent = function(event) {
});
debuglog(
"Queue algorithm dumped event %s into queue '%s'",
event.getId(), queueName
event.getId(), queueName,
);
_startProcessingQueues(this);
return defer.promise;
@@ -213,7 +213,7 @@ function _processQueue(scheduler, queueName) {
}
debuglog(
"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
// invoke the retry algorithm.
@@ -230,11 +230,11 @@ function _processQueue(scheduler, queueName) {
const waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);
debuglog(
"retry(%s) err=%s event_id=%s waitTime=%s",
obj.attempts, err, obj.event.getId(), waitTimeMs
obj.attempts, err, obj.event.getId(), waitTimeMs,
);
if (waitTimeMs === -1) { // give up (you quitter!)
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
_removeNextEvent(scheduler, queueName);

View File

@@ -102,7 +102,7 @@ module.exports.MatrixInMemoryStore.prototype = {
user.setDisplayName(member.name);
if (member.events.member) {
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'
) {
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) || {};
sessions[sessionId] = session;
setJsonItem(
this.store, keyEndToEndSessions(deviceKey), sessions
this.store, keyEndToEndSessions(deviceKey), sessions,
);
},

View File

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

View File

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

View File

@@ -141,8 +141,8 @@ MatrixCall.prototype.placeScreenSharingCall =
self.emit("error",
callError(
MatrixCall.ERR_NO_USER_MEDIA,
"Failed to get screen-sharing stream: " + err
)
"Failed to get screen-sharing stream: " + err,
),
);
});
this.type = 'video';
@@ -311,7 +311,7 @@ MatrixCall.prototype._initWithInvite = function(event) {
this.peerConn.setRemoteDescription(
new this.webRtc.RtcSessionDescription(this.msg.offer),
hookCallback(self, self._onSetRemoteDescriptionSuccess),
hookCallback(self, self._onSetRemoteDescriptionError)
hookCallback(self, self._onSetRemoteDescriptionError),
);
}
setState(this, 'ringing');
@@ -370,7 +370,7 @@ MatrixCall.prototype.answer = function() {
this.webRtc.getUserMedia(
_getUserMediaVideoContraints(this.type),
hookCallback(self, self._gotUserMediaForAnswer),
hookCallback(self, self._getUserMediaFailed)
hookCallback(self, self._getUserMediaFailed),
);
setState(this, 'wait_local_media');
} else if (this.localAVStream) {
@@ -528,7 +528,7 @@ MatrixCall.prototype._gotUserMediaForInvite = function(stream) {
this.peerConn.addStream(stream);
this.peerConn.createOffer(
hookCallback(self, self._gotLocalOffer),
hookCallback(self, self._getLocalOfferFailed)
hookCallback(self, self._getLocalOfferFailed),
);
setState(self, 'create_offer');
};
@@ -600,7 +600,7 @@ MatrixCall.prototype._gotLocalIceCandidate = function(event) {
if (event.candidate) {
debuglog(
"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
// pass the original: that broke in Chrome ~m43.
@@ -627,7 +627,7 @@ MatrixCall.prototype._gotRemoteIceCandidate = function(cand) {
this.peerConn.addIceCandidate(
new this.webRtc.RtcIceCandidate(cand),
function() {},
function(e) {}
function(e) {},
);
};
@@ -645,7 +645,7 @@ MatrixCall.prototype._receivedAnswer = function(msg) {
this.peerConn.setRemoteDescription(
new this.webRtc.RtcSessionDescription(msg.answer),
hookCallback(self, self._onSetRemoteDescriptionSuccess),
hookCallback(self, self._onSetRemoteDescriptionError)
hookCallback(self, self._onSetRemoteDescriptionError),
);
setState(self, 'connecting');
};
@@ -705,7 +705,7 @@ MatrixCall.prototype._gotLocalOffer = function(description) {
MatrixCall.prototype._getLocalOfferFailed = function(error) {
this.emit(
"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(
MatrixCall.ERR_NO_USER_MEDIA,
"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");
};
@@ -735,7 +735,7 @@ MatrixCall.prototype._onIceConnectionStateChanged = function() {
return; // because ICE can still complete as we're ending the call
}
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
// chrome doesn't implement any of the 'onstarted' events yet
@@ -755,7 +755,7 @@ MatrixCall.prototype._onIceConnectionStateChanged = function() {
MatrixCall.prototype._onSignallingStateChanged = function() {
debuglog(
"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) {
if (self.listeners("error").length === 0) {
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) {
debuglog(
"Failed to send candidates on attempt %s. Giving up for now.",
self.candidateSendTries
self.candidateSendTries,
);
self.candidateSendTries = 0;
return;
@@ -1093,7 +1093,7 @@ const _placeCallWithConstraints = function(self, constraints) {
self.webRtc.getUserMedia(
constraints,
hookCallback(self, self._gotUserMediaForInvite),
hookCallback(self, self._getUserMediaFailed)
hookCallback(self, self._getUserMediaFailed),
);
setState(self, 'wait_local_media');
self.direction = 'outbound';
@@ -1131,7 +1131,7 @@ const _getChromeScreenSharingConstraints = function(call) {
if (!screen) {
call.emit("error", callError(
MatrixCall.ERR_NO_USER_MEDIA,
"Couldn't determine screen sharing constaints."
"Couldn't determine screen sharing constaints.",
));
return;
}