1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-12-01 04:43:29 +03:00

Merge pull request #490 from matrix-org/rav/bluebird

Switch matrix-js-sdk to bluebird
This commit is contained in:
Richard van der Hoff
2017-07-12 23:34:40 +01:00
committed by GitHub
36 changed files with 244 additions and 245 deletions

View File

@@ -49,9 +49,9 @@
],
"dependencies": {
"another-json": "^0.2.0",
"bluebird": "^3.5.0",
"browser-request": "^0.3.3",
"content-type": "^1.0.2",
"q": "^1.4.1",
"regenerator-runtime": "^0.10.5",
"request": "^2.53.0"
},

View File

@@ -24,7 +24,7 @@ import sdk from '..';
import testUtils from './test-utils';
import MockHttpBackend from 'matrix-mock-request';
import expect from 'expect';
import q from 'q';
import Promise from 'bluebird';
/**
* Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient
@@ -118,7 +118,7 @@ TestClient.prototype.expectDeviceKeyUpload = function() {
TestClient.prototype.awaitOneTimeKeyUpload = function() {
if (Object.keys(this.oneTimeKeys).length != 0) {
// already got one-time keys
return q(this.oneTimeKeys);
return Promise.resolve(this.oneTimeKeys);
}
this.httpBackend.when("POST", "/keys/upload")
@@ -195,7 +195,7 @@ TestClient.prototype.getSigningKey = function() {
*/
TestClient.prototype.flushSync = function() {
console.log(`${this}: flushSync`);
return q.all([
return Promise.all([
this.httpBackend.flush('/sync', 1),
testUtils.syncPromise(this.client),
]);

View File

@@ -31,7 +31,7 @@ import '../olm-loader';
import expect from 'expect';
const sdk = require("../..");
const q = require("q");
import Promise from 'bluebird';
const utils = require("../../lib/utils");
const testUtils = require("../test-utils");
const TestClient = require('../TestClient').default;
@@ -50,7 +50,7 @@ let bobMessages;
function bobUploadsDeviceKeys() {
bobTestClient.expectDeviceKeyUpload();
return q.all([
return Promise.all([
bobTestClient.client.uploadKeys(),
bobTestClient.httpBackend.flush(),
]).then(() => {
@@ -157,7 +157,7 @@ function aliDownloadsKeys() {
// check that the localStorage is updated as we expect (not sure this is
// an integration test, but meh)
return q.all([p1, p2]).then(function() {
return Promise.all([p1, p2]).then(function() {
const devices = aliTestClient.storage.getEndToEndDevicesForUser(bobUserId);
expect(devices[bobDeviceId].keys).toEqual(bobTestClient.deviceKeys.keys);
expect(devices[bobDeviceId].verified).
@@ -188,7 +188,7 @@ function bobEnablesEncryption() {
* @return {promise} which resolves to the ciphertext for Bob's device.
*/
function aliSendsFirstMessage() {
return q.all([
return Promise.all([
sendMessage(aliTestClient.client),
expectAliQueryKeys()
.then(expectAliClaimKeys)
@@ -205,7 +205,7 @@ function aliSendsFirstMessage() {
* @return {promise} which resolves to the ciphertext for Bob's device.
*/
function aliSendsMessage() {
return q.all([
return Promise.all([
sendMessage(aliTestClient.client),
expectAliSendMessageRequest(),
]).spread(function(_, ciphertext) {
@@ -220,7 +220,7 @@ function aliSendsMessage() {
* @return {promise} which resolves to the ciphertext for Ali's device.
*/
function bobSendsReplyMessage() {
return q.all([
return Promise.all([
sendMessage(bobTestClient.client),
expectBobQueryKeys()
.then(expectBobSendMessageRequest),
@@ -269,7 +269,7 @@ function sendMessage(client) {
function expectSendMessageRequest(httpBackend) {
const path = "/send/m.room.encrypted/";
const deferred = q.defer();
const deferred = Promise.defer();
httpBackend.when("PUT", path).respond(200, function(path, content) {
deferred.resolve(content);
return {
@@ -317,7 +317,7 @@ function recvMessage(httpBackend, client, sender, message) {
},
};
httpBackend.when("GET", "/sync").respond(200, syncData);
const deferred = q.defer();
const deferred = Promise.defer();
const onEvent = function(event) {
console.log(client.credentials.userId + " received event",
event);
@@ -406,19 +406,19 @@ describe("MatrixClient crypto", function() {
});
it("Bob uploads device keys", function() {
return q()
return Promise.resolve()
.then(bobUploadsDeviceKeys);
});
it("Ali downloads Bobs device keys", function(done) {
q()
Promise.resolve()
.then(bobUploadsDeviceKeys)
.then(aliDownloadsKeys)
.nodeify(done);
});
it("Ali gets keys with an invalid signature", function(done) {
q()
Promise.resolve()
.then(bobUploadsDeviceKeys)
.then(function() {
// tamper bob's keys
@@ -426,7 +426,7 @@ describe("MatrixClient crypto", function() {
expect(bobDeviceKeys.keys["curve25519:" + bobDeviceId]).toBeTruthy();
bobDeviceKeys.keys["curve25519:" + bobDeviceId] += "abc";
return q.all([
return Promise.all([
aliTestClient.client.downloadKeys([bobUserId]),
expectAliQueryKeys(),
]);
@@ -467,7 +467,7 @@ describe("MatrixClient crypto", function() {
return {device_keys: result};
});
q.all([
Promise.all([
aliTestClient.client.downloadKeys([bobUserId, eveUserId]),
aliTestClient.httpBackend.flush("/keys/query", 1),
]).then(function() {
@@ -504,7 +504,7 @@ describe("MatrixClient crypto", function() {
return {device_keys: result};
});
q.all([
Promise.all([
aliTestClient.client.downloadKeys([bobUserId]),
aliTestClient.httpBackend.flush("/keys/query", 1),
]).then(function() {
@@ -515,7 +515,7 @@ describe("MatrixClient crypto", function() {
it("Bob starts his client and uploads device keys and one-time keys", function() {
return q()
return Promise.resolve()
.then(() => bobTestClient.start())
.then(() => bobTestClient.awaitOneTimeKeyUpload())
.then((keys) => {
@@ -525,7 +525,7 @@ describe("MatrixClient crypto", function() {
});
it("Ali sends a message", function(done) {
q()
Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -535,7 +535,7 @@ describe("MatrixClient crypto", function() {
});
it("Bob receives a message", function(done) {
q()
Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -546,7 +546,7 @@ describe("MatrixClient crypto", function() {
});
it("Bob receives a message with a bogus sender", function(done) {
q()
Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -576,7 +576,7 @@ describe("MatrixClient crypto", function() {
};
bobTestClient.httpBackend.when("GET", "/sync").respond(200, syncData);
const deferred = q.defer();
const deferred = Promise.defer();
const onEvent = function(event) {
console.log(bobUserId + " received event",
event);
@@ -603,7 +603,7 @@ describe("MatrixClient crypto", function() {
});
it("Ali blocks Bob's device", function(done) {
q()
Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -617,12 +617,12 @@ describe("MatrixClient crypto", function() {
// no unblocked devices, so the ciphertext should be empty
expect(sentContent.ciphertext).toEqual({});
});
return q.all([p1, p2]);
return Promise.all([p1, p2]);
}).nodeify(done);
});
it("Bob receives two pre-key messages", function(done) {
q()
Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -635,7 +635,7 @@ describe("MatrixClient crypto", function() {
});
it("Bob replies to the message", function() {
return q()
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => bobTestClient.start())
.then(() => firstSync(aliTestClient))
@@ -652,7 +652,7 @@ describe("MatrixClient crypto", function() {
it("Ali does a key query when encryption is enabled", function() {
// enabling encryption in the room should make alice download devices
// for both members.
return q()
return Promise.resolve()
.then(() => aliTestClient.start())
.then(() => firstSync(aliTestClient))
.then(() => {

View File

@@ -1,6 +1,6 @@
"use strict";
import 'source-map-support/register';
const q = require("q");
import Promise from 'bluebird';
const sdk = require("../..");
const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
@@ -82,7 +82,7 @@ function startClient(httpBackend, client) {
client.startClient();
// set up a promise which will resolve once the client is initialised
const deferred = q.defer();
const deferred = Promise.defer();
client.on("sync", function(state) {
console.log("sync", state);
if (state != "SYNCING") {
@@ -91,7 +91,7 @@ function startClient(httpBackend, client) {
deferred.resolve();
});
return q.all([
return Promise.all([
httpBackend.flushAllExpected(),
deferred.promise,
]);
@@ -205,7 +205,7 @@ describe("getEventTimeline support", function() {
}).then(() => {
// the sync isn't processed immediately; give the promise chain
// a chance to complete.
return q.delay(0);
return Promise.delay(0);
}).then(function() {
expect(room.timeline.length).toEqual(1);
expect(room.timeline[0].event).toEqual(EVENTS[1]);
@@ -266,7 +266,7 @@ describe("MatrixClient event timelines", function() {
};
});
return q.all([
return Promise.all([
client.getEventTimeline(timelineSet, "event1:bar").then(function(tl) {
expect(tl.getEvents().length).toEqual(4);
for (let i = 0; i < 4; i++) {
@@ -346,7 +346,7 @@ describe("MatrixClient event timelines", function() {
};
});
const deferred = q.defer();
const deferred = Promise.defer();
client.on("sync", function() {
client.getEventTimeline(timelineSet, EVENTS[2].event_id,
).then(function(tl) {
@@ -362,7 +362,7 @@ describe("MatrixClient event timelines", function() {
(e) => deferred.reject(e));
});
return q.all([
return Promise.all([
httpBackend.flushAllExpected(),
deferred.promise,
]);
@@ -429,7 +429,7 @@ describe("MatrixClient event timelines", function() {
let tl0;
let tl3;
return q.all([
return Promise.all([
client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl) {
expect(tl.getEvents().length).toEqual(1);
@@ -480,7 +480,7 @@ describe("MatrixClient event timelines", function() {
};
});
return q.all([
return Promise.all([
client.getEventTimeline(timelineSet, "event1",
).then(function(tl) {
// could do with a fail()
@@ -525,7 +525,7 @@ describe("MatrixClient event timelines", function() {
});
let tl;
return q.all([
return Promise.all([
client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) {
tl = tl0;
@@ -577,7 +577,7 @@ describe("MatrixClient event timelines", function() {
});
let tl;
return q.all([
return Promise.all([
client.getEventTimeline(timelineSet, EVENTS[0].event_id,
).then(function(tl0) {
tl = tl0;
@@ -634,7 +634,7 @@ describe("MatrixClient event timelines", function() {
const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0];
return q.all([
return Promise.all([
client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) {
expect(res.event_id).toEqual(event.event_id);
return client.getEventTimeline(timelineSet, event.event_id);
@@ -644,7 +644,7 @@ describe("MatrixClient event timelines", function() {
expect(tl.getEvents()[1].getContent().body).toEqual("a body");
// now let the sync complete, and check it again
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]);
@@ -663,7 +663,7 @@ describe("MatrixClient event timelines", function() {
const room = client.getRoom(roomId);
const timelineSet = room.getTimelineSets()[0];
return q.all([
return Promise.all([
// initiate the send, and set up checks to be done when it completes
// - but note that it won't complete until after the /sync does, below.
client.sendTextMessage(roomId, "a body", TXN_ID).then(function(res) {
@@ -676,7 +676,7 @@ describe("MatrixClient event timelines", function() {
expect(tl.getEvents()[1].getContent().body).toEqual("a body");
}),
q.all([
Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {

View File

@@ -6,7 +6,7 @@ const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
import expect from 'expect';
import q from 'q';
import Promise from 'bluebird';
describe("MatrixClient opts", function() {
const baseUrl = "http://localhost.or.something";
@@ -114,7 +114,7 @@ describe("MatrixClient opts", function() {
httpBackend.flush("/pushrules", 1).then(function() {
return httpBackend.flush("/filter", 1);
}).then(function() {
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]);

View File

@@ -5,7 +5,7 @@ const EventStatus = sdk.EventStatus;
const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
import q from 'q';
import Promise from 'bluebird';
import expect from 'expect';
describe("MatrixClient room timelines", function() {
@@ -394,7 +394,7 @@ describe("MatrixClient room timelines", function() {
];
setNextSyncData(eventData);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(() => {
@@ -409,7 +409,7 @@ describe("MatrixClient room timelines", function() {
});
httpBackend.flush("/messages", 1);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {
@@ -436,12 +436,12 @@ describe("MatrixClient room timelines", function() {
eventData[1].__prev_event = USER_MEMBERSHIP_EVENT;
setNextSyncData(eventData);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(() => {
const room = client.getRoom(roomId);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {
@@ -462,7 +462,7 @@ describe("MatrixClient room timelines", function() {
secondRoomNameEvent.__prev_event = ROOM_NAME_EVENT;
setNextSyncData([secondRoomNameEvent]);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(() => {
@@ -472,7 +472,7 @@ describe("MatrixClient room timelines", function() {
nameEmitCount += 1;
});
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {
@@ -487,7 +487,7 @@ describe("MatrixClient room timelines", function() {
thirdRoomNameEvent.__prev_event = secondRoomNameEvent;
setNextSyncData([thirdRoomNameEvent]);
httpBackend.when("GET", "/sync").respond(200, NEXT_SYNC_DATA);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]);
@@ -513,12 +513,12 @@ describe("MatrixClient room timelines", function() {
eventData[1].__prev_event = null;
setNextSyncData(eventData);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(() => {
const room = client.getRoom(roomId);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {
@@ -544,14 +544,14 @@ describe("MatrixClient room timelines", function() {
setNextSyncData(eventData);
NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true;
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(() => {
const room = client.getRoom(roomId);
httpBackend.flush("/messages", 1);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {
@@ -577,7 +577,7 @@ describe("MatrixClient room timelines", function() {
setNextSyncData(eventData);
NEXT_SYNC_DATA.rooms.join[roomId].timeline.limited = true;
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(() => {
@@ -590,7 +590,7 @@ describe("MatrixClient room timelines", function() {
});
httpBackend.flush("/messages", 1);
return q.all([
return Promise.all([
httpBackend.flush("/sync", 1),
utils.syncPromise(client),
]).then(function() {

View File

@@ -7,7 +7,7 @@ const MatrixEvent = sdk.MatrixEvent;
const EventTimeline = sdk.EventTimeline;
import expect from 'expect';
import q from 'q';
import Promise from 'bluebird';
describe("MatrixClient syncing", function() {
const baseUrl = "http://localhost.or.something";
@@ -634,7 +634,7 @@ describe("MatrixClient syncing", function() {
include_leave: true }});
}).respond(200, { filter_id: "another_id" });
const defer = q.defer();
const defer = Promise.defer();
httpBackend.when("GET", "/sync").check(function(req) {
expect(req.queryParams.filter).toEqual("another_id");
@@ -645,7 +645,7 @@ describe("MatrixClient syncing", function() {
// first flush the filter request; this will make syncLeftRooms
// make its /sync call
return q.all([
return Promise.all([
httpBackend.flush("/filter").then(function() {
// flush the syncs
return httpBackend.flushAllExpected();
@@ -679,7 +679,7 @@ describe("MatrixClient syncing", function() {
httpBackend.when("GET", "/sync").respond(200, syncData);
return q.all([
return Promise.all([
client.syncLeftRooms().then(function() {
const room = client.getRoom(roomTwo);
const tok = room.getLiveTimeline().getPaginationToken(

View File

@@ -17,7 +17,7 @@ limitations under the License.
"use strict";
const anotherjson = require('another-json');
const q = require('q');
import Promise from 'bluebird';
import expect from 'expect';
const utils = require('../../lib/utils');
@@ -506,7 +506,7 @@ describe("megolm", function() {
200, getTestKeysQueryResponse('@bob:xyz'),
);
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test').then(() => {
throw new Error("sendTextMessage failed on an unknown device");
}, (e) => {
@@ -552,7 +552,7 @@ describe("megolm", function() {
const room = aliceTestClient.client.getRoom(ROOM_ID);
const pendingMsg = room.getPendingEvents()[0];
return q.all([
return Promise.all([
aliceTestClient.client.resendEvent(pendingMsg, room),
aliceTestClient.httpBackend.flushAllExpected(),
]);
@@ -574,7 +574,7 @@ describe("megolm", function() {
},
});
return q.all([
return Promise.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flush('/keys/query', 1),
]);
@@ -587,7 +587,7 @@ describe("megolm", function() {
event_id: '$event_id',
});
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(),
]);
@@ -619,7 +619,7 @@ describe("megolm", function() {
200, getTestKeysQueryResponse('@bob:xyz'),
);
return q.all([
return Promise.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flush('/keys/query', 1),
]);
@@ -634,7 +634,7 @@ describe("megolm", function() {
event_id: '$event_id',
});
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(),
]);
@@ -670,7 +670,7 @@ describe("megolm", function() {
200, getTestKeysQueryResponse('@bob:xyz'),
);
return q.all([
return Promise.all([
aliceTestClient.client.downloadKeys(['@bob:xyz']),
aliceTestClient.httpBackend.flushAllExpected(),
]).then((keys) => {
@@ -703,7 +703,7 @@ describe("megolm", function() {
};
});
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(),
]);
@@ -722,7 +722,7 @@ describe("megolm", function() {
};
});
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test2'),
aliceTestClient.httpBackend.flushAllExpected(),
]);
@@ -824,7 +824,7 @@ describe("megolm", function() {
};
});
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flushAllExpected(),
]);
@@ -875,7 +875,7 @@ describe("megolm", function() {
return aliceTestClient.httpBackend.flushAllExpected();
}).then(function() {
return q.all([downloadPromise, sendPromise]);
return Promise.all([downloadPromise, sendPromise]);
});
});
@@ -903,7 +903,7 @@ describe("megolm", function() {
aliceTestClient.httpBackend.when('PUT', '/send/').respond(
200, {event_id: '$event1'});
return q.all([
return Promise.all([
aliceTestClient.client.sendTextMessage(ROOM_ID, 'test'),
aliceTestClient.httpBackend.flush('/keys/query', 1).then(
() => aliceTestClient.httpBackend.flush('/send/', 1),

View File

@@ -1,6 +1,6 @@
"use strict";
import expect from 'expect';
import q from 'q';
import Promise from 'bluebird';
// load olm before the sdk if possible
import './olm-loader';
@@ -15,7 +15,7 @@ const MatrixEvent = sdk.MatrixEvent;
* @return {Promise} Resolves once the client has emitted a SYNCING event
*/
module.exports.syncPromise = function(client) {
const def = q.defer();
const def = Promise.defer();
const cb = (state) => {
if (state == 'SYNCING') {
def.resolve();

View File

@@ -5,7 +5,7 @@ import testUtils from '../../test-utils';
import utils from '../../../lib/utils';
import expect from 'expect';
import q from 'q';
import Promise from 'bluebird';
const signedDeviceList = {
"failures": {},
@@ -64,7 +64,7 @@ describe('DeviceList', function() {
dl.startTrackingDeviceList('@test1:sw1v.org');
const queryDefer1 = q.defer();
const queryDefer1 = Promise.defer();
downloadSpy.andReturn(queryDefer1.promise);
const prom1 = dl.refreshOutdatedDeviceLists();
@@ -83,7 +83,7 @@ describe('DeviceList', function() {
dl.startTrackingDeviceList('@test1:sw1v.org');
const queryDefer1 = q.defer();
const queryDefer1 = Promise.defer();
downloadSpy.andReturn(queryDefer1.promise);
const prom1 = dl.refreshOutdatedDeviceLists();
@@ -91,7 +91,7 @@ describe('DeviceList', function() {
downloadSpy.reset();
// outdated notif arrives while the request is in flight.
const queryDefer2 = q.defer();
const queryDefer2 = Promise.defer();
downloadSpy.andReturn(queryDefer2.promise);
dl.invalidateUserDeviceList('@test1:sw1v.org');
@@ -110,7 +110,7 @@ describe('DeviceList', function() {
console.log("Creating new devicelist to simulate app reload");
downloadSpy.reset();
const dl2 = createTestDeviceList();
const queryDefer3 = q.defer();
const queryDefer3 = Promise.defer();
downloadSpy.andReturn(queryDefer3.promise);
const prom3 = dl2.refreshOutdatedDeviceLists();

View File

@@ -5,7 +5,7 @@ try {
}
import expect from 'expect';
import q from 'q';
import Promise from 'bluebird';
import sdk from '../../../..';
import algorithms from '../../../../lib/crypto/algorithms';
@@ -125,7 +125,7 @@ describe("MegolmDecryption", function() {
const deviceInfo = {};
mockCrypto.getStoredDevice.andReturn(deviceInfo);
mockOlmLib.ensureOlmSessionsForDevices.andReturn(
q({'@alice:foo': {'alidevice': {
Promise.resolve({'@alice:foo': {'alidevice': {
sessionId: 'alisession',
}}}),
);
@@ -136,7 +136,7 @@ describe("MegolmDecryption", function() {
megolmDecryption.shareKeysWithDevice(keyRequest);
// it's asynchronous, so we have to wait a bit
return q.delay(1).then(() => {
return Promise.delay(1).then(() => {
// check that it called encryptMessageForDevice with
// appropriate args.
expect(mockOlmLib.encryptMessageForDevice.calls.length)

View File

@@ -16,7 +16,7 @@ limitations under the License.
"use strict";
import 'source-map-support/register';
const q = require("q");
import Promise from 'bluebird';
const sdk = require("../..");
const utils = require("../test-utils");
@@ -81,7 +81,7 @@ describe("InteractiveAuth", function() {
type: "logintype",
foo: "bar",
});
return q(requestRes);
return Promise.resolve(requestRes);
});
ia.attemptAuth().then(function(res) {
@@ -138,7 +138,7 @@ describe("InteractiveAuth", function() {
type: "logintype",
foo: "bar",
});
return q(requestRes);
return Promise.resolve(requestRes);
});
ia.submitAuthDict({

View File

@@ -1,6 +1,6 @@
"use strict";
import 'source-map-support/register';
const q = require("q");
import Promise from 'bluebird';
const sdk = require("../..");
const MatrixClient = sdk.MatrixClient;
const utils = require("../test-utils");
@@ -62,7 +62,7 @@ describe("MatrixClient", function() {
let pendingLookup = null;
function httpReq(cb, method, path, qp, data, prefix) {
if (path === KEEP_ALIVE_PATH && acceptKeepalives) {
return q();
return Promise.resolve();
}
const next = httpLookups.shift();
const logLine = (
@@ -84,7 +84,7 @@ describe("MatrixClient", function() {
);
}
pendingLookup = {
promise: q.defer().promise,
promise: Promise.defer().promise,
method: method,
path: path,
};
@@ -109,7 +109,7 @@ describe("MatrixClient", function() {
}
if (next.error) {
return q.reject({
return Promise.reject({
errcode: next.error.errcode,
httpStatus: next.error.httpStatus,
name: next.error.errcode,
@@ -117,10 +117,10 @@ describe("MatrixClient", function() {
data: next.error,
});
}
return q(next.data);
return Promise.resolve(next.data);
}
expect(true).toBe(false, "Expected different request. " + logLine);
return q.defer().promise;
return Promise.defer().promise;
}
beforeEach(function() {
@@ -136,8 +136,8 @@ describe("MatrixClient", function() {
"getFilterIdByName", "setFilterIdByName", "getFilter", "storeFilter",
"getSyncAccumulator", "startup", "deleteAllData",
].reduce((r, k) => { r[k] = expect.createSpy(); return r; }, {});
store.getSavedSync = expect.createSpy().andReturn(q(null));
store.setSyncData = expect.createSpy().andReturn(q(null));
store.getSavedSync = expect.createSpy().andReturn(Promise.resolve(null));
store.setSyncData = expect.createSpy().andReturn(Promise.resolve(null));
client = new MatrixClient({
baseUrl: "https://my.home.server",
idBaseUrl: identityServerUrl,
@@ -174,10 +174,10 @@ describe("MatrixClient", function() {
// a DIFFERENT test (pollution between tests!) - we return unresolved
// promises to stop the client from continuing to run.
client._http.authedRequest.andCall(function() {
return q.defer().promise;
return Promise.defer().promise;
});
client._http.authedRequestWithPrefix.andCall(function() {
return q.defer().promise;
return Promise.defer().promise;
});
});

View File

@@ -2,7 +2,7 @@
/* eslint new-cap: "off" */
import 'source-map-support/register';
const q = require("q");
import Promise from 'bluebird';
const sdk = require("../..");
const MatrixScheduler = sdk.MatrixScheduler;
const MatrixError = sdk.MatrixError;
@@ -41,7 +41,7 @@ describe("MatrixScheduler", function() {
});
retryFn = null;
queueFn = null;
defer = q.defer();
defer = Promise.defer();
});
afterEach(function() {
@@ -55,8 +55,8 @@ describe("MatrixScheduler", function() {
queueFn = function() {
return "one_big_queue";
};
const deferA = q.defer();
const deferB = q.defer();
const deferA = Promise.defer();
const deferB = Promise.defer();
let resolvedA = false;
scheduler.setProcessFunction(function(event) {
if (resolvedA) {
@@ -80,7 +80,7 @@ describe("MatrixScheduler", function() {
it("should invoke the retryFn on failure and wait the amount of time specified",
function(done) {
const waitTimeMs = 1500;
const retryDefer = q.defer();
const retryDefer = Promise.defer();
retryFn = function() {
retryDefer.resolve();
return waitTimeMs;
@@ -97,7 +97,7 @@ describe("MatrixScheduler", function() {
return defer.promise;
} else if (procCount === 2) {
// don't care about this defer
return q.defer().promise;
return Promise.defer().promise;
}
expect(procCount).toBeLessThan(3);
});
@@ -125,8 +125,8 @@ describe("MatrixScheduler", function() {
return "yep";
};
const deferA = q.defer();
const deferB = q.defer();
const deferA = Promise.defer();
const deferB = Promise.defer();
let procCount = 0;
scheduler.setProcessFunction(function(ev) {
procCount += 1;
@@ -177,7 +177,7 @@ describe("MatrixScheduler", function() {
const expectOrder = [
eventA.getId(), eventB.getId(), eventD.getId(),
];
const deferA = q.defer();
const deferA = Promise.defer();
scheduler.setProcessFunction(function(event) {
const id = expectOrder.shift();
expect(id).toEqual(event.getId());

View File

@@ -1,6 +1,6 @@
"use strict";
import 'source-map-support/register';
const q = require("q");
import Promise from 'bluebird';
const sdk = require("../..");
const EventTimeline = sdk.EventTimeline;
const TimelineWindow = sdk.TimelineWindow;
@@ -157,7 +157,7 @@ describe("TimelineWindow", function() {
client = {};
client.getEventTimeline = function(timelineSet0, eventId0) {
expect(timelineSet0).toBe(timelineSet);
return q(timeline);
return Promise.resolve(timeline);
};
return new TimelineWindow(client, timelineSet, opts);
@@ -191,7 +191,7 @@ describe("TimelineWindow", function() {
client.getEventTimeline = function(timelineSet0, eventId0) {
expect(timelineSet0).toBe(timelineSet);
expect(eventId0).toEqual(eventId);
return q(timeline);
return Promise.resolve(timeline);
};
const timelineWindow = new TimelineWindow(client, timelineSet);
@@ -219,7 +219,7 @@ describe("TimelineWindow", function() {
.toBe(false);
expect(timelineWindow.canPaginate(EventTimeline.FORWARDS))
.toBe(false);
return q(timeline);
return Promise.resolve(timeline);
};
timelineWindow.load(eventId, 3).then(function() {
@@ -383,7 +383,7 @@ describe("TimelineWindow", function() {
expect(opts.limit).toEqual(2);
addEventsToTimeline(timeline, 3, false);
return q(true);
return Promise.resolve(true);
};
timelineWindow.load(eventId, 3).then(function() {
@@ -416,7 +416,7 @@ describe("TimelineWindow", function() {
expect(opts.limit).toEqual(2);
addEventsToTimeline(timeline, 3, true);
return q(true);
return Promise.resolve(true);
};
timelineWindow.load(eventId, 3).then(function() {
@@ -449,7 +449,7 @@ describe("TimelineWindow", function() {
expect(opts.backwards).toBe(false);
expect(opts.limit).toEqual(2);
paginateCount += 1;
return q(true);
return Promise.resolve(true);
};
timelineWindow.load(eventId, 3).then(function() {

View File

@@ -23,7 +23,7 @@ const PushProcessor = require('./pushprocessor');
* @module client
*/
const EventEmitter = require("events").EventEmitter;
const q = require("q");
import Promise from 'bluebird';
const url = require('url');
const httpApi = require("./http-api");
@@ -198,7 +198,7 @@ MatrixClient.prototype.clearStores = function() {
if (this._cryptoStore) {
promises.push(this._cryptoStore.deleteAllData());
}
return q.all(promises);
return Promise.all(promises);
};
/**
@@ -368,7 +368,7 @@ MatrixClient.prototype.uploadKeys = function() {
*/
MatrixClient.prototype.downloadKeys = function(userIds, forceDownload) {
if (this._crypto === null) {
return q.reject(new Error("End-to-end encryption disabled"));
return Promise.reject(new Error("End-to-end encryption disabled"));
}
return this._crypto.downloadKeys(userIds, forceDownload);
};
@@ -551,7 +551,7 @@ MatrixClient.prototype.setRoomEncryption = function(roomId, config) {
throw new Error("End-to-End encryption disabled");
}
this._crypto.setRoomEncryption(roomId, config);
return q();
return Promise.resolve();
};
/**
@@ -577,7 +577,7 @@ MatrixClient.prototype.isRoomEncrypted = function(roomId) {
*/
MatrixClient.prototype.exportRoomKeys = function() {
if (!this._crypto) {
return q.reject(new Error("End-to-end encryption disabled"));
return Promise.reject(new Error("End-to-end encryption disabled"));
}
return this._crypto.exportRoomKeys();
};
@@ -730,10 +730,10 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
const room = this.getRoom(roomIdOrAlias);
if (room && room.hasMembershipState(this.credentials.userId, "join")) {
return q(room);
return Promise.resolve(room);
}
let sign_promise = q();
let sign_promise = Promise.resolve();
if (opts.inviteSignUrl) {
sign_promise = this._http.requestOtherUrl(
@@ -742,7 +742,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
);
}
const defer = q.defer();
const defer = Promise.defer();
const self = this;
sign_promise.then(function(signed_invite_object) {
@@ -761,7 +761,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
// v2 will do this for us
// return syncApi.syncRoom(room);
}
return q(room);
return Promise.resolve(room);
}).done(function(room) {
_resolve(callback, defer, room);
}, function(err) {
@@ -981,10 +981,10 @@ MatrixClient.prototype.sendEvent = function(roomId, eventType, content, txnId,
// marks the event as sent/unsent
// returns a promise which resolves with the result of the send request
function _sendEvent(client, room, event, callback) {
// Add an extra q() to turn synchronous exceptions into promise rejections,
// Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections,
// so that we can handle synchronous and asynchronous exceptions with the
// same code path.
return q().then(function() {
return Promise.resolve().then(function() {
let encryptionPromise = null;
if (client._crypto) {
encryptionPromise = client._crypto.encryptEventIfNeeded(event, room);
@@ -1238,7 +1238,7 @@ MatrixClient.prototype.sendHtmlEmote = function(roomId, body, htmlBody, callback
*/
MatrixClient.prototype.sendReceipt = function(event, receiptType, callback) {
if (this.isGuest()) {
return q({}); // guests cannot send receipts so don't bother.
return Promise.resolve({}); // guests cannot send receipts so don't bother.
}
const path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", {
@@ -1315,7 +1315,7 @@ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
const key = ts + "_" + url;
const og = this.urlPreviewCache[key];
if (og) {
return q(og);
return Promise.resolve(og);
}
const self = this;
@@ -1341,7 +1341,7 @@ MatrixClient.prototype.getUrlPreview = function(url, ts, callback) {
*/
MatrixClient.prototype.sendTyping = function(roomId, isTyping, timeoutMs, callback) {
if (this.isGuest()) {
return q({}); // guests cannot send typing notifications so don't bother.
return Promise.resolve({}); // guests cannot send typing notifications so don't bother.
}
const path = utils.encodeUri("/rooms/$roomId/typing/$userId", {
@@ -1402,7 +1402,7 @@ MatrixClient.prototype.inviteByThreePid = function(roomId, medium, address, call
let identityServerUrl = this.getIdentityServerUrl();
if (!identityServerUrl) {
return q.reject(new MatrixError({
return Promise.reject(new MatrixError({
error: "No supplied identity server URL",
errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM",
}));
@@ -1742,13 +1742,13 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
}
if (room.oldState.paginationToken === null) {
return q(room); // already at the start.
return Promise.resolve(room); // already at the start.
}
// attempt to grab more events from the store first
const numAdded = this.store.scrollback(room, limit).length;
if (numAdded === limit) {
// store contained everything we needed.
return q(room);
return Promise.resolve(room);
}
// reduce the required number of events appropriately
limit = limit - numAdded;
@@ -1761,7 +1761,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
limit: limit,
dir: 'b',
};
const defer = q.defer();
const defer = Promise.defer();
info = {
promise: defer.promise,
errorTs: null,
@@ -1769,7 +1769,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
const self = this;
// wait for a time before doing this request
// (which may be 0 in order not to special case the code paths)
q.delay(timeToWaitMs).then(function() {
Promise.delay(timeToWaitMs).then(function() {
return self._http.authedRequest(callback, "GET", path, params);
}).done(function(res) {
const matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self));
@@ -1812,7 +1812,7 @@ MatrixClient.prototype.paginateEventContext = function(eventContext, opts) {
const token = eventContext.getPaginateToken(backwards);
if (!token) {
// no more results.
return q.reject(new Error("No paginate token"));
return Promise.reject(new Error("No paginate token"));
}
const dir = backwards ? 'b' : 'f';
@@ -1881,7 +1881,7 @@ MatrixClient.prototype.getEventTimeline = function(timelineSet, eventId) {
}
if (timelineSet.getTimelineForEvent(eventId)) {
return q(timelineSet.getTimelineForEvent(eventId));
return Promise.resolve(timelineSet.getTimelineForEvent(eventId));
}
const path = utils.encodeUri(
@@ -1969,7 +1969,7 @@ MatrixClient.prototype.paginateEventTimeline = function(eventTimeline, opts) {
const token = eventTimeline.getPaginationToken(dir);
if (!token) {
// no token - no results.
return q(false);
return Promise.resolve(false);
}
const pendingRequest = eventTimeline._paginationRequests[dir];
@@ -2146,14 +2146,14 @@ MatrixClient.prototype.setGuestAccess = function(roomId, opts) {
guest_access: opts.allowJoin ? "can_join" : "forbidden",
});
let readPromise = q();
let readPromise = Promise.resolve();
if (opts.allowRead) {
readPromise = this.sendStateEvent(roomId, "m.room.history_visibility", {
history_visibility: "world_readable",
});
}
return q.all([readPromise, writePromise]);
return Promise.all([readPromise, writePromise]);
};
// Registration/Login operations
@@ -2421,7 +2421,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
} else if (!hasDontNotifyRule) {
// Remove the existing one before setting the mute push rule
// This is a workaround to SYN-590 (Push rule update fails)
deferred = q.defer();
deferred = Promise.defer();
this.deletePushRule(scope, "room", roomPushRule.rule_id)
.done(function() {
self.addPushRule(scope, "room", roomId, {
@@ -2441,7 +2441,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
if (deferred) {
// Update this.pushRules when the operation completes
const ruleRefreshDeferred = q.defer();
const ruleRefreshDeferred = Promise.defer();
deferred.done(function() {
self.getPushRules().done(function(result) {
self.pushRules = result;
@@ -2555,7 +2555,7 @@ MatrixClient.prototype.backPaginateRoomEventsSearch = function(searchResults) {
// nicely with HTTP errors.
if (!searchResults.next_batch) {
return q.reject(new Error("Cannot backpaginate event search any further"));
return Promise.reject(new Error("Cannot backpaginate event search any further"));
}
if (searchResults.pendingRequest) {
@@ -2624,7 +2624,7 @@ MatrixClient.prototype._processRoomEventsSearch = function(searchResults, respon
MatrixClient.prototype.syncLeftRooms = function() {
// Guard against multiple calls whilst ongoing and multiple calls post success
if (this._syncedLeftRooms) {
return q([]); // don't call syncRooms again if it succeeded.
return Promise.resolve([]); // don't call syncRooms again if it succeeded.
}
if (this._syncLeftRoomsPromise) {
return this._syncLeftRoomsPromise; // return the ongoing request
@@ -2683,7 +2683,7 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
if (allowCached) {
const filter = this.store.getFilter(userId, filterId);
if (filter) {
return q(filter);
return Promise.resolve(filter);
}
}
@@ -2712,7 +2712,7 @@ MatrixClient.prototype.getFilter = function(userId, filterId, allowCached) {
*/
MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
const filterId = this.store.getFilterIdByName(filterName);
let promise = q();
let promise = Promise.resolve();
const self = this;
if (filterId) {
@@ -2727,7 +2727,7 @@ MatrixClient.prototype.getOrCreateFilter = function(filterName, filter) {
// super, just use that.
// debuglog("Using existing filter ID %s: %s", filterId,
// JSON.stringify(oldDef));
return q(filterId);
return Promise.resolve(filterId);
}
// debuglog("Existing filter ID %s: %s; new filter: %s",
// filterId, JSON.stringify(oldDef), JSON.stringify(newDef));

View File

@@ -21,7 +21,7 @@ limitations under the License.
* Manages the list of other users' devices
*/
import q from 'q';
import Promise from 'bluebird';
import DeviceInfo from './deviceinfo';
import olmlib from './olmlib';
@@ -96,7 +96,7 @@ export default class DeviceList {
console.log("downloadKeys: already have all necessary keys");
}
return q.all(promises).then(() => {
return Promise.all(promises).then(() => {
return this._getDevicesFromStore(userIds);
});
}
@@ -309,7 +309,7 @@ export default class DeviceList {
_doKeyDownload(users) {
if (users.length === 0) {
// nothing to do
return q();
return Promise.resolve();
}
const prom = this._serialiser.updateDevicesForUsers(
@@ -416,7 +416,7 @@ class DeviceListUpdateSerialiser {
this._nextSyncToken = syncToken;
if (!this._queuedQueryDeferred) {
this._queuedQueryDeferred = q.defer();
this._queuedQueryDeferred = Promise.defer();
}
if (this._downloadInProgress) {
@@ -459,7 +459,7 @@ class DeviceListUpdateSerialiser {
//
// of course we ought to do this in a web worker or similar, but
// this serves as an easy solution for now.
let prom = q();
let prom = Promise.resolve();
for (const userId of downloadUsers) {
prom = prom.delay(5).then(() => {
this._processQueryResponseForUser(userId, dk[userId]);

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from 'q';
import Promise from 'bluebird';
import utils from '../utils';
@@ -251,7 +251,7 @@ export default class OutgoingRoomKeyRequestManager {
_sendOutgoingRoomKeyRequests() {
if (!this._clientRunning) {
this._sendOutgoingRoomKeyRequestsTimer = null;
return q();
return Promise.resolve();
}
console.log("Looking for queued outgoing room key requests");

View File

@@ -21,7 +21,7 @@ limitations under the License.
* @module crypto/algorithms/megolm
*/
const q = require("q");
import Promise from 'bluebird';
const utils = require("../../utils");
const olmlib = require("../olmlib");
@@ -132,7 +132,7 @@ function MegolmEncryption(params) {
// are using, and which devices we have shared the keys with. It resolves
// with an OutboundSessionInfo (or undefined, for the first message in the
// room).
this._setupPromise = q();
this._setupPromise = Promise.resolve();
// default rotation periods
this._sessionRotationPeriodMsgs = 100;
@@ -348,7 +348,7 @@ MegolmEncryption.prototype._shareKeyWithDevices = function(session, devicesByUse
}
if (!haveTargets) {
return q();
return Promise.resolve();
}
// TODO: retries

View File

@@ -20,7 +20,7 @@ limitations under the License.
*
* @module crypto/algorithms/olm
*/
const q = require('q');
import Promise from 'bluebird';
const utils = require("../../utils");
const olmlib = require("../olmlib");
@@ -60,7 +60,7 @@ OlmEncryption.prototype._ensureSession = function(roomMembers) {
if (this._sessionPrepared) {
// prep already done
return q();
return Promise.resolve();
}
const self = this;

View File

@@ -21,7 +21,7 @@ limitations under the License.
*/
const anotherjson = require('another-json');
const q = require("q");
import Promise from 'bluebird';
import {EventEmitter} from 'events';
const utils = require("../utils");
@@ -287,7 +287,7 @@ function _maybeUploadOneTimeKeys(crypto) {
}
crypto._oneTimeKeyCheckInProgress = true;
q().then(() => {
Promise.resolve().then(() => {
// ask the server how many keys we have
return crypto._baseApis.uploadKeysRequest({}, {
device_id: crypto._deviceId,
@@ -701,7 +701,7 @@ Crypto.prototype.isRoomEncrypted = function(roomId) {
* session export objects
*/
Crypto.prototype.exportRoomKeys = function() {
return q(
return Promise.resolve(
this._sessionStore.getAllEndToEndInboundGroupSessionKeys().map(
(s) => {
const sess = this._olmDevice.exportInboundGroupSession(

View File

@@ -20,7 +20,7 @@ limitations under the License.
* Utilities common to olm encryption algorithms
*/
const q = require('q');
import Promise from 'bluebird';
const anotherjson = require('another-json');
const utils = require("../utils");
@@ -148,7 +148,7 @@ module.exports.ensureOlmSessionsForDevices = function(
}
if (devicesWithoutSession.length === 0) {
return q(result);
return Promise.resolve(result);
}
// TODO: this has a race condition - if we try to send another message

View File

@@ -1,4 +1,4 @@
import q from 'q';
import Promise from 'bluebird';
import utils from '../../utils';
export const VERSION = 1;
@@ -39,7 +39,7 @@ export class Backend {
getOrAddOutgoingRoomKeyRequest(request) {
const requestBody = request.requestBody;
const deferred = q.defer();
const deferred = Promise.defer();
const txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite");
txn.onerror = deferred.reject;
@@ -81,7 +81,7 @@ export class Backend {
* not found
*/
getOutgoingRoomKeyRequest(requestBody) {
const deferred = q.defer();
const deferred = Promise.defer();
const txn = this._db.transaction("outgoingRoomKeyRequests", "readonly");
txn.onerror = deferred.reject;
@@ -146,7 +146,7 @@ export class Backend {
*/
getOutgoingRoomKeyRequestByState(wantedStates) {
if (wantedStates.length === 0) {
return q(null);
return Promise.resolve(null);
}
// this is a bit tortuous because we need to make sure we do the lookup
@@ -284,7 +284,7 @@ function createDatabase(db) {
}
function promiseifyTxn(txn) {
return new q.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
txn.oncomplete = resolve;
txn.onerror = reject;
});

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from 'q';
import Promise from 'bluebird';
import MemoryCryptoStore from './memory-crypto-store';
import * as IndexedDBCryptoStoreBackend from './indexeddb-crypto-store-backend';
@@ -56,7 +56,7 @@ export default class IndexedDBCryptoStore {
return this._backendPromise;
}
this._backendPromise = new q.Promise((resolve, reject) => {
this._backendPromise = new Promise((resolve, reject) => {
if (!this._indexedDB) {
reject(new Error('no indexeddb support available'));
return;
@@ -107,7 +107,7 @@ export default class IndexedDBCryptoStore {
* @returns {Promise} resolves when the store has been cleared.
*/
deleteAllData() {
return new q.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
if (!this._indexedDB) {
reject(new Error('no indexeddb support available'));
return;

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from 'q';
import Promise from 'bluebird';
import utils from '../../utils';
@@ -38,7 +38,7 @@ export default class MemoryCryptoStore {
* @returns {Promise} Promise which resolves when the store has been cleared.
*/
deleteAllData() {
return q();
return Promise.resolve();
}
/**
@@ -90,10 +90,10 @@ export default class MemoryCryptoStore {
getOutgoingRoomKeyRequest(requestBody) {
for (const existing of this._outgoingRoomKeyRequests) {
if (utils.deepCompare(existing.requestBody, requestBody)) {
return q(existing);
return Promise.resolve(existing);
}
}
return q(null);
return Promise.resolve(null);
}
/**
@@ -109,11 +109,11 @@ export default class MemoryCryptoStore {
for (const req of this._outgoingRoomKeyRequests) {
for (const state of wantedStates) {
if (req.state === state) {
return q(req);
return Promise.resolve(req);
}
}
}
return q(null);
return Promise.resolve(null);
}
/**
@@ -139,13 +139,13 @@ export default class MemoryCryptoStore {
`Cannot update room key request from ${expectedState} ` +
`as it was already updated to ${req.state}`,
);
return q(null);
return Promise.resolve(null);
}
Object.assign(req, updates);
return q(req);
return Promise.resolve(req);
}
return q(null);
return Promise.resolve(null);
}
/**
@@ -170,13 +170,13 @@ export default class MemoryCryptoStore {
`Cannot delete room key request in state ${req.state} `
+ `(expected ${expectedState})`,
);
return q(null);
return Promise.resolve(null);
}
this._outgoingRoomKeyRequests.splice(i, 1);
return q(req);
return Promise.resolve(req);
}
return q(null);
return Promise.resolve(null);
}
}

View File

@@ -18,7 +18,7 @@ limitations under the License.
* This is an internal module. See {@link MatrixHttpApi} for the public class.
* @module http-api
*/
const q = require("q");
import Promise from 'bluebird';
const parseContentType = require('content-type').parse;
const utils = require("./utils");
@@ -219,7 +219,7 @@ module.exports.MatrixHttpApi.prototype = {
}
if (global.XMLHttpRequest) {
const defer = q.defer();
const defer = Promise.defer();
const xhr = new global.XMLHttpRequest();
upload.xhr = xhr;
const cb = requestCallback(defer, opts.callback, this.opts.onlyData);
@@ -343,7 +343,7 @@ module.exports.MatrixHttpApi.prototype = {
opts.form = params;
}
const defer = q.defer();
const defer = Promise.defer();
this.opts.request(
opts,
requestCallback(defer, callback, this.opts.onlyData),
@@ -676,7 +676,7 @@ module.exports.MatrixHttpApi.prototype = {
}
}
const defer = q.defer();
const defer = Promise.defer();
let timeoutId;
let timedOut = false;

View File

@@ -17,7 +17,7 @@ limitations under the License.
"use strict";
/** @module interactive-auth */
const q = require("q");
import Promise from 'bluebird';
const url = require("url");
const utils = require("./utils");
@@ -115,11 +115,11 @@ InteractiveAuth.prototype = {
* no suitable authentication flow can be found
*/
attemptAuth: function() {
this._completionDeferred = q.defer();
this._completionDeferred = Promise.defer();
// wrap in a promise so that if _startNextAuthStage
// throws, it rejects the promise in a consistent way
return q().then(() => {
return Promise.resolve().then(() => {
// if we have no flows, try a request (we'll have
// just a session ID in _data if resuming)
if (!this._data.flows) {
@@ -258,12 +258,12 @@ InteractiveAuth.prototype = {
// hackery to make sure that synchronous exceptions end up in the catch
// handler (without the additional event loop entailed by q.fcall or an
// extra q().then)
// extra Promise.resolve().then)
let prom;
try {
prom = this._requestCallback(auth, background);
} catch (e) {
prom = q.reject(e);
prom = Promise.reject(e);
}
prom = prom.then(

View File

@@ -20,7 +20,7 @@ limitations under the License.
* @module scheduler
*/
const utils = require("./utils");
const q = require("q");
import Promise from 'bluebird';
const DEBUG = false; // set true to enable console logging.
@@ -118,7 +118,7 @@ MatrixScheduler.prototype.queueEvent = function(event) {
if (!this._queues[queueName]) {
this._queues[queueName] = [];
}
const defer = q.defer();
const defer = Promise.defer();
this._queues[queueName].push({
event: event,
defer: defer,

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from "q";
import Promise from 'bluebird';
import SyncAccumulator from "../sync-accumulator";
import utils from "../utils";
@@ -44,7 +44,7 @@ function createDatabase(db) {
*/
function selectQuery(store, keyRange, resultMapper) {
const query = store.openCursor(keyRange);
return q.Promise((resolve, reject) => { /*eslint new-cap: 0*/
return new Promise((resolve, reject) => {
const results = [];
query.onerror = (event) => {
reject(new Error("Query failed: " + event.target.errorCode));
@@ -63,7 +63,7 @@ function selectQuery(store, keyRange, resultMapper) {
}
function promiseifyTxn(txn) {
return new q.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
txn.oncomplete = function(event) {
resolve(event);
};
@@ -74,7 +74,7 @@ function promiseifyTxn(txn) {
}
function promiseifyRequest(req) {
return new q.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
req.onsuccess = function(event) {
resolve(event);
};
@@ -113,7 +113,7 @@ LocalIndexedDBStoreBackend.prototype = {
*/
connect: function() {
if (this.db) {
return q();
return Promise.resolve();
}
const req = this.indexedDB.open(this._dbName, VERSION);
req.onupgradeneeded = (ev) => {
@@ -143,7 +143,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves on success
*/
_init: function() {
return q.all([
return Promise.all([
this._loadAccountData(),
this._loadSyncData(),
]).then(([accountData, syncData]) => {
@@ -163,7 +163,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolved when the database is cleared.
*/
clearDatabase: function() {
return new q.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
console.log(`Removing indexeddb instance: ${this._dbName}`);
const req = this.indexedDB.deleteDatabase(this._dbName);
@@ -204,18 +204,18 @@ LocalIndexedDBStoreBackend.prototype = {
if (copy === undefined) copy = true;
const data = this._syncAccumulator.getJSON();
if (!data.nextBatch) return q(null);
if (!data.nextBatch) return Promise.resolve(null);
if (copy) {
// We must deep copy the stored data so that the /sync processing code doesn't
// corrupt the internal state of the sync accumulator (it adds non-clonable keys)
return q(utils.deepCopy(data));
return Promise.resolve(utils.deepCopy(data));
} else {
return q(data);
return Promise.resolve(data);
}
},
setSyncData: function(syncData) {
return q().then(() => {
return Promise.resolve().then(() => {
this._syncAccumulator.accumulate(syncData);
});
},
@@ -223,7 +223,7 @@ LocalIndexedDBStoreBackend.prototype = {
syncToDatabase: function(userTuples) {
const syncData = this._syncAccumulator.getJSON();
return q.all([
return Promise.all([
this._persistUserPresenceEvents(userTuples),
this._persistAccountData(syncData.accountData),
this._persistSyncData(syncData.nextBatch, syncData.roomsData),
@@ -238,7 +238,7 @@ LocalIndexedDBStoreBackend.prototype = {
*/
_persistSyncData: function(nextBatch, roomsData) {
console.log("Persisting sync data up to ", nextBatch);
return q.try(() => {
return Promise.try(() => {
const txn = this.db.transaction(["sync"], "readwrite");
const store = txn.objectStore("sync");
store.put({
@@ -257,7 +257,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves if the events were persisted.
*/
_persistAccountData: function(accountData) {
return q.try(() => {
return Promise.try(() => {
const txn = this.db.transaction(["accountData"], "readwrite");
const store = txn.objectStore("accountData");
for (let i = 0; i < accountData.length; i++) {
@@ -276,7 +276,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves if the users were persisted.
*/
_persistUserPresenceEvents: function(tuples) {
return q.try(() => {
return Promise.try(() => {
const txn = this.db.transaction(["users"], "readwrite");
const store = txn.objectStore("users");
for (const tuple of tuples) {
@@ -296,7 +296,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object[]>} A list of presence events in their raw form.
*/
getUserPresenceEvents: function() {
return q.try(() => {
return Promise.try(() => {
const txn = this.db.transaction(["users"], "readonly");
const store = txn.objectStore("users");
return selectQuery(store, undefined, (cursor) => {
@@ -310,7 +310,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object[]>} A list of raw global account events.
*/
_loadAccountData: function() {
return q.try(() => {
return Promise.try(() => {
const txn = this.db.transaction(["accountData"], "readonly");
const store = txn.objectStore("accountData");
return selectQuery(store, undefined, (cursor) => {
@@ -324,7 +324,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object>} An object with "roomsData" and "nextBatch" keys.
*/
_loadSyncData: function() {
return q.try(() => {
return Promise.try(() => {
const txn = this.db.transaction(["sync"], "readonly");
const store = txn.objectStore("sync");
return selectQuery(store, undefined, (cursor) => {

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from "q";
import Promise from 'bluebird';
/**
* An IndexedDB store backend where the actual backend sits in a web
@@ -96,9 +96,9 @@ RemoteIndexedDBStoreBackend.prototype = {
_doCmd: function(cmd, args) {
// wrap in a q so if the postMessage throws,
// the promise automatically gets rejected
return q().then(() => {
return Promise.resolve().then(() => {
const seq = this._nextSeq++;
const def = q.defer();
const def = Promise.defer();
this._inFlight[seq] = def;

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from "q";
import Promise from 'bluebird';
import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js";
/**
@@ -61,7 +61,7 @@ class IndexedDBStoreWorker {
// because it's a web worker and there is no window).
indexedDB, msg.args[0],
);
prom = q();
prom = Promise.resolve();
break;
case 'connect':
prom = this.backend.connect();

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import q from "q";
import Promise from 'bluebird';
import {MatrixInMemoryStore} from "./memory";
import utils from "../utils";
import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js";
@@ -115,7 +115,7 @@ utils.inherits(IndexedDBStore, MatrixInMemoryStore);
*/
IndexedDBStore.prototype.startup = function() {
if (this.startedUp) {
return q();
return Promise.resolve();
}
return this.backend.connect().then(() => {
@@ -164,7 +164,7 @@ IndexedDBStore.prototype.save = function() {
if (now - this._syncTs > WRITE_DELAY_MS) {
return this._reallySave();
}
return q();
return Promise.resolve();
};
IndexedDBStore.prototype._reallySave = function() {

View File

@@ -21,7 +21,7 @@ limitations under the License.
*/
const utils = require("../utils");
const User = require("../models/user");
const q = require("q");
import Promise from 'bluebird';
/**
* Construct a new in-memory data store for the Matrix Client.
@@ -284,7 +284,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* @return {Promise} An immediately resolved promise.
*/
setSyncData: function(syncData) {
return q();
return Promise.resolve();
},
/**
@@ -297,7 +297,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* @return {Promise} An immediately resolved promise.
*/
startup: function() {
return q();
return Promise.resolve();
},
/**
@@ -306,7 +306,7 @@ module.exports.MatrixInMemoryStore.prototype = {
* is no saved sync data.
*/
getSavedSync: function() {
return q(null);
return Promise.resolve(null);
},
/**
@@ -329,6 +329,6 @@ module.exports.MatrixInMemoryStore.prototype = {
this.accountData = {
// type : content
};
return q();
return Promise.resolve();
},
};

View File

@@ -15,7 +15,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
import q from "q";
import Promise from 'bluebird';
/**
* This is an internal module.
* @module store/stub
@@ -189,7 +189,7 @@ StubStore.prototype = {
* @return {Promise} An immediately resolved promise.
*/
setSyncData: function(syncData) {
return q();
return Promise.resolve();
},
/**
@@ -202,7 +202,7 @@ StubStore.prototype = {
* @return {Promise} An immediately resolved promise.
*/
startup: function() {
return q();
return Promise.resolve();
},
/**
@@ -211,7 +211,7 @@ StubStore.prototype = {
* is no saved sync data.
*/
getSavedSync: function() {
return q(null);
return Promise.resolve(null);
},
/**
@@ -220,7 +220,7 @@ StubStore.prototype = {
* @return {Promise} An immediately resolved promise.
*/
deleteAllData: function() {
return q();
return Promise.resolve();
},
};

View File

@@ -24,7 +24,7 @@ limitations under the License.
* an alternative syncing API, we may want to have a proper syncing interface
* for HTTP and WS at some point.
*/
const q = require("q");
import Promise from 'bluebird';
const User = require("./models/user");
const Room = require("./models/room");
const utils = require("./utils");
@@ -558,7 +558,7 @@ SyncApi.prototype._sync = function(syncOptions) {
// if there is data there.
syncPromise = client.store.getSavedSync();
} else {
syncPromise = q(null);
syncPromise = Promise.resolve(null);
}
syncPromise.then((savedSync) => {
@@ -600,7 +600,7 @@ SyncApi.prototype._sync = function(syncOptions) {
return data;
});
} else {
return q(data);
return Promise.resolve(data);
}
}).done((data) => {
try {
@@ -1009,7 +1009,7 @@ SyncApi.prototype._startKeepAlives = function(delay) {
self._pokeKeepAlive();
}
if (!this._connectionReturnedDefer) {
this._connectionReturnedDefer = q.defer();
this._connectionReturnedDefer = Promise.defer();
}
return this._connectionReturnedDefer.promise;
};
@@ -1127,7 +1127,7 @@ SyncApi.prototype._resolveInvites = function(room) {
const user = client.getUser(member.userId);
let promise;
if (user) {
promise = q({
promise = Promise.resolve({
avatar_url: user.avatarUrl,
displayname: user.displayName,
});

View File

@@ -17,7 +17,7 @@ limitations under the License.
/** @module timeline-window */
const q = require("q");
import Promise from 'bluebird';
const EventTimeline = require("./models/event-timeline");
/**
@@ -133,17 +133,16 @@ TimelineWindow.prototype.load = function(initialEventId, initialWindowSize) {
if (initialEventId) {
const prom = this._client.getEventTimeline(this._timelineSet, initialEventId);
const promState = prom.inspect();
if (promState.state == 'fulfilled') {
initFields(promState.value);
return q();
if (prom.isFulfilled()) {
initFields(prom.value());
return Promise.resolve();
} else {
return prom.then(initFields);
}
} else {
const tl = this._timelineSet.getLiveTimeline();
initFields(tl);
return q();
return Promise.resolve();
}
};
@@ -235,7 +234,7 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
if (!tl) {
debuglog("TimelineWindow: no timeline yet");
return q(false);
return Promise.resolve(false);
}
if (tl.pendingPaginate) {
@@ -255,20 +254,20 @@ TimelineWindow.prototype.paginate = function(direction, size, makeRequest,
if (excess > 0) {
this.unpaginate(excess, direction != EventTimeline.BACKWARDS);
}
return q(true);
return Promise.resolve(true);
}
if (!makeRequest || requestLimit === 0) {
// todo: should we return something different to indicate that there
// might be more events out there, but we haven't found them yet?
return q(false);
return Promise.resolve(false);
}
// try making a pagination request
const token = tl.timeline.getPaginationToken(direction);
if (!token) {
debuglog("TimelineWindow: no token");
return q(false);
return Promise.resolve(false);
}
debuglog("TimelineWindow: starting request");