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

Merge pull request #1100 from matrix-org/t3chguy/remove_bluebird_13

Remove Bluebird: phase 2.5
This commit is contained in:
Michael Telatynski
2019-12-10 16:58:22 +00:00
committed by GitHub
55 changed files with 141 additions and 218 deletions

View File

@@ -3,11 +3,6 @@
"plugins": [
"transform-class-properties",
// this transforms async functions into generator functions, which
// are then made to use the regenerator module by babel's
// transform-regnerator plugin (which is enabled by es2015).
"transform-async-to-bluebird",
// This makes sure that the regenerator runtime is available to
// the transpiled code.
"transform-runtime",

View File

@@ -161,7 +161,7 @@ which will be fulfilled in the future.
The typical usage is something like:
```javascript
matrixClient.someMethod(arg1, arg2).done(function(result) {
matrixClient.someMethod(arg1, arg2).then(function(result) {
...
});
```
@@ -206,7 +206,7 @@ core functionality of the SDK. These examples assume the SDK is setup like this:
```javascript
matrixClient.on("RoomMember.membership", function(event, member) {
if (member.membership === "invite" && member.userId === myUserId) {
matrixClient.joinRoom(member.roomId).done(function() {
matrixClient.joinRoom(member.roomId).then(function() {
console.log("Auto-joined %s", member.roomId);
});
}

View File

@@ -56,7 +56,7 @@ rl.on('line', function(line) {
}
}
if (notSentEvent) {
matrixClient.resendEvent(notSentEvent, viewingRoom).done(function() {
matrixClient.resendEvent(notSentEvent, viewingRoom).then(function() {
printMessages();
rl.prompt();
}, function(err) {
@@ -70,7 +70,7 @@ rl.on('line', function(line) {
}
else if (line.indexOf("/more ") === 0) {
var amount = parseInt(line.split(" ")[1]) || 20;
matrixClient.scrollback(viewingRoom, amount).done(function(room) {
matrixClient.scrollback(viewingRoom, amount).then(function(room) {
printMessages();
rl.prompt();
}, function(err) {
@@ -79,7 +79,7 @@ rl.on('line', function(line) {
}
else if (line.indexOf("/invite ") === 0) {
var userId = line.split(" ")[1].trim();
matrixClient.invite(viewingRoom.roomId, userId).done(function() {
matrixClient.invite(viewingRoom.roomId, userId).then(function() {
printMessages();
rl.prompt();
}, function(err) {
@@ -92,7 +92,7 @@ rl.on('line', function(line) {
matrixClient.uploadContent({
stream: stream,
name: filename
}).done(function(url) {
}).then(function(url) {
var content = {
msgtype: "m.file",
body: filename,
@@ -116,7 +116,7 @@ rl.on('line', function(line) {
viewingRoom = roomList[roomIndex];
if (viewingRoom.getMember(myUserId).membership === "invite") {
// join the room first
matrixClient.joinRoom(viewingRoom.roomId).done(function(room) {
matrixClient.joinRoom(viewingRoom.roomId).then(function(room) {
setRoomList();
viewingRoom = room;
printMessages();

View File

@@ -50,7 +50,6 @@
"dependencies": {
"another-json": "^0.2.0",
"babel-runtime": "^6.26.0",
"bluebird": "3.5.5",
"browser-request": "^0.3.3",
"bs58": "^4.0.1",
"content-type": "^1.0.2",
@@ -63,7 +62,6 @@
"babel-cli": "^6.18.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.6.0",
"babel-plugin-transform-async-to-bluebird": "^1.1.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.18.0",

View File

@@ -24,7 +24,6 @@ import './olm-loader';
import sdk from '..';
import testUtils from './test-utils';
import MockHttpBackend from 'matrix-mock-request';
import Promise from 'bluebird';
import LocalStorageCryptoStore from '../lib/crypto/store/localStorage-crypto-store';
import logger from '../src/logger';

View File

@@ -15,8 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import TestClient from '../TestClient';
import testUtils from '../test-utils';
import logger from '../../src/logger';

View File

@@ -31,7 +31,6 @@ import 'source-map-support/register';
import '../olm-loader';
const sdk = require("../..");
import Promise from 'bluebird';
const utils = require("../../lib/utils");
const testUtils = require("../test-utils");
const TestClient = require('../TestClient').default;

View File

@@ -4,8 +4,6 @@ const sdk = require("../..");
const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
import Promise from 'bluebird';
describe("MatrixClient events", function() {
const baseUrl = "http://localhost.or.something";
let client;
@@ -162,7 +160,7 @@ describe("MatrixClient events", function() {
});
client.startClient();
httpBackend.flushAllExpected().done(function() {
httpBackend.flushAllExpected().then(function() {
expect(fired).toBe(true, "User.presence didn't fire.");
done();
});

View File

@@ -1,6 +1,5 @@
"use strict";
import 'source-map-support/register';
import Promise from 'bluebird';
const sdk = require("../..");
const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
@@ -356,7 +355,7 @@ describe("MatrixClient event timelines", function() {
.toEqual("start_token");
// expect(tl.getPaginationToken(EventTimeline.FORWARDS))
// .toEqual("s_5_4");
}).done(resolve, reject);
}).then(resolve, reject);
});
});

View File

@@ -181,7 +181,7 @@ describe("MatrixClient", function() {
event_format: "client",
});
store.storeFilter(filter);
client.getFilter(userId, filterId, true).done(function(gotFilter) {
client.getFilter(userId, filterId, true).then(function(gotFilter) {
expect(gotFilter).toEqual(filter);
done();
});
@@ -202,7 +202,7 @@ describe("MatrixClient", function() {
event_format: "client",
});
store.storeFilter(storeFilter);
client.getFilter(userId, filterId, false).done(function(gotFilter) {
client.getFilter(userId, filterId, false).then(function(gotFilter) {
expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition);
done();
});
@@ -220,7 +220,7 @@ describe("MatrixClient", function() {
httpBackend.when(
"GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId,
).respond(200, httpFilterDefinition);
client.getFilter(userId, filterId, true).done(function(gotFilter) {
client.getFilter(userId, filterId, true).then(function(gotFilter) {
expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition);
expect(store.getFilter(userId, filterId)).toBeTruthy();
done();
@@ -248,7 +248,7 @@ describe("MatrixClient", function() {
filter_id: filterId,
});
client.createFilter(filterDefinition).done(function(gotFilter) {
client.createFilter(filterDefinition).then(function(gotFilter) {
expect(gotFilter.getDefinition()).toEqual(filterDefinition);
expect(store.getFilter(userId, filterId)).toEqual(gotFilter);
done();
@@ -295,7 +295,7 @@ describe("MatrixClient", function() {
});
}).respond(200, response);
httpBackend.flush().done(function() {
httpBackend.flush().then(function() {
done();
});
});

View File

@@ -5,8 +5,6 @@ const MatrixClient = sdk.MatrixClient;
const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
import Promise from 'bluebird';
describe("MatrixClient opts", function() {
const baseUrl = "http://localhost.or.something";
let client = null;
@@ -86,7 +84,7 @@ describe("MatrixClient opts", function() {
httpBackend.when("PUT", "/txn1").respond(200, {
event_id: eventId,
});
client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) {
client.sendTextMessage("!foo:bar", "a body", "txn1").then(function(res) {
expect(res.event_id).toEqual(eventId);
done();
});
@@ -139,7 +137,7 @@ describe("MatrixClient opts", function() {
errcode: "M_SOMETHING",
error: "Ruh roh",
});
client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) {
client.sendTextMessage("!foo:bar", "a body", "txn1").then(function(res) {
expect(false).toBe(true, "sendTextMessage resolved but shouldn't");
}, function(err) {
expect(err.errcode).toEqual("M_SOMETHING");
@@ -157,16 +155,16 @@ describe("MatrixClient opts", function() {
});
let sentA = false;
let sentB = false;
client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) {
client.sendTextMessage("!foo:bar", "a body", "txn1").then(function(res) {
sentA = true;
expect(sentB).toBe(true);
});
client.sendTextMessage("!foo:bar", "b body", "txn2").done(function(res) {
client.sendTextMessage("!foo:bar", "b body", "txn2").then(function(res) {
sentB = true;
expect(sentA).toBe(false);
});
httpBackend.flush("/txn2", 1).done(function() {
httpBackend.flush("/txn1", 1).done(function() {
httpBackend.flush("/txn2", 1).then(function() {
httpBackend.flush("/txn1", 1).then(function() {
done();
});
});
@@ -176,7 +174,7 @@ describe("MatrixClient opts", function() {
httpBackend.when("PUT", "/txn1").respond(200, {
event_id: "foo",
});
client.sendTextMessage("!foo:bar", "a body", "txn1").done(function(res) {
client.sendTextMessage("!foo:bar", "a body", "txn1").then(function(res) {
expect(res.event_id).toEqual("foo");
done();
});

View File

@@ -1,6 +1,5 @@
"use strict";
import 'source-map-support/register';
import Promise from 'bluebird';
const sdk = require("../..");
const HttpBackend = require("matrix-mock-request");

View File

@@ -5,8 +5,6 @@ const EventStatus = sdk.EventStatus;
const HttpBackend = require("matrix-mock-request");
const utils = require("../test-utils");
import Promise from 'bluebird';
describe("MatrixClient room timelines", function() {
const baseUrl = "http://localhost.or.something";
let client = null;
@@ -151,7 +149,7 @@ describe("MatrixClient room timelines", function() {
expect(member.userId).toEqual(userId);
expect(member.name).toEqual(userName);
httpBackend.flush("/sync", 1).done(function() {
httpBackend.flush("/sync", 1).then(function() {
done();
});
});
@@ -177,10 +175,10 @@ describe("MatrixClient room timelines", function() {
return;
}
const room = client.getRoom(roomId);
client.sendTextMessage(roomId, "I am a fish", "txn1").done(
client.sendTextMessage(roomId, "I am a fish", "txn1").then(
function() {
expect(room.timeline[1].getId()).toEqual(eventId);
httpBackend.flush("/sync", 1).done(function() {
httpBackend.flush("/sync", 1).then(function() {
expect(room.timeline[1].getId()).toEqual(eventId);
done();
});
@@ -210,10 +208,10 @@ describe("MatrixClient room timelines", function() {
}
const room = client.getRoom(roomId);
const promise = client.sendTextMessage(roomId, "I am a fish", "txn1");
httpBackend.flush("/sync", 1).done(function() {
httpBackend.flush("/sync", 1).then(function() {
expect(room.timeline.length).toEqual(2);
httpBackend.flush("/txn1", 1);
promise.done(function() {
promise.then(function() {
expect(room.timeline.length).toEqual(2);
expect(room.timeline[1].getId()).toEqual(eventId);
done();
@@ -248,7 +246,7 @@ describe("MatrixClient room timelines", function() {
const room = client.getRoom(roomId);
expect(room.timeline.length).toEqual(1);
client.scrollback(room).done(function() {
client.scrollback(room).then(function() {
expect(room.timeline.length).toEqual(1);
expect(room.oldState.paginationToken).toBe(null);
@@ -312,7 +310,7 @@ describe("MatrixClient room timelines", function() {
// sync response
expect(room.timeline.length).toEqual(1);
client.scrollback(room).done(function() {
client.scrollback(room).then(function() {
expect(room.timeline.length).toEqual(5);
const joinMsg = room.timeline[0];
expect(joinMsg.sender.name).toEqual("Old Alice");
@@ -350,7 +348,7 @@ describe("MatrixClient room timelines", function() {
const room = client.getRoom(roomId);
expect(room.timeline.length).toEqual(1);
client.scrollback(room).done(function() {
client.scrollback(room).then(function() {
expect(room.timeline.length).toEqual(3);
expect(room.timeline[0].event).toEqual(sbEvents[1]);
expect(room.timeline[1].event).toEqual(sbEvents[0]);
@@ -381,11 +379,11 @@ describe("MatrixClient room timelines", function() {
const room = client.getRoom(roomId);
expect(room.oldState.paginationToken).toBeTruthy();
client.scrollback(room, 1).done(function() {
client.scrollback(room, 1).then(function() {
expect(room.oldState.paginationToken).toEqual(sbEndTok);
});
httpBackend.flush("/messages", 1).done(function() {
httpBackend.flush("/messages", 1).then(function() {
// still have a sync to flush
httpBackend.flush("/sync", 1).then(() => {
done();

View File

@@ -6,8 +6,6 @@ const utils = require("../test-utils");
const MatrixEvent = sdk.MatrixEvent;
const EventTimeline = sdk.EventTimeline;
import Promise from 'bluebird';
describe("MatrixClient syncing", function() {
const baseUrl = "http://localhost.or.something";
let client = null;
@@ -51,7 +49,7 @@ describe("MatrixClient syncing", function() {
client.startClient();
httpBackend.flushAllExpected().done(function() {
httpBackend.flushAllExpected().then(function() {
done();
});
});
@@ -65,7 +63,7 @@ describe("MatrixClient syncing", function() {
client.startClient();
httpBackend.flushAllExpected().done(function() {
httpBackend.flushAllExpected().then(function() {
done();
});
});

View File

@@ -17,7 +17,6 @@ limitations under the License.
"use strict";
const anotherjson = require('another-json');
import Promise from 'bluebird';
const utils = require('../../lib/utils');
const testUtils = require('../test-utils');

View File

@@ -1,6 +1,4 @@
"use strict";
import Promise from 'bluebird';
// load olm before the sdk if possible
import './olm-loader';
@@ -256,7 +254,7 @@ HttpResponse.prototype.request = function HttpResponse(
if (!next) { // no more things to return
if (method === "GET" && path === "/sync" && this.ignoreUnhandledSync) {
logger.log("MatrixClient[UT] Ignoring.");
return Promise.defer().promise;
return new Promise(() => {});
}
if (this.pendingLookup) {
if (this.pendingLookup.method === method
@@ -271,7 +269,7 @@ HttpResponse.prototype.request = function HttpResponse(
);
}
this.pendingLookup = {
promise: Promise.defer().promise,
promise: new Promise(() => {}),
method: method,
path: path,
};
@@ -308,10 +306,10 @@ HttpResponse.prototype.request = function HttpResponse(
} else if (method === "GET" && path === "/sync" && this.ignoreUnhandledSync) {
logger.log("MatrixClient[UT] Ignoring.");
this.httpLookups.unshift(next);
return Promise.defer().promise;
return new Promise(() => {});
}
expect(true).toBe(false, "Expected different request. " + logLine);
return Promise.defer().promise;
return new Promise(() => {});
};
HttpResponse.KEEP_ALIVE_PATH = "/_matrix/client/versions";

View File

@@ -16,7 +16,6 @@ limitations under the License.
"use strict";
import 'source-map-support/register';
import Promise from 'bluebird';
const sdk = require("../..");
const AutoDiscovery = sdk.AutoDiscovery;

View File

@@ -11,6 +11,7 @@ import TestClient from '../TestClient';
import {MatrixEvent} from '../../lib/models/event';
import Room from '../../lib/models/room';
import olmlib from '../../lib/crypto/olmlib';
import {sleep} from "../../src/utils";
const EventEmitter = require("events").EventEmitter;
@@ -18,8 +19,6 @@ const sdk = require("../..");
const Olm = global.Olm;
jest.useFakeTimers();
describe("Crypto", function() {
if (!sdk.CRYPTO_ENABLED) {
return;
@@ -270,7 +269,8 @@ describe("Crypto", function() {
await bobDecryptor.onRoomKeyEvent(ksEvent);
await eventPromise;
expect(events[0].getContent().msgtype).not.toBe("m.bad.encrypted");
// the room key request should be gone since we've now decypted everything
await sleep(1);
// the room key request should be gone since we've now decrypted everything
expect(await cryptoStore.getOutgoingRoomKeyRequest(roomKeyRequestBody))
.toBeFalsy();
},
@@ -301,6 +301,8 @@ describe("Crypto", function() {
});
it("uses a new txnid for re-requesting keys", async function() {
jest.useFakeTimers();
const event = new MatrixEvent({
sender: "@bob:example.com",
room_id: "!someroom",
@@ -310,52 +312,31 @@ describe("Crypto", function() {
sender_key: "senderkey",
},
});
/* return a promise and a function. When the function is called,
* the promise will be resolved.
*/
function awaitFunctionCall() {
let func;
const promise = new Promise((resolve, reject) => {
func = function(...args) {
resolve(args);
return new Promise((resolve, reject) => {
// give us some time to process the result before
// continuing
global.setTimeout(resolve, 1);
});
};
});
return {func, promise};
}
// replace Alice's sendToDevice function with a mock
aliceClient.sendToDevice = jest.fn().mockResolvedValue(undefined);
aliceClient.startClient();
let promise;
// make a room key request, and record the transaction ID for the
// sendToDevice call
({promise, func: aliceClient.sendToDevice} = awaitFunctionCall());
await aliceClient.cancelAndResendEventRoomKeyRequest(event);
jest.runAllTimers();
let args = await promise;
const txnId = args[2];
jest.runAllTimers();
await Promise.resolve();
expect(aliceClient.sendToDevice).toBeCalledTimes(1);
const txnId = aliceClient.sendToDevice.mock.calls[0][2];
// give the room key request manager time to update the state
// of the request
await Promise.resolve();
// cancel and resend the room key request
({promise, func: aliceClient.sendToDevice} = awaitFunctionCall());
await aliceClient.cancelAndResendEventRoomKeyRequest(event);
jest.runAllTimers();
await Promise.resolve();
// cancelAndResend will call sendToDevice twice:
// the first call to sendToDevice will be the cancellation
args = await promise;
// the second call to sendToDevice will be the key request
({promise, func: aliceClient.sendToDevice} = awaitFunctionCall());
jest.runAllTimers();
args = await promise;
jest.runAllTimers();
expect(args[2]).not.toBe(txnId);
expect(aliceClient.sendToDevice).toBeCalledTimes(3);
expect(aliceClient.sendToDevice.mock.calls[2][2]).not.toBe(txnId);
});
});
});

View File

@@ -20,8 +20,6 @@ import MemoryCryptoStore from '../../../lib/crypto/store/memory-crypto-store.js'
import utils from '../../../lib/utils';
import logger from '../../../src/logger';
import Promise from 'bluebird';
const signedDeviceList = {
"failures": {},
"device_keys": {
@@ -87,7 +85,7 @@ describe('DeviceList', function() {
dl.startTrackingDeviceList('@test1:sw1v.org');
const queryDefer1 = Promise.defer();
const queryDefer1 = utils.defer();
downloadSpy.mockReturnValue(queryDefer1.promise);
const prom1 = dl.refreshOutdatedDeviceLists();
@@ -106,7 +104,7 @@ describe('DeviceList', function() {
dl.startTrackingDeviceList('@test1:sw1v.org');
const queryDefer1 = Promise.defer();
const queryDefer1 = utils.defer();
downloadSpy.mockReturnValue(queryDefer1.promise);
const prom1 = dl.refreshOutdatedDeviceLists();
@@ -114,7 +112,7 @@ describe('DeviceList', function() {
downloadSpy.mockReset();
// outdated notif arrives while the request is in flight.
const queryDefer2 = Promise.defer();
const queryDefer2 = utils.defer();
downloadSpy.mockReturnValue(queryDefer2.promise);
dl.invalidateUserDeviceList('@test1:sw1v.org');
@@ -134,7 +132,7 @@ describe('DeviceList', function() {
logger.log("Creating new devicelist to simulate app reload");
downloadSpy.mockReset();
const dl2 = createTestDeviceList();
const queryDefer3 = Promise.defer();
const queryDefer3 = utils.defer();
downloadSpy.mockReturnValue(queryDefer3.promise);
const prom3 = dl2.refreshOutdatedDeviceLists();

View File

@@ -1,7 +1,5 @@
import '../../../olm-loader';
import Promise from 'bluebird';
import sdk from '../../../..';
import algorithms from '../../../../lib/crypto/algorithms';
import MemoryCryptoStore from '../../../../lib/crypto/store/memory-crypto-store.js';
@@ -56,7 +54,7 @@ describe("MegolmDecryption", function() {
mockOlmLib = {};
mockOlmLib.ensureOlmSessionsForDevices = jest.fn();
mockOlmLib.encryptMessageForDevice =
jest.fn().mockReturnValue(Promise.resolve());
jest.fn().mockResolvedValue(undefined);
megolmDecryption.olmlib = mockOlmLib;
});
@@ -136,11 +134,11 @@ describe("MegolmDecryption", function() {
const deviceInfo = {};
mockCrypto.getStoredDevice.mockReturnValue(deviceInfo);
mockOlmLib.ensureOlmSessionsForDevices.mockReturnValue(
Promise.resolve({'@alice:foo': {'alidevice': {
mockOlmLib.ensureOlmSessionsForDevices.mockResolvedValue({
'@alice:foo': {'alidevice': {
sessionId: 'alisession',
}}}),
);
}},
});
const awaitEncryptForDevice = new Promise((res, rej) => {
mockOlmLib.encryptMessageForDevice.mockImplementation(() => {
@@ -282,7 +280,7 @@ describe("MegolmDecryption", function() {
},
},
}));
mockBaseApis.sendToDevice = jest.fn().mockReturnValue(Promise.resolve());
mockBaseApis.sendToDevice = jest.fn().mockResolvedValue(undefined);
mockCrypto.downloadKeys.mockReturnValue(Promise.resolve({
'@alice:home.server': {

View File

@@ -16,8 +16,6 @@ limitations under the License.
import '../../olm-loader';
import Promise from 'bluebird';
import sdk from '../../..';
import algorithms from '../../../lib/crypto/algorithms';
import WebStorageSessionStore from '../../../lib/store/session/webstorage';
@@ -157,7 +155,7 @@ describe("MegolmBackup", function() {
mockOlmLib = {};
mockOlmLib.ensureOlmSessionsForDevices = jest.fn();
mockOlmLib.encryptMessageForDevice =
jest.fn().mockReturnValue(Promise.resolve());
jest.fn().mockResolvedValue(undefined);
});
describe("backup", function() {

View File

@@ -789,6 +789,9 @@ describe("Cross Signing", function() {
upgradeResolveFunc = resolve;
});
alice._crypto._deviceList.emit("userCrossSigningUpdated", "@bob:example.com");
await new Promise((resolve) => {
alice._crypto.on("userTrustStatusChanged", resolve);
});
await upgradePromise;
const bobTrust3 = alice.checkUserTrust("@bob:example.com");

View File

@@ -473,6 +473,12 @@ describe("SAS verification", function() {
}
});
});
afterEach(async function() {
await Promise.all([
alice.stop(),
bob.stop(),
]);
});
it("should verify a key", async function() {
await Promise.all([

View File

@@ -17,7 +17,6 @@ limitations under the License.
import sdk from '../..';
const MatrixEvent = sdk.MatrixEvent;
import Promise from 'bluebird';
import logger from '../../src/logger';
describe("MatrixEvent", () => {

View File

@@ -16,7 +16,6 @@ limitations under the License.
"use strict";
import 'source-map-support/register';
import Promise from 'bluebird';
const sdk = require("../..");
const InteractiveAuth = sdk.InteractiveAuth;

View File

@@ -1,6 +1,5 @@
"use strict";
import 'source-map-support/register';
import Promise from 'bluebird';
const sdk = require("../..");
const MatrixClient = sdk.MatrixClient;
@@ -83,7 +82,7 @@ describe("MatrixClient", function() {
);
}
pendingLookup = {
promise: Promise.defer().promise,
promise: new Promise(() => {}),
method: method,
path: path,
};
@@ -119,7 +118,7 @@ describe("MatrixClient", function() {
return Promise.resolve(next.data);
}
expect(true).toBe(false, "Expected different request. " + logLine);
return Promise.defer().promise;
return new Promise(() => {});
}
beforeEach(function() {
@@ -171,7 +170,7 @@ describe("MatrixClient", function() {
// a DIFFERENT test (pollution between tests!) - we return unresolved
// promises to stop the client from continuing to run.
client._http.authedRequest.mockImplementation(function() {
return Promise.defer().promise;
return new Promise(() => {});
});
});

View File

@@ -2,7 +2,7 @@
/* eslint new-cap: "off" */
import 'source-map-support/register';
import Promise from 'bluebird';
import {defer} from '../../src/utils';
const sdk = require("../..");
const MatrixScheduler = sdk.MatrixScheduler;
const MatrixError = sdk.MatrixError;
@@ -14,7 +14,7 @@ describe("MatrixScheduler", function() {
let scheduler;
let retryFn;
let queueFn;
let defer;
let deferred;
const roomId = "!foo:bar";
const eventA = utils.mkMessage({
user: "@alice:bar", room: roomId, event: true,
@@ -37,7 +37,7 @@ describe("MatrixScheduler", function() {
});
retryFn = null;
queueFn = null;
defer = Promise.defer();
deferred = defer();
});
it("should process events in a queue in a FIFO manner", async function() {
@@ -47,8 +47,8 @@ describe("MatrixScheduler", function() {
queueFn = function() {
return "one_big_queue";
};
const deferA = Promise.defer();
const deferB = Promise.defer();
const deferA = defer();
const deferB = defer();
let yieldedA = false;
scheduler.setProcessFunction(function(event) {
if (yieldedA) {
@@ -74,7 +74,7 @@ describe("MatrixScheduler", function() {
it("should invoke the retryFn on failure and wait the amount of time specified",
async function() {
const waitTimeMs = 1500;
const retryDefer = Promise.defer();
const retryDefer = defer();
retryFn = function() {
retryDefer.resolve();
return waitTimeMs;
@@ -88,9 +88,9 @@ describe("MatrixScheduler", function() {
procCount += 1;
if (procCount === 1) {
expect(ev).toEqual(eventA);
return defer.promise;
return deferred.promise;
} else if (procCount === 2) {
// don't care about this defer
// don't care about this deferred
return new Promise();
}
expect(procCount).toBeLessThan(3);
@@ -101,7 +101,7 @@ describe("MatrixScheduler", function() {
// wait just long enough before it does
await Promise.resolve();
expect(procCount).toEqual(1);
defer.reject({});
deferred.reject({});
await retryDefer.promise;
expect(procCount).toEqual(1);
jest.advanceTimersByTime(waitTimeMs);
@@ -121,8 +121,8 @@ describe("MatrixScheduler", function() {
return "yep";
};
const deferA = Promise.defer();
const deferB = Promise.defer();
const deferA = defer();
const deferB = defer();
let procCount = 0;
scheduler.setProcessFunction(function(ev) {
procCount += 1;
@@ -177,14 +177,14 @@ describe("MatrixScheduler", function() {
const expectOrder = [
eventA.getId(), eventB.getId(), eventD.getId(),
];
const deferA = Promise.defer();
const deferA = defer();
scheduler.setProcessFunction(function(event) {
const id = expectOrder.shift();
expect(id).toEqual(event.getId());
if (expectOrder.length === 0) {
done();
}
return id === eventA.getId() ? deferA.promise : defer.promise;
return id === eventA.getId() ? deferA.promise : deferred.promise;
});
scheduler.queueEvent(eventA);
scheduler.queueEvent(eventB);
@@ -298,7 +298,7 @@ describe("MatrixScheduler", function() {
scheduler.setProcessFunction(function(ev) {
procCount += 1;
expect(ev).toEqual(eventA);
return defer.promise;
return deferred.promise;
});
// as queueing doesn't start processing synchronously anymore (see commit bbdb5ac)
// wait just long enough before it does
@@ -314,7 +314,7 @@ describe("MatrixScheduler", function() {
let procCount = 0;
scheduler.setProcessFunction(function(ev) {
procCount += 1;
return defer.promise;
return deferred.promise;
});
expect(procCount).toEqual(0);
});

View File

@@ -1,6 +1,5 @@
"use strict";
import 'source-map-support/register';
import Promise from 'bluebird';
const sdk = require("../..");
const EventTimeline = sdk.EventTimeline;
const TimelineWindow = sdk.TimelineWindow;

View File

@@ -17,7 +17,6 @@ limitations under the License.
/** @module auto-discovery */
import Promise from 'bluebird';
import logger from './logger';
import { URL as NodeURL } from "url";

View File

@@ -26,7 +26,6 @@ import {sleep} from './utils';
* @module client
*/
const EventEmitter = require("events").EventEmitter;
import Promise from 'bluebird';
const url = require('url');
const httpApi = require("./http-api");
@@ -55,11 +54,6 @@ import { encodeRecoveryKey, decodeRecoveryKey } from './crypto/recoverykey';
import { keyFromPassphrase, keyFromAuthData } from './crypto/key_passphrase';
import { randomString } from './randomstring';
// Disable warnings for now: we use deprecated bluebird functions
// and need to migrate, but they spam the console with warnings.
Promise.config({warnings: false});
const SCROLLBACK_DELAY_MS = 3000;
const CRYPTO_ENABLED = isCryptoAvailable();
const CAPABILITIES_CACHE_MS = 21600000; // 6 hours - an arbitrary value
@@ -1892,7 +1886,7 @@ MatrixClient.prototype.joinRoom = function(roomIdOrAlias, opts, callback) {
// return syncApi.syncRoom(room);
}
return Promise.resolve(room);
}).done(function(room) {
}).then(function(room) {
_resolve(callback, resolve, room);
}, function(err) {
_reject(callback, reject, err);
@@ -3224,7 +3218,7 @@ MatrixClient.prototype.scrollback = function(room, limit, callback) {
room.oldState.paginationToken,
limit,
'b');
}).done(function(res) {
}).then(function(res) {
const matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self));
if (res.state) {
const stateEvents = utils.map(res.state, _PojoToMatrixEventMapper(self));
@@ -3872,10 +3866,10 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
// This is a workaround to SYN-590 (Push rule update fails)
deferred = utils.defer();
this.deletePushRule(scope, "room", roomPushRule.rule_id)
.done(function() {
.then(function() {
self.addPushRule(scope, "room", roomId, {
actions: ["dont_notify"],
}).done(function() {
}).then(function() {
deferred.resolve();
}, function(err) {
deferred.reject(err);
@@ -3891,8 +3885,8 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
if (deferred) {
return new Promise((resolve, reject) => {
// Update this.pushRules when the operation completes
deferred.done(function() {
self.getPushRules().done(function(result) {
deferred.then(function() {
self.getPushRules().then(function(result) {
self.pushRules = result;
resolve();
}, function(err) {
@@ -3901,7 +3895,7 @@ MatrixClient.prototype.setRoomMutePushRule = function(scope, roomId, mute) {
}, function(err) {
// Update it even if the previous operation fails. This can help the
// app to recover when push settings has been modifed from another client
self.getPushRules().done(function(result) {
self.getPushRules().then(function(result) {
self.pushRules = result;
reject(err);
}, function(err2) {
@@ -4395,7 +4389,7 @@ MatrixClient.prototype.startClient = async function(opts) {
}
if (this._crypto) {
this._crypto.uploadDeviceKeys().done();
this._crypto.uploadDeviceKeys();
this._crypto.start();
}
@@ -4854,7 +4848,7 @@ function checkTurnServers(client) {
return; // guests can't access TURN servers
}
client.turnServer().done(function(res) {
client.turnServer().then(function(res) {
if (res.uris) {
logger.log("Got TURN URIs: " + res.uris + " refresh in " +
res.ttl + " secs");
@@ -5354,5 +5348,4 @@ module.exports.CRYPTO_ENABLED = CRYPTO_ENABLED;
* @property {Function} then promise.then(onFulfilled, onRejected, onProgress)
* @property {Function} catch promise.catch(onRejected)
* @property {Function} finally promise.finally(callback)
* @property {Function} done promise.done(onFulfilled, onRejected, onProgress)
*/

View File

@@ -23,7 +23,6 @@ limitations under the License.
* Manages the list of other users' devices
*/
import Promise from 'bluebird';
import {EventEmitter} from 'events';
import logger from '../logger';
@@ -31,7 +30,7 @@ import DeviceInfo from './deviceinfo';
import {CrossSigningInfo} from './CrossSigning';
import olmlib from './olmlib';
import IndexedDBCryptoStore from './store/indexeddb-crypto-store';
import {sleep} from '../utils';
import {defer, sleep} from '../utils';
/* State transition diagram for DeviceList._deviceTrackingStatus
@@ -712,7 +711,7 @@ class DeviceListUpdateSerialiser {
});
if (!this._queuedQueryDeferred) {
this._queuedQueryDeferred = Promise.defer();
this._queuedQueryDeferred = defer();
}
// We always take the new sync token and just use the latest one we've
@@ -777,7 +776,7 @@ class DeviceListUpdateSerialiser {
}
return prom;
}).done(() => {
}).then(() => {
logger.log('Completed key download for ' + downloadUsers);
this._downloadInProgress = false;

View File

@@ -14,8 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import logger from '../logger';
import utils from '../utils';

View File

@@ -20,8 +20,6 @@ limitations under the License.
* @module
*/
import Promise from 'bluebird';
/**
* map of registered encryption algorithm classes. A map from string to {@link
* module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm} class

View File

@@ -22,7 +22,6 @@ limitations under the License.
* @module crypto/algorithms/megolm
*/
import Promise from 'bluebird';
import logger from '../../logger';
const utils = require("../../utils");
@@ -508,7 +507,7 @@ MegolmEncryption.prototype.reshareKeyWithDevice = async function(
userId,
device,
payload,
),
);
await this._baseApis.sendToDevice("m.room.encrypted", {
[userId]: {
@@ -1036,7 +1035,7 @@ MegolmDecryption.prototype.shareKeysWithDevice = function(keyRequest) {
// TODO: retries
return this._baseApis.sendToDevice("m.room.encrypted", contentMap);
});
}).done();
});
};
MegolmDecryption.prototype._buildKeyForwardingMessage = async function(

View File

@@ -20,15 +20,12 @@ limitations under the License.
*
* @module crypto/algorithms/olm
*/
import Promise from 'bluebird';
import logger from '../../logger';
const utils = require("../../utils");
const olmlib = require("../olmlib");
const DeviceInfo = require("../deviceinfo");
const DeviceVerification = DeviceInfo.DeviceVerification;
const base = require("./base");
/**

View File

@@ -23,7 +23,6 @@ limitations under the License.
*/
const anotherjson = require('another-json');
import Promise from 'bluebird';
import {EventEmitter} from 'events';
import ReEmitter from '../ReEmitter';
@@ -1088,7 +1087,7 @@ function _maybeUploadOneTimeKeys(crypto) {
// it will be set again on the next /sync-response
crypto._oneTimeKeyCount = undefined;
crypto._oneTimeKeyCheckInProgress = false;
}).done();
});
}
// returns a promise which resolves to the response
@@ -1998,7 +1997,7 @@ Crypto.prototype.requestRoomKey = function(requestBody, recipients, resend=false
logger.error(
'Error requesting key for event', e,
);
}).done();
});
};
/**
@@ -2011,7 +2010,7 @@ Crypto.prototype.cancelRoomKeyRequest = function(requestBody) {
this._outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody)
.catch((e) => {
logger.warn("Error clearing pending room key requests", e);
}).done();
});
};
/**

View File

@@ -21,7 +21,6 @@ limitations under the License.
* Utilities common to olm encryption algorithms
*/
import Promise from 'bluebird';
const anotherjson = require('another-json');
import logger from '../logger';

View File

@@ -15,8 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import logger from '../../logger';
import utils from '../../utils';

View File

@@ -15,8 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import logger from '../../logger';
import LocalStorageCryptoStore from './localStorage-crypto-store';
import MemoryCryptoStore from './memory-crypto-store';

View File

@@ -14,8 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import logger from '../../logger';
import MemoryCryptoStore from './memory-crypto-store';

View File

@@ -15,8 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import logger from '../../logger';
import utils from '../../utils';
@@ -69,7 +67,7 @@ export default class MemoryCryptoStore {
getOrAddOutgoingRoomKeyRequest(request) {
const requestBody = request.requestBody;
return Promise.try(() => {
return utils.promiseTry(() => {
// first see if we already have an entry for this request.
const existing = this._getOutgoingRoomKeyRequest(requestBody);

View File

@@ -19,7 +19,6 @@ limitations under the License.
* This is an internal module. See {@link MatrixHttpApi} for the public class.
* @module http-api
*/
import Promise from 'bluebird';
const parseContentType = require('content-type').parse;
const utils = require("./utils");
@@ -256,7 +255,7 @@ module.exports.MatrixHttpApi.prototype = {
}
if (global.XMLHttpRequest) {
const defer = Promise.defer();
const defer = utils.defer();
const xhr = new global.XMLHttpRequest();
upload.xhr = xhr;
const cb = requestCallback(defer, opts.callback, this.opts.onlyData);
@@ -418,7 +417,7 @@ module.exports.MatrixHttpApi.prototype = {
opts.headers['Authorization'] = `Bearer ${accessToken}`;
}
const defer = Promise.defer();
const defer = utils.defer();
this.opts.request(
opts,
requestCallback(defer, callback, this.opts.onlyData),
@@ -682,7 +681,7 @@ module.exports.MatrixHttpApi.prototype = {
}
}
const defer = Promise.defer();
const defer = utils.defer();
let timeoutId;
let timedOut = false;

View File

@@ -14,8 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
/**
* Check if an IndexedDB database exists. The only way to do so is to try opening it, so
* we do that and then delete it did not exist before.

View File

@@ -18,7 +18,6 @@ limitations under the License.
"use strict";
/** @module interactive-auth */
import Promise from 'bluebird';
const url = require("url");
const utils = require("./utils");

View File

@@ -21,7 +21,6 @@ limitations under the License.
* @module models/event
*/
import Promise from 'bluebird';
import {EventEmitter} from 'events';
import utils from '../utils.js';
import logger from '../logger';

View File

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

View File

@@ -15,7 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import SyncAccumulator from "../sync-accumulator";
import utils from "../utils";
import * as IndexedDBHelpers from "../indexeddb-helpers";
@@ -436,7 +435,7 @@ LocalIndexedDBStoreBackend.prototype = {
*/
_persistSyncData: function(nextBatch, roomsData, groupsData) {
logger.log("Persisting sync data up to ", nextBatch);
return Promise.try(() => {
return utils.promiseTry(() => {
const txn = this.db.transaction(["sync"], "readwrite");
const store = txn.objectStore("sync");
store.put({
@@ -456,7 +455,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves if the events were persisted.
*/
_persistAccountData: function(accountData) {
return Promise.try(() => {
return utils.promiseTry(() => {
const txn = this.db.transaction(["accountData"], "readwrite");
const store = txn.objectStore("accountData");
for (let i = 0; i < accountData.length; i++) {
@@ -475,7 +474,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise} Resolves if the users were persisted.
*/
_persistUserPresenceEvents: function(tuples) {
return Promise.try(() => {
return utils.promiseTry(() => {
const txn = this.db.transaction(["users"], "readwrite");
const store = txn.objectStore("users");
for (const tuple of tuples) {
@@ -495,7 +494,7 @@ LocalIndexedDBStoreBackend.prototype = {
* @return {Promise<Object[]>} A list of presence events in their raw form.
*/
getUserPresenceEvents: function() {
return Promise.try(() => {
return utils.promiseTry(() => {
const txn = this.db.transaction(["users"], "readonly");
const store = txn.objectStore("users");
return selectQuery(store, undefined, (cursor) => {
@@ -512,7 +511,7 @@ LocalIndexedDBStoreBackend.prototype = {
logger.log(
`LocalIndexedDBStoreBackend: loading account data...`,
);
return Promise.try(() => {
return utils.promiseTry(() => {
const txn = this.db.transaction(["accountData"], "readonly");
const store = txn.objectStore("accountData");
return selectQuery(store, undefined, (cursor) => {
@@ -534,7 +533,7 @@ LocalIndexedDBStoreBackend.prototype = {
logger.log(
`LocalIndexedDBStoreBackend: loading sync data...`,
);
return Promise.try(() => {
return utils.promiseTry(() => {
const txn = this.db.transaction(["sync"], "readonly");
const store = txn.objectStore("sync");
return selectQuery(store, undefined, (cursor) => {

View File

@@ -15,7 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import logger from '../logger';
import {defer} from '../utils';

View File

@@ -15,7 +15,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import Promise from 'bluebird';
import LocalIndexedDBStoreBackend from "./indexeddb-local-backend.js";
import logger from '../logger';
@@ -123,7 +122,7 @@ class IndexedDBStoreWorker {
return;
}
prom.done((ret) => {
prom.then((ret) => {
this.postMessage.call(null, {
command: 'cmd_success',
seq: msg.seq,

View File

@@ -17,7 +17,6 @@ limitations under the License.
/* eslint-disable babel/no-invalid-this */
import Promise from 'bluebird';
import {MemoryStore} from "./memory";
import utils from "../utils";
import {EventEmitter} from 'events';

View File

@@ -22,7 +22,6 @@ limitations under the License.
*/
const utils = require("../utils");
const User = require("../models/user");
import Promise from 'bluebird';
/**
* Construct a new in-memory data store for the Matrix Client.

View File

@@ -16,7 +16,6 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
import Promise from 'bluebird';
/**
* This is an internal module.
* @module store/stub

View File

@@ -25,7 +25,6 @@ limitations under the License.
* an alternative syncing API, we may want to have a proper syncing interface
* for HTTP and WS at some point.
*/
import Promise from 'bluebird';
const User = require("./models/user");
const Room = require("./models/room");
const Group = require('./models/group');
@@ -360,7 +359,7 @@ SyncApi.prototype._peekPoll = function(peekRoom, token) {
room_id: peekRoom.roomId,
timeout: 30 * 1000,
from: token,
}, undefined, 50 * 1000).done(function(res) {
}, undefined, 50 * 1000).then(function(res) {
if (self._peekRoomId !== peekRoom.roomId) {
debuglog("Stopped peeking in room %s", peekRoom.roomId);
return;
@@ -1150,7 +1149,7 @@ SyncApi.prototype._processSyncResponse = async function(
});
// Handle joins
await Promise.mapSeries(joinRooms, async function(joinObj) {
await utils.promiseMapSeries(joinRooms, async function(joinObj) {
const room = joinObj.room;
const stateEvents = self._mapSyncEventsFormat(joinObj.state, room);
const timelineEvents = self._mapSyncEventsFormat(joinObj.timeline, room);
@@ -1278,8 +1277,8 @@ SyncApi.prototype._processSyncResponse = async function(
}
}
await Promise.mapSeries(stateEvents, processRoomEvent);
await Promise.mapSeries(timelineEvents, processRoomEvent);
await utils.promiseMapSeries(stateEvents, processRoomEvent);
await utils.promiseMapSeries(timelineEvents, processRoomEvent);
ephemeralEvents.forEach(function(e) {
client.emit("event", e);
});
@@ -1383,7 +1382,7 @@ SyncApi.prototype._startKeepAlives = function(delay) {
self._pokeKeepAlive();
}
if (!this._connectionReturnedDefer) {
this._connectionReturnedDefer = Promise.defer();
this._connectionReturnedDefer = utils.defer();
}
return this._connectionReturnedDefer.promise;
};
@@ -1417,7 +1416,7 @@ SyncApi.prototype._pokeKeepAlive = function(connDidFail) {
prefix: '',
localTimeoutMs: 15 * 1000,
},
).done(function() {
).then(function() {
success();
}, function(err) {
if (err.httpStatus == 400 || err.httpStatus == 404) {
@@ -1541,7 +1540,7 @@ SyncApi.prototype._resolveInvites = function(room) {
} else {
promise = client.getProfileInfo(member.userId);
}
promise.done(function(info) {
promise.then(function(info) {
// slightly naughty by doctoring the invite event but this means all
// the code paths remain the same between invite/join display name stuff
// which is a worthy trade-off for some minor pollution.

View File

@@ -17,7 +17,6 @@ limitations under the License.
/** @module timeline-window */
import Promise from 'bluebird';
const EventTimeline = require("./models/event-timeline");
import logger from './logger';

View File

@@ -21,7 +21,6 @@ limitations under the License.
*/
const unhomoglyph = require('unhomoglyph');
import Promise from 'bluebird';
/**
* Encode a dictionary of query parameters.
@@ -731,3 +730,13 @@ module.exports.defer = () => {
return {resolve, reject, promise};
};
module.exports.promiseMapSeries = async (promises, fn) => {
for (const o of await promises) {
await fn(await o);
}
};
module.exports.promiseTry = (fn) => {
return new Promise((resolve) => resolve(fn()));
};