Browse Source

Switch promises from q to bluebird

tags/0.1.1
Daniel Wagner-Hall 4 years ago
committed by review.rocks
parent
commit
3fd3ab5a75
33 changed files with 307 additions and 261 deletions
  1. +2
    -0
      .gitignore
  2. +14
    -14
      lib/bridge/irc-to-matrix.js
  3. +7
    -6
      lib/bridge/matrix-to-irc.js
  4. +7
    -6
      lib/bridge/membershiplists.js
  5. +0
    -44
      lib/hot-reload.js
  6. +2
    -2
      lib/irc-appservice.js
  7. +3
    -3
      lib/irclib/client-connection.js
  8. +12
    -8
      lib/irclib/client-events.js
  9. +29
    -26
      lib/irclib/client.js
  10. +11
    -10
      lib/irclib/irc.js
  11. +4
    -4
      lib/irclib/names.js
  12. +4
    -3
      lib/models/requests.js
  13. +14
    -13
      lib/mxlib/matrix.js
  14. +23
    -0
      lib/promiseutil.js
  15. +26
    -25
      lib/store.js
  16. +1
    -1
      package.json
  17. +8
    -8
      spec/integ/admin-rooms.spec.js
  18. +12
    -12
      spec/integ/dynamic-channels.spec.js
  19. +3
    -3
      spec/integ/hs-queries.spec.js
  20. +5
    -5
      spec/integ/invite-rooms.spec.js
  21. +8
    -8
      spec/integ/irc-connections.spec.js
  22. +5
    -5
      spec/integ/irc-modes.spec.js
  23. +7
    -7
      spec/integ/irc-to-matrix.spec.js
  24. +3
    -3
      spec/integ/mirroring.spec.js
  25. +23
    -22
      spec/integ/pm.spec.js
  26. +4
    -4
      spec/unit/names.spec.js
  27. +42
    -0
      spec/unit/promiseutil.spec.js
  28. +2
    -2
      spec/util/asapi-controller-mock.js
  29. +4
    -4
      spec/util/client-sdk-mock.js
  30. +5
    -4
      spec/util/db-helper.js
  31. +5
    -4
      spec/util/irc-client-mock.js
  32. +7
    -0
      spec/util/test.js
  33. +5
    -5
      unbridge.js

+ 2
- 0
.gitignore View File

@@ -2,6 +2,8 @@ config.yaml
data
appservice-registration-irc.yaml
spec-db
.idea/*
.*.swp

# Logs
logs


+ 14
- 14
lib/bridge/irc-to-matrix.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var Promise = require("bluebird");

var matrixLib = require("../mxlib/matrix");
var store = require("../store");
@@ -24,23 +24,23 @@ var log = logging.get("irc-to-matrix");
*/
module.exports.onPrivateMessage = function(server, fromUser, toUser, action) {
if (fromUser.isVirtual) {
return q.reject(requests.ERR_VIRTUAL_USER);
return Promise.reject(new Error(requests.ERR_VIRTUAL_USER));
}

if (!toUser.isVirtual) {
log.error("Cannot route PM to %s", toUser);
return q.reject();
return Promise.reject();
}
var bridgedIrcClient = pool.getBridgedClientByNick(
toUser.server, toUser.nick
);
if (!bridgedIrcClient) {
log.error("Cannot route PM to %s - no client", toUser);
return q.reject();
return Promise.reject();
}
if (bridgedIrcClient.isBot) {
log.debug("Ignoring PM directed to the bot from %s", fromUser);
return q.reject();
return Promise.reject();
}

/* type {Request} */
@@ -120,7 +120,7 @@ module.exports.onPrivateMessage = function(server, fromUser, toUser, action) {
*/
module.exports.onMessage = function(server, fromUser, channel, action) {
if (fromUser.isVirtual) {
return q.reject(requests.ERR_VIRTUAL_USER);
return Promise.reject(new Error(requests.ERR_VIRTUAL_USER));
}

/* type {Request} */
@@ -163,7 +163,7 @@ module.exports.onMessage = function(server, fromUser, channel, action) {
channel
);
}
q.all(promises).done(req.sucFn, req.errFn);
Promise.all(promises).done(req.sucFn, req.errFn);
}).catch(req.errFn);
}).catch(req.errFn);
return req.defer.promise;
@@ -183,7 +183,7 @@ module.exports.onJoin = function(server, joiningUser, chan, kind) {
var syncType = kind === "names" ? "initial" : "incremental";
if (!server.shouldSyncMembershipToMatrix(syncType, chan)) {
log.info("IRC onJoin(%s) %s to %s - not syncing.", kind, nick, chan);
return q.reject("Server doesn't mirror joins.");
return Promise.reject("Server doesn't mirror joins.");
}
/* type {Request} */
var req = requests.newRequest(true);
@@ -191,7 +191,7 @@ module.exports.onJoin = function(server, joiningUser, chan, kind) {
req.log.info("onJoin(%s) %s to %s", kind, nick, chan);
// if the person joining is a virtual IRC user, do nothing.
if (joiningUser.isVirtual) {
req.defer.reject(requests.ERR_VIRTUAL_USER);
req.defer.reject(new Error(requests.ERR_VIRTUAL_USER));
return req.defer.promise; // don't send stuff which were sent from bots
}
// get virtual matrix user
@@ -217,7 +217,7 @@ module.exports.onJoin = function(server, joiningUser, chan, kind) {
"No mapped matrix rooms for IRC channel %s", chan
);
}
q.all(promises).done(req.sucFn, req.errFn);
Promise.all(promises).done(req.sucFn, req.errFn);
}).catch(req.errFn);

return req.defer.promise;
@@ -235,7 +235,7 @@ module.exports.onJoin = function(server, joiningUser, chan, kind) {
module.exports.onPart = function(server, leavingUser, chan, kind) {
// parts are always incremental (only NAMES are initial)
if (!server.shouldSyncMembershipToMatrix("incremental", chan)) {
return q.reject("Server doesn't mirror parts.");
return Promise.reject("Server doesn't mirror parts.");
}
/* type {Request} */
var req = requests.newRequest(true);
@@ -243,7 +243,7 @@ module.exports.onPart = function(server, leavingUser, chan, kind) {
req.log.info("onPart(%s) %s to %s", kind, nick, chan);
// if the person leaving is a virtual IRC user, do nothing.
if (leavingUser.isVirtual) {
req.defer.reject(requests.ERR_VIRTUAL_USER);
req.defer.reject(new Error(requests.ERR_VIRTUAL_USER));
return req.defer.promise;
}
// get virtual matrix user
@@ -269,7 +269,7 @@ module.exports.onPart = function(server, leavingUser, chan, kind) {
"No mapped matrix rooms for IRC channel %s", chan
);
}
q.all(promises).done(req.sucFn, req.errFn);
Promise.all(promises).done(req.sucFn, req.errFn);
}).catch(req.errFn);

return req.defer.promise;
@@ -325,7 +325,7 @@ module.exports.onMode = function(server, channel, by, mode, enabled, arg) {
"No mapped matrix rooms for IRC channel %s", channel
);
}
q.all(promises).done(req.sucFn, req.errFn);
Promise.all(promises).done(req.sucFn, req.errFn);
}).catch(req.errFn);
}



+ 7
- 6
lib/bridge/matrix-to-irc.js View File

@@ -1,6 +1,7 @@
"use strict";

var q = require("q");
var promiseutil = require("../promiseutil");

var matrixLib = require("../mxlib/matrix");
var ircLib = require("../irclib/irc");
@@ -20,7 +21,7 @@ var logging = require("../logging");
var log = logging.get("matrix-to-irc");

var createMatrixUserForIrcUser = function(ircUser, req) {
var defer = q.defer();
var defer = promiseutil.defer();

/* TODO: Uncomment this when Synapse 0.9.3 comes out (fixes onUserQuery bug)
req.ircLib.checkNickExists(ircUser.server, ircUser.nick).then(function(info) {
@@ -208,7 +209,7 @@ var onAdminMessage = function(event, req, adminRoom) {

if (ircServer.claimsUserId(event.user_id)) {
req.log.error("%s is a virtual user!", event.user_id);
req.defer.reject(requests.ERR_VIRTUAL_USER);
req.defer.reject(new Error(requests.ERR_VIRTUAL_USER));
return req.defer.promise;
}

@@ -319,7 +320,7 @@ module.exports.onInvite = function(event, inviter, invitee) {
processingInvitesForRooms[
event.room_id + event.state_key
] = req.defer.promise;
req.defer.promise.fin(function() {
req.defer.promise.finally(function() {
processingInvitesForRooms[event.room_id + event.state_key] = undefined;
});

@@ -362,7 +363,7 @@ module.exports.onJoin = function(event, user) {

if (matrixLib.getAppServiceUserId() === user.userId) {
// ignore messages from the bot
req.defer.reject(requests.ERR_VIRTUAL_USER);
req.defer.reject(new Error(requests.ERR_VIRTUAL_USER));
return req.defer.promise;
}

@@ -421,7 +422,7 @@ module.exports.onLeave = function(event, user) {

if (matrixLib.getAppServiceUserId() === user.userId) {
// ignore messages from the bot
req.defer.reject(requests.ERR_VIRTUAL_USER);
req.defer.reject(new Error(requests.ERR_VIRTUAL_USER));
return req.defer.promise;
}

@@ -499,7 +500,7 @@ module.exports.onMessage = function(event, existingRequest) {

if (matrixLib.getAppServiceUserId() === event.user_id) {
// ignore messages from the bot
req.defer.reject(requests.ERR_VIRTUAL_USER);
req.defer.reject(new Error(requests.ERR_VIRTUAL_USER));
return req.defer.promise;
}



+ 7
- 6
lib/bridge/membershiplists.js View File

@@ -2,7 +2,8 @@
// handles the sequence of events until the lists are in sync.
"use strict";

var q = require("q");
var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var matrixToIrc = require("./matrix-to-irc.js");
var ircLib = require("../irclib/irc.js");
var matrixLib = require("../mxlib/matrix");
@@ -45,7 +46,7 @@ module.exports.sync = function(server) {

module.exports.getChannelsToJoin = function(server) {
log.debug("getChannelsToJoin => %s", server.domain);
var defer = q.defer();
var defer = promiseutil.defer();
// map room IDs to channels on this server.
getSyncableRooms(server).then(function(rooms) {
var promises = [];
@@ -68,7 +69,7 @@ module.exports.getChannelsToJoin = function(server) {
});
}));
});
q.allSettled(promises).then(function() {
promiseutil.allSettled(promises).then(function() {
var chans = Object.keys(channels);
log.debug(
"getChannelsToJoin => %s should be synced: %s",
@@ -141,7 +142,7 @@ module.exports.checkBotPartRoom = function(ircRoom, req) {
// grab all rooms the bot knows about which have at least 1 real user in them.
function getSyncableRooms(server) {
var mxLib = matrixLib.getMatrixLibFor();
var defer = q.defer();
var defer = promiseutil.defer();
// hit /initialSync on the bot to pull in room state for all rooms.
mxLib.initialSync().done(function(res) {
var rooms = res.rooms || [];
@@ -159,7 +160,7 @@ function getSyncableRooms(server) {
}

function joinMatrixUsersToChannels(rooms, server) {
var d = q.defer();
var d = promiseutil.defer();

// filter out rooms listed in the rules
var filteredRooms = [];
@@ -227,7 +228,7 @@ function joinMatrixUsersToChannels(rooms, server) {
}

function leaveIrcUsersFromRooms(rooms, server) {
return q();
return Promise.resolve();
}

function getRoomMemberData(server, roomId, stateEvents) {


+ 0
- 44
lib/hot-reload.js View File

@@ -1,44 +0,0 @@
/**
"use strict";
var PID_FILENAME = "ircas.pid";
var fs = require("fs");
var q = require("q");
var logging = require("./logging");
var Validator = require("./config/validator");
var log = logging.get("hotreload");

var reloading = false;

var reloadConfig = function() {
log.info("Reloading config file....");
var config;
try {
var configValidator = new Validator(Validator.getFileLocation());
config = configValidator.validate();
}
catch (e) {
log.error("Failed to load config file: " + e);
return q.reject();
}
log.info("Loaded config file.");
return q();
};
*/

module.exports.setup = function() { /*
// write out the pid file
fs.writeFileSync(PID_FILENAME, "" + process.pid);

// SIGUSR1 is reserved by node for debugging
process.on("SIGUSR2", function() {
log.info("SIGUSR2 received.");

if (!reloading) {
log.info(" @@@@@@@@@@ HOT RELOAD @@@@@@@@@@ ");
reloading = true;
reloadConfig().finally(function() {
reloading = false;
});
}
}); */
};

+ 2
- 2
lib/irc-appservice.js View File

@@ -5,7 +5,7 @@

module.exports.serviceName = "matrix-appservice-irc";

var q = require("q");
var promiseutil = require("./promiseutil");

var matrixToIrc = require("./bridge/matrix-to-irc.js");
var ircToMatrix = require("./bridge/irc-to-matrix.js");
@@ -86,7 +86,7 @@ module.exports.register = function(controller, serviceConfig) {
);
}

var defer = q.defer();
var defer = promiseutil.defer();
dbConnPromise.then(function() {
return store.rooms.getRoomIdsFromConfig();
}).then(function(configRooms) {


+ 3
- 3
lib/irclib/client-connection.js View File

@@ -1,6 +1,6 @@
"use strict";
var irc = require("irc");
var q = require("q");
var promiseutil = require("../promiseutil");
var logging = require("../logging");
var log = logging.get("client-connection");

@@ -34,7 +34,7 @@ function ConnectionInstance(ircClient, domain, nick) {
this._listenForPings();
this.dead = false;
this.state = "created"; // created|connecting|connected
this._connectDefer = q.defer();
this._connectDefer = promiseutil.defer();
}

/**
@@ -232,7 +232,7 @@ module.exports = {
secure: server.useSsl(),
selfSigned: server.useSslSelfSigned()
};
var d = q.defer();
var d = promiseutil.defer();
var returnClient = function(cli) {
d.resolve(cli);
};


+ 12
- 8
lib/irclib/client-events.js View File

@@ -340,29 +340,29 @@ module.exports.addHooks = function(client, connInst, callbacks) {
});
hookIfClaimed(client, connInst, "message", function(from, to, text) {
if (to.indexOf("#") !== 0) { return; }
callbacks.onMessage(
ignoreOutcome(callbacks.onMessage(
server, createUser(from), to,
actions.irc.createMessage(text)
);
));
});
hookIfClaimed(client, connInst, "ctcp-privmsg", function(from, to, text) {
if (to.indexOf("#") !== 0) { return; }
if (text.indexOf("ACTION ") === 0) {
callbacks.onMessage(
ignoreOutcome(callbacks.onMessage(
server, createUser(from), to,
actions.irc.createEmote(
text.substring("ACTION ".length)
)
);
));
}
});
hookIfClaimed(client, connInst, "notice", function(from, to, text) {
if (to.indexOf("#") !== 0) { return; }
if (from) { // ignore server notices
callbacks.onMessage(
ignoreOutcome(callbacks.onMessage(
server, createUser(from), to,
actions.irc.createNotice(text)
);
));
}
});
hookIfClaimed(client, connInst, "topic", function(channel, topic, nick) {
@@ -377,9 +377,13 @@ module.exports.addHooks = function(client, connInst, callbacks) {
nick = match[1];
}
}
callbacks.onMessage(
ignoreOutcome(callbacks.onMessage(
server, createUser(nick), channel,
actions.irc.createTopic(topic)
);
));
});
};

function ignoreOutcome(promise) {
promise.then(function() {}, function() {});
}

+ 29
- 26
lib/irclib/client.js View File

@@ -1,6 +1,7 @@
"use strict";

var q = require("q");
var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var ident = require("./ident");
@@ -31,7 +32,7 @@ function BridgedClient(ircUser, matrixUser, isBot) {
this.instCreationFailed = false;
this.explicitDisconnect = false;
this.chanList = [];
this._connectDefer = q.defer();
this._connectDefer = promiseutil.defer();
this._id = (Math.random() * 1e20).toString(36);
// decorate log lines with the nick and domain, along with an instance id
var prefix = "<" + this.nick + "@" + this.server.domain + "#" + this._id + "> ";
@@ -78,7 +79,7 @@ BridgedClient.prototype.connect = function(callbacks) {
this.callbacks = callbacks;
var self = this;
var server = this.server;
var defer = q.defer();
var defer = promiseutil.defer();

names.getIrcNames(this.ircUser, this.matrixUser).then(function(nameInfo) {
self.log.info(
@@ -136,9 +137,9 @@ BridgedClient.prototype.connect = function(callbacks) {
BridgedClient.prototype.disconnect = function(reason) {
this.explicitDisconnect = true;
if (!this.inst || this.inst.dead) {
return q();
return Promise.resolve();
}
var d = q.defer();
var d = promiseutil.defer();
this.inst.disconnect(reason, function() {
d.resolve();
});
@@ -157,7 +158,7 @@ BridgedClient.prototype.changeNick = function(newNick) {
var nick = newNick.replace(/[^A-Za-z0-9\]\[\^\\\{\}\-`_]/g, "");
// nicks must start with a letter
if (!/^[A-Za-z]/.test(nick)) {
return q.reject("Nick '" + nick + "' must start with a letter.");
return Promise.reject("Nick '" + nick + "' must start with a letter.");
}
var maxNickLen = 9; // RFC 1459 default
if (this.unsafeClient.supported &&
@@ -165,13 +166,15 @@ BridgedClient.prototype.changeNick = function(newNick) {
maxNickLen = this.unsafeClient.supported.nicklength;
}
if (nick.length > maxNickLen) {
return q.reject("Nick '" + nick + "' is too long. (Max: " + maxNickLen + ")");
return Promise.reject(
"Nick '" + nick + "' is too long. (Max: " + maxNickLen + ")"
);
}
if (nick === this.nick) {
return q("Your nick is already '" + nick + "'.");
return Promise.resolve("Your nick is already '" + nick + "'.");
}

var d = q.defer();
var d = promiseutil.defer();
this.unsafeClient.once("nick", function(old, n) {
d.resolve("Nick changed from '" + old + "' to '" + n + "'.");
});
@@ -180,23 +183,23 @@ BridgedClient.prototype.changeNick = function(newNick) {
};

BridgedClient.prototype.joinChannel = function(channel) {
if (this.disabled) { return q(new IrcRoom(this.server, channel)); }
if (this.disabled) { return Promise.resolve(new IrcRoom(this.server, channel)); }
return joinChannel(this, channel);
};

BridgedClient.prototype.leaveChannel = function(channel) {
if (this.disabled) { return q("disabled"); }
if (this.disabled) { return Promise.resolve("disabled"); }
if (!this.inst || this.inst.dead) {
return q(); // we were never connected to the network.
return Promise.resolve(); // we were never connected to the network.
}
if (Object.keys(this.unsafeClient.chans).indexOf(channel) === -1) {
return q(); // we were never joined to it.
return Promise.resolve(); // we were never joined to it.
}
if (channel.indexOf("#") !== 0) {
return q(); // PM room
return Promise.resolve(); // PM room
}
var self = this;
var defer = q.defer();
var defer = promiseutil.defer();
this._removeChannel(channel);
self.log.debug("Leaving channel %s", channel);
this.unsafeClient.part(channel, "User left", function() {
@@ -208,7 +211,7 @@ BridgedClient.prototype.leaveChannel = function(channel) {
};

BridgedClient.prototype.sendAction = function(room, action) {
if (this.disabled) { return q("disabled"); }
if (this.disabled) { return Promise.resolve("disabled"); }
this._keepAlive();
switch (action.action) {
case "message":
@@ -222,17 +225,17 @@ BridgedClient.prototype.sendAction = function(room, action) {
default:
this.log.error("Unknown action type: %s", action.action);
}
return q.reject("Unknown action type: %s", action.action);
return Promise.reject("Unknown action type: %s", action.action);
};

BridgedClient.prototype.whois = function(nick) {
if (this.disabled) {
return q({
return Promise.resolve({
server: this.server,
nick: nick
});
}
var defer = q.defer();
var defer = promiseutil.defer();
var self = this;
this.unsafeClient.whois(nick, function(whois) {
if (!whois.user) {
@@ -326,7 +329,7 @@ module.exports.BridgedClient = BridgedClient;

var setTopic = function(self, room, topic) {
// join the room if we haven't already
var defer = q.defer();
var defer = promiseutil.defer();
joinChannel(self, room.channel).done(function() {
self.log.info("Setting topic to %s in channel %s", topic, room.channel);
self.unsafeClient.send("TOPIC", room.channel, topic);
@@ -339,7 +342,7 @@ var setTopic = function(self, room, topic) {

var sendMessage = function(self, room, msgType, text) {
// join the room if we haven't already
var defer = q.defer();
var defer = promiseutil.defer();
msgType = msgType || "message";
self._connectDefer.promise.then(function() {
return joinChannel(self, room.channel);
@@ -364,19 +367,19 @@ var sendMessage = function(self, room, msgType, text) {
var joinChannel = function(self, channel, attemptCount) {
attemptCount = attemptCount || 1;
if (!self.unsafeClient) {
return q.reject("No client");
return Promise.reject("No client");
}
if (Object.keys(self.unsafeClient.chans).indexOf(channel) !== -1) {
return q(new IrcRoom(self.server, channel));
return Promise.resolve(new IrcRoom(self.server, channel));
}
if (channel.indexOf("#") !== 0) {
// PM room
return q(new IrcRoom(self.server, channel));
return Promise.resolve(new IrcRoom(self.server, channel));
}
if (self.server.isExcludedChannel(channel)) {
return q.reject(channel + " is a do-not-track channel.");
return Promise.reject(channel + " is a do-not-track channel.");
}
var defer = q.defer();
var defer = promiseutil.defer();
self.log.debug("Joining channel %s", channel);
self._addChannel(channel);
var client = self.unsafeClient;


+ 11
- 10
lib/irclib/irc.js View File

@@ -3,7 +3,8 @@
*/
"use strict";

var q = require("q");
var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var log = require("../logging").get("irc");

var membershiplists = require("../bridge/membershiplists.js");
@@ -73,10 +74,10 @@ IrcLib.prototype.getBridgedClient = function(server, userId, displayName) {
var bridgedClient = module.exports.getIrcUserFromCache(server, userId);
if (bridgedClient) {
lg.debug("Returning cached bridged client %s", userId);
return q(bridgedClient);
return Promise.resolve(bridgedClient);
}

var defer = q.defer();
var defer = promiseutil.defer();

var nick = server.getNick(userId, displayName);
var ircUser = new IrcUser(server, nick, true);
@@ -172,9 +173,9 @@ var loginToServer = function(server) {
var getBotClient = function(server) {
var botClient = pool.getBot(server);
if (botClient) {
return q(botClient);
return Promise.resolve(botClient);
}
var defer = q.defer();
var defer = promiseutil.defer();
loginToServer(server).done(function() {
defer.resolve(pool.getBot(server));
},
@@ -185,13 +186,13 @@ var getBotClient = function(server) {
};

module.exports.connect = function() {
var defer = q.defer();
var defer = promiseutil.defer();
store.waitForDatabase().done(function() {
var promises = [];
servers.forEach(function(server) {
promises.push(loginToServer(server));
});
q.allSettled(promises).then(function() {
promiseutil.allSettled(promises).then(function() {
defer.resolve();
});
});
@@ -271,11 +272,11 @@ module.exports.aliasToIrcChannel = function(alias) {
module.exports.matrixToIrcUser = function(user) {
if (user.protocol !== "matrix") {
log.error("Bad src protocol: %s", user.protocol);
return q.reject("Bad source protocol.");
return Promise.reject("Bad source protocol.");
}
var ircInfo = userIdToServerNick(user.userId);
if (!ircInfo.server || !ircInfo.nick) {
return q.reject("User ID " + user.userId + " doesn't map to a server/nick");
return Promise.reject("User ID " + user.userId + " doesn't map to a server/nick");
}
return q(new IrcUser(ircInfo.server, ircInfo.nick, true));
return Promise.resolve(new IrcUser(ircInfo.server, ircInfo.nick, true));
};

+ 4
- 4
lib/irclib/names.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var promiseutil = require("../promiseutil");
var store = require("../store");
var log = require("../logging").get("irc-names");

@@ -17,7 +17,7 @@ var processing = null;
*/
var generateIdentUsername = function(domain, userId) {
// @foobar££stuff:domain.com => foobar__stuff_domain_com
var d = q.defer();
var d = promiseutil.defer();
var uname = sanitiseUsername(userId.substring(1));
if (uname < module.exports.MAX_USER_NAME_LENGTH) { // bwahaha not likely.
return uname;
@@ -188,7 +188,7 @@ module.exports = {
* }
*/
getIrcNames: function(ircUser, matrixUser) {
var d = q.defer();
var d = promiseutil.defer();
var generatingUsername = false;
var info = {};
// strip illegal chars according to RFC 1459 Sect 2.3.1
@@ -206,7 +206,7 @@ module.exports = {
}
else {
generatingUsername = true;
var queueDefer = q.defer();
var queueDefer = promiseutil.defer();
queue.push({
matrixUser: matrixUser,
ircUser: ircUser,


+ 4
- 3
lib/models/requests.js View File

@@ -8,7 +8,8 @@
*/
"use strict";

var q = require("q");
var promiseutil = require("../promiseutil");

var matrixLib = require("../mxlib/matrix");
var ircLib = require("../irclib/irc");
var stats = require("../config/stats");
@@ -54,7 +55,7 @@ module.exports.findRequest = function(requestId) {
module.exports.newRequest = function(isFromIrc) {
var requestId = generateRequestId();
var logger = logging.newRequestLogger(log, requestId, isFromIrc);
var request = new Request(requestId, q.defer(), logger, isFromIrc);
var request = new Request(requestId, promiseutil.defer(), logger, isFromIrc);
outstandingRequests[requestId] = request;

// expose an error handler to prevent defer boilerplate leaking everywhere
@@ -78,7 +79,7 @@ module.exports.newRequest = function(isFromIrc) {
request.finished = true;
var delta = Date.now() - request.start;
delete outstandingRequests[requestId];
if (err === module.exports.ERR_VIRTUAL_USER) {
if (err.message === module.exports.ERR_VIRTUAL_USER) {
request.log.debug("IGNORED - %s ms (Sender is a virtual user.)",
delta);
return;


+ 14
- 13
lib/mxlib/matrix.js View File

@@ -3,7 +3,8 @@
*/
"use strict";

var q = require("q");
var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var sdk = require("./cs-extended-sdk");
var MatrixRoom = require("../models/rooms").MatrixRoom;
var MatrixUser = require("../models/users").MatrixUser;
@@ -39,14 +40,14 @@ module.exports.setMatrixClientConfig = function(config) {
};

module.exports.joinMappedRooms = function() {
var d = q.defer();
var d = promiseutil.defer();
var promises = [];
store.rooms.getRoomIdsFromConfig().done(function(roomIds) {
var lib = module.exports.getMatrixLibFor();
roomIds.forEach(function(roomId) {
promises.push(lib.joinRoom(roomId));
});
q.allSettled(promises).then(function() {
promiseutil.allSettled(promises).then(function() {
d.resolve();
});
});
@@ -87,7 +88,7 @@ MatrixLib.prototype._getClient = function(userId) {
};

MatrixLib.prototype.addAlias = function(roomId, alias) {
var defer = q.defer();
var defer = promiseutil.defer();
var client = this._getClient();
client.createAlias(
alias, roomId
@@ -100,7 +101,7 @@ MatrixLib.prototype.addAlias = function(roomId, alias) {
};

MatrixLib.prototype.createRoomWithUser = function(fromUserId, toUserId, name) {
var defer = q.defer();
var defer = promiseutil.defer();
var client = this._getClient(fromUserId);
var room;
client.createRoom({
@@ -196,7 +197,7 @@ MatrixLib.prototype.leaveRoom = function(userId, roomId) {
};

MatrixLib.prototype.isPmRoom = function(userId, roomId, pmRoomUserId) {
var defer = q.defer();
var defer = promiseutil.defer();
var client = this._getClient(userId);
client.roomState(roomId).then(function(response) {
var joinedMembers = 0;
@@ -231,13 +232,13 @@ MatrixLib.prototype.sendAction = function(room, from, action) {
else if (action.action === "topic") {
return setTopic(this, room, from, action.topic);
}
return q.reject("Unknown action: " + action.action);
return Promise.reject("Unknown action: " + action.action);
};

MatrixLib.prototype.setInviteOnly = function(room, isInviteOnly) {
var joinRule = isInviteOnly ? "invite" : "public";
var client = this._getClient();
var defer = q.defer();
var defer = promiseutil.defer();
setJoinRule(client, room.roomId, joinRule).done(function() {
defer.resolve({});
}, function(e) {
@@ -254,7 +255,7 @@ MatrixLib.prototype.joinRoom = function(roomId, matrixUser) {
// specified.
var opts = {syncRoom: false};
var lib = this;
var defer = q.defer();
var defer = promiseutil.defer();
var client = matrixUser ? lib._getClient(matrixUser.userId) : lib._getClient();
client.joinRoom(roomId, opts).done(function(response) {
defer.resolve(response);
@@ -307,7 +308,7 @@ MatrixLib.prototype.invite = function(room, userIdToInvite) {

MatrixLib.prototype.getDisplayName = function(roomId, userId) {
var client = this._getClient();
var defer = q.defer();
var defer = promiseutil.defer();
client.getStateEvent(roomId, "m.room.member", userId).done(function(res) {
defer.resolve(res.displayname);
}, function(err) {
@@ -349,7 +350,7 @@ var setRoomHistoryVisibility = function(client, roomId, history_visibility) {
};

var setTopic = function(lib, room, from, topic) {
var defer = q.defer();
var defer = promiseutil.defer();
var client = lib._getClient(from.userId);
client.setRoomTopic(room.roomId, topic).then(function(suc) {
defer.resolve(suc);
@@ -393,7 +394,7 @@ var sendHtml = function(lib, room, from, msgtype, html) {
* rejected if it failed to send.
*/
var sendMessageEvent = function(lib, room, from, content, joinState, existingDefer) {
var defer = existingDefer || q.defer();
var defer = existingDefer || promiseutil.defer();
var client = lib._getClient(from.userId);
client.sendMessage(room.roomId, content).then(function(suc) {
defer.resolve(suc);
@@ -418,7 +419,7 @@ var sendMessageEvent = function(lib, room, from, content, joinState, existingDef


var getMatrixUser = function(userLocalpart, displayName) {
var defer = q.defer();
var defer = promiseutil.defer();
var client = sdk.getClientAs();

var createUserFn = function() {


+ 23
- 0
lib/promiseutil.js View File

@@ -0,0 +1,23 @@
var Promise = require("bluebird");

function defer() {
var resolve, reject;
var promise = new Promise(function() {
resolve = arguments[0];
reject = arguments[1];
});
return {
resolve: resolve,
reject: reject,
promise: promise
};
}

function allSettled(promises) {
return Promise.all(promises.map(function(p) {
return p.reflect();
}));
}

module.exports.defer = defer;
module.exports.allSettled = allSettled;

+ 26
- 25
lib/store.js View File

@@ -4,7 +4,8 @@
*/
"use strict";

var q = require("q");
var Promise = require("bluebird");
var promiseutil = require("./promiseutil");

var rooms = require("./models/rooms");
var IrcRoom = rooms.IrcRoom;
@@ -17,10 +18,10 @@ var toIrcLowerCase = require("./irclib/formatting").toIrcLowerCase;
var Datastore = require("nedb");

var collection = {
rooms: { db: null, loc: "/rooms.db", defer: q.defer() },
config: { db: null, loc: "/config.db", defer: q.defer() },
users: { db: null, loc: "/users.db", defer: q.defer() },
irc_clients: { db: null, loc: "/irc_clients.db", defer: q.defer() }
rooms: { db: null, loc: "/rooms.db", defer: promiseutil.defer() },
config: { db: null, loc: "/config.db", defer: promiseutil.defer() },
users: { db: null, loc: "/users.db", defer: promiseutil.defer() },
irc_clients: { db: null, loc: "/irc_clients.db", defer: promiseutil.defer() }
};

/**
@@ -101,7 +102,7 @@ module.exports.connectToDatabase = function(databaseUri) {
}

if (databaseUri.indexOf("nedb://") !== 0) {
return q.reject(
return Promise.reject(
"Must use a nedb:// URI of the form nedb://databasefolder"
);
}
@@ -125,7 +126,7 @@ module.exports.connectToDatabase = function(databaseUri) {
});
});

dbPromise = q.all(promises);
dbPromise = Promise.all(promises);

return dbPromise;
};
@@ -161,7 +162,7 @@ module.exports.setServerFromConfig = function(server, serverConfig) {

module.exports.config = {
set: function(info) {
var d = q.defer();
var d = promiseutil.defer();
upsert(getCollection("config"), d, {},
{
$set: info
@@ -171,7 +172,7 @@ module.exports.config = {
},

get: function() {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("config"), d, {}, false);
return d.promise;
}
@@ -186,7 +187,7 @@ module.exports.rooms = {
* @return {Promise}
*/
set: function(ircRoom, matrixRoom, fromConfig) {
var d = q.defer();
var d = promiseutil.defer();
var addr = ircRoom.server ? ircRoom.server.domain : undefined;
fromConfig = Boolean(fromConfig);

@@ -210,7 +211,7 @@ module.exports.rooms = {
* rooms.
*/
getIrcChannelsForRoomId: function(roomId) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("rooms"), d, {
room_id: roomId
}, true, function(docs) {
@@ -235,7 +236,7 @@ module.exports.rooms = {
* @return {Promise<Array<MatrixRoom>>} A promise which resolves to a list of rooms.
*/
getMatrixRoomsForChannel: function(server, channel) {
var d = q.defer();
var d = promiseutil.defer();
channel = toIrcLowerCase(channel); // all stored in lower case
select(getCollection("rooms"), d, {
irc_addr: server.domain,
@@ -256,7 +257,7 @@ module.exports.rooms = {
// PM to two separate 'rooms' ('to' room is the nick), and because we want to
// clobber uid:uid pairs.
setPmRoom: function(ircRoom, matrixRoom, userId, virtualUserId) {
var d = q.defer();
var d = promiseutil.defer();
var addr = (
ircRoom.server ? ircRoom.server.domain : undefined
);
@@ -283,7 +284,7 @@ module.exports.rooms = {
},

getMatrixPmRoom: function(realUserId, virtualUserId) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("rooms"), d, {
type: "pm",
real_user_id: realUserId,
@@ -298,7 +299,7 @@ module.exports.rooms = {
},

getTrackedChannelsForServer: function(ircAddr) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("rooms"), d, {
irc_addr: ircAddr
}, true, function(docs) {
@@ -314,7 +315,7 @@ module.exports.rooms = {
},

getRoomIdsFromConfig: function() {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("rooms"), d, { from_config: true }, true,
function(docs) {
var roomIds = [];
@@ -330,7 +331,7 @@ module.exports.rooms = {

// removes all mappings with from_config = true
removeConfigMappings: function() {
var d = q.defer();
var d = promiseutil.defer();
log.info("removeConfigMappings");
del(getCollection("rooms"), d, { from_config: true });
return d.promise;
@@ -342,7 +343,7 @@ module.exports.rooms = {
* @return {Promise} Resolved when the room is retrieved.
*/
getAdminRoomById: function(roomId) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("rooms"), d, {
type: "admin",
room_id: roomId
@@ -362,7 +363,7 @@ module.exports.rooms = {
* @return {Promise} Resolved when the room is stored.
*/
storeAdminRoom: function(room, userId) {
var d = q.defer();
var d = promiseutil.defer();
log.info("storeAdminRoom (id=%s, user_id=%s)", room.roomId, userId);

upsert(getCollection("rooms"), d, {
@@ -382,7 +383,7 @@ module.exports.rooms = {

module.exports.users = {
get: function(userLocalpart) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("users"), d, {
localpart: userLocalpart
}, false, function(doc) {
@@ -395,7 +396,7 @@ module.exports.users = {
},

set: function(user, localpart, displayName, setDisplayName) {
var d = q.defer();
var d = promiseutil.defer();
log.info(
"storeUser (user_id=%s, localpart=%s display_name=%s " +
"set_display_name=%s)",
@@ -419,7 +420,7 @@ module.exports.users = {

module.exports.ircClients = {
get: function(userId, domain) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("irc_clients"), d, {
user_id: userId,
domain: domain
@@ -436,7 +437,7 @@ module.exports.ircClients = {
return d.promise;
},
set: function(userId, ircUser) {
var d = q.defer();
var d = promiseutil.defer();
log.info("Storing " + ircUser + " on behalf of " + userId);

upsert(getCollection("irc_clients"), d, {
@@ -455,7 +456,7 @@ module.exports.ircClients = {
return d.promise;
},
update: function(userId, domain, key, newVal) {
var d = q.defer();
var d = promiseutil.defer();
log.info(
"Update %s for %s on %s to %s",
key, userId, domain, newVal
@@ -473,7 +474,7 @@ module.exports.ircClients = {
return d.promise;
},
getByUsername: function(domain, username) {
var d = q.defer();
var d = promiseutil.defer();
select(getCollection("irc_clients"), d, {
domain: domain,
username: username


+ 1
- 1
package.json View File

@@ -21,6 +21,7 @@
"url": "https://github.com/matrix-org/matrix-appservice-irc/issues"
},
"dependencies": {
"bluebird": "^3.1.1",
"crc": "^3.2.1",
"extend": "^2.0.0",
"fs": "0.0.2",
@@ -31,7 +32,6 @@
"matrix-js-sdk": "0.3.0",
"nedb": "^1.1.2",
"nopt": "^3.0.1",
"q": "^1.2.0",
"request": "^2.54.0",
"sanitize-html": "^1.6.1",
"winston": "^0.9.0"


+ 8
- 8
spec/integ/admin-rooms.spec.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var Promise = require("bluebird");
var test = require("../util/test");

// set up integration testing mocks
@@ -35,7 +35,7 @@ describe("Creating admin rooms", function() {
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual("!adminroomid:here");
botJoinedRoom = true;
return q({});
return Promise.resolve({});
});

env.mockAsapiController._trigger("type:m.room.member", {
@@ -90,7 +90,7 @@ describe("Admin rooms", function() {
sdk = env.clientMock._client();
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual(adminRoomId);
return q({});
return Promise.resolve({});
});

// do the init
@@ -135,7 +135,7 @@ describe("Admin rooms", function() {
expect(roomId).toEqual(adminRoomId);
expect(content.msgtype).toEqual("m.notice");
sentNotice = true;
return q();
return Promise.resolve();
});

env.mockAsapiController._trigger("type:m.room.message", {
@@ -159,7 +159,7 @@ describe("Admin rooms", function() {
expect(roomId).toEqual(adminRoomId);
expect(content.msgtype).toEqual("m.notice");
sentNotice = true;
return q();
return Promise.resolve();
});

env.mockAsapiController._trigger("type:m.room.message", {
@@ -225,7 +225,7 @@ describe("Admin rooms", function() {
expect(roomId).toEqual(adminRoomId);
expect(content.msgtype).toEqual("m.notice");
sentAckNotice = true;
return q();
return Promise.resolve();
});

// trigger the request to change the nick
@@ -277,7 +277,7 @@ describe("Admin rooms", function() {
sdk.createRoom.andCallFake(function(opts) {
expect(opts.visibility).toEqual("private");
createdMatrixRoom = true;
return q({
return Promise.resolve({
room_id: newRoomId
});
});
@@ -288,7 +288,7 @@ describe("Admin rooms", function() {
expect(roomId).toEqual(newRoomId);
expect(inviteeUserId).toEqual(userId);
sentInvite = true;
return q({
return Promise.resolve({
room_id: newRoomId
});
});


+ 12
- 12
spec/integ/dynamic-channels.spec.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var Promise = require("bluebird");
var test = require("../util/test");

// set up integration testing mocks
@@ -59,7 +59,7 @@ describe("Dynamic channels", function() {
var sdk = env.clientMock._client();
sdk.createRoom.andCallFake(function(opts) {
expect(opts.room_alias_name).toEqual(tAliasLocalpart);
return q({
return Promise.resolve({
room_id: tRoomId
});
});
@@ -67,7 +67,7 @@ describe("Dynamic channels", function() {
expect(roomId).toEqual(tRoomId);
expect(eventType).toEqual("m.room.history_visibility");
expect(obj).toEqual({history_visibility: "joined"});
return q({});
return Promise.resolve({});
});

env.mockAsapiController._queryAlias(tAlias).done(function() {
@@ -105,7 +105,7 @@ describe("Dynamic channels", function() {
var sdk = env.clientMock._client();
sdk.createRoom.andCallFake(function(opts) {
expect(opts.creation_content).toEqual({"m.federate": true});
return q({
return Promise.resolve({
room_id: tRoomId
});
});
@@ -114,7 +114,7 @@ describe("Dynamic channels", function() {
expect(roomId).toEqual(tRoomId);
expect(eventType).toEqual("m.room.history_visibility");
expect(obj).toEqual({history_visibility: "joined"});
return q({});
return Promise.resolve({});
});

env.mockAsapiController._queryAlias(tAlias).done(function() {
@@ -148,7 +148,7 @@ describe("Dynamic channels", function() {
var sdk = env.clientMock._client();
sdk.createRoom.andCallFake(function(opts) {
expect(opts.creation_content).toEqual({"m.federate": false});
return q({
return Promise.resolve({
room_id: tRoomId
});
});
@@ -157,7 +157,7 @@ describe("Dynamic channels", function() {
expect(roomId).toEqual(tRoomId);
expect(eventType).toEqual("m.room.history_visibility");
expect(obj).toEqual({history_visibility: "joined"});
return q({});
return Promise.resolve({});
});

env.mockAsapiController._queryAlias(tAlias).done(function() {
@@ -191,7 +191,7 @@ describe("Dynamic channels", function() {
var sdk = env.clientMock._client();
sdk.createRoom.andCallFake(function(opts) {
expect(opts.room_alias_name).toEqual(tAliasLocalpart);
return q({
return Promise.resolve({
room_id: tRoomId
});
});
@@ -200,7 +200,7 @@ describe("Dynamic channels", function() {
expect(roomId).toEqual(tRoomId);
expect(eventType).toEqual("m.room.history_visibility");
expect(obj).toEqual({history_visibility: "joined"});
return q({});
return Promise.resolve({});
});

var madeAlias = false;
@@ -208,7 +208,7 @@ describe("Dynamic channels", function() {
madeAlias = true;
expect(roomId).toEqual(tRoomId);
expect(alias).toEqual(tCapsAlias);
return q({});
return Promise.resolve({});
});

env.mockAsapiController._queryAlias(tAlias).then(function() {
@@ -272,7 +272,7 @@ describe("Dynamic channels (disabled)", function() {
// when we get the create room request, process it.
var sdk = env.clientMock._client();
sdk.createRoom.andCallFake(function(opts) {
return q({
return Promise.resolve({
room_id: tRoomId
});
});
@@ -281,7 +281,7 @@ describe("Dynamic channels (disabled)", function() {
expect(roomId).toEqual(tRoomId);
expect(eventType).toEqual("m.room.history_visibility");
expect(obj).toEqual({history_visibility: "joined"});
return q({});
return Promise.resolve({});
});

env.mockAsapiController._queryAlias(tAlias).catch(function() {


+ 3
- 3
spec/integ/hs-queries.spec.js View File

@@ -1,6 +1,6 @@
"use strict";
var test = require("../util/test");
var q = require("q");
var Promise = require("bluebird");

// set up integration testing mocks
var env = test.mkEnv();
@@ -88,7 +88,7 @@ describe("Homeserver alias queries", function() {
sdk.createRoom.andCallFake(function(opts) {
expect(opts.room_alias_name).toEqual(testLocalpart);
expect(opts.visibility).toEqual("public");
return q({
return Promise.resolve({
room_id: "!something:somewhere"
});
});
@@ -96,7 +96,7 @@ describe("Homeserver alias queries", function() {
sdk.sendStateEvent.andCallFake(function(roomId, eventType, obj) {
expect(eventType).toEqual("m.room.history_visibility");
expect(obj).toEqual({history_visibility: "joined"});
return q({});
return Promise.resolve({});
});

var botJoined = false;


+ 5
- 5
spec/integ/invite-rooms.spec.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var Promise = require("bluebird");
var test = require("../util/test");

// set up integration testing mocks
@@ -41,7 +41,7 @@ describe("Invite-only rooms", function() {
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
joinedRoom = true;
return q({});
return Promise.resolve({});
});

env.mockAsapiController._trigger("type:m.room.member", {
@@ -84,21 +84,21 @@ describe("Invite-only rooms", function() {
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
joinedRoom = true;
return q({});
return Promise.resolve({});
});

var leftRoom = false;
sdk.leave.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
leftRoom = true;
return q({});
return Promise.resolve({});
});

var askedForRoomState = false;
sdk.roomState.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
askedForRoomState = true;
return q([
return Promise.resolve([
{
content: {membership: "join"},
user_id: botUserId,


+ 8
- 8
spec/integ/irc-connections.spec.js View File

@@ -3,7 +3,7 @@
*/
"use strict";
var test = require("../util/test");
var q = require("q");
var Promise = require("bluebird");

// set up integration testing mocks
var env = test.mkEnv();
@@ -68,7 +68,7 @@ describe("IRC connections", function() {

// mock a response for the state event.
env.clientMock._client().getStateEvent.andCallFake(function() {
return q({
return Promise.resolve({
displayname: displayName
});
});
@@ -116,7 +116,7 @@ describe("IRC connections", function() {
"irc user with a nick assigned from rpl_welcome."
);
done();
return q();
return Promise.resolve();
});

// let the user connect
@@ -195,7 +195,7 @@ describe("IRC connections", function() {
type: "m.room.message"
}));

q.all(promises).done(function() {
Promise.all(promises).done(function() {
expect(connectCount).toBe(1);
done();
});
@@ -249,7 +249,7 @@ describe("IRC connections", function() {
"irc user (clashing nicks)."
);
done();
return q();
return Promise.resolve();
});

// send a message from the first guy
@@ -334,7 +334,7 @@ describe("IRC connections", function() {

// mock a response for the state event.
env.clientMock._client().getStateEvent.andCallFake(function() {
return q({});
return Promise.resolve({});
});

// send a message to kick start the AS
@@ -398,7 +398,7 @@ describe("IRC connections", function() {

// mock a response for the state event.
env.clientMock._client().getStateEvent.andCallFake(function() {
return q({});
return Promise.resolve({});
});

// send a message to kick start the AS
@@ -420,7 +420,7 @@ describe("IRC connections", function() {
room_id: roomMapping.roomId,
type: "m.room.message"
});
q.all([p1, p2]).done(function() {
Promise.all([p1, p2]).done(function() {
expect(usr1.username).toBeDefined();
expect(usr2.username).toBeDefined();
expect(usr1.username).not.toEqual(usr2.username);


+ 5
- 5
spec/integ/irc-modes.spec.js View File

@@ -2,7 +2,7 @@
* Contains integration tests for IRC mode events.
*/
"use strict";
var q = require("q");
var Promise = require("bluebird");
var test = require("../util/test");

// set up integration testing mocks
@@ -57,7 +57,7 @@ describe("IRC-to-Matrix mode bridging", function() {
});
expect(key).toEqual("");
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -76,7 +76,7 @@ describe("IRC-to-Matrix mode bridging", function() {
});
expect(key).toEqual("");
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -95,7 +95,7 @@ describe("IRC-to-Matrix mode bridging", function() {
});
expect(key).toEqual("");
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -114,7 +114,7 @@ describe("IRC-to-Matrix mode bridging", function() {
});
expect(key).toEqual("");
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(


+ 7
- 7
spec/integ/irc-to-matrix.spec.js View File

@@ -2,7 +2,7 @@
* Contains integration tests for all IRC-initiated events.
*/
"use strict";
var q = require("q");
var Promise = require("bluebird");
var test = require("../util/test");

// set up integration testing mocks
@@ -61,7 +61,7 @@ describe("IRC-to-Matrix message bridging", function() {
msgtype: "m.text"
});
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -80,7 +80,7 @@ describe("IRC-to-Matrix message bridging", function() {
msgtype: "m.emote"
});
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -101,7 +101,7 @@ describe("IRC-to-Matrix message bridging", function() {
msgtype: "m.notice"
});
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -119,7 +119,7 @@ describe("IRC-to-Matrix message bridging", function() {
expect(roomId).toEqual(roomMapping.roomId);
expect(topic).toEqual(testTopic);
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -138,7 +138,7 @@ describe("IRC-to-Matrix message bridging", function() {
msgtype: "m.text"
});
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -177,7 +177,7 @@ describe("IRC-to-Matrix message bridging", function() {
checksum(tHtmlCloseTags)
);
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(


+ 3
- 3
spec/integ/mirroring.spec.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var Promise = require("bluebird");
var test = require("../util/test");

// set up integration testing mocks
@@ -178,7 +178,7 @@ describe("Mirroring", function() {
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(
@@ -191,7 +191,7 @@ describe("Mirroring", function() {
sdk.leave.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
done();
return q();
return Promise.resolve();
});

env.ircMock._findClientAsync(roomMapping.server, roomMapping.botNick).done(


+ 23
- 22
spec/integ/pm.spec.js View File

@@ -2,7 +2,8 @@
* Contains integration tests for private messages.
*/
"use strict";
var q = require("q");
var Promise = require("bluebird");
var promiseutil = require("../../lib/promiseutil");
var test = require("../util/test");

// set up integration testing mocks
@@ -25,10 +26,10 @@ describe("Matrix-to-IRC PMing", function() {
test.beforeEach(this, env);

// reset the deferreds
whoisDefer = q.defer();
registerDefer = q.defer();
joinRoomDefer = q.defer();
roomStateDefer = q.defer();
whoisDefer = promiseutil.defer();
registerDefer = promiseutil.defer();
joinRoomDefer = promiseutil.defer();
roomStateDefer = promiseutil.defer();

env.ircMock._autoConnectNetworks(
roomMapping.server, roomMapping.botNick, roomMapping.server
@@ -42,7 +43,7 @@ describe("Matrix-to-IRC PMing", function() {
it("should join 1:1 rooms invited from matrix", function(done) {
// there's a number of actions we want this to do, so track them to make
// sure they are all called.
var globalPromise = q.all([
var globalPromise = Promise.all([
registerDefer.promise, joinRoomDefer.promise,
roomStateDefer.promise
]);
@@ -79,12 +80,12 @@ describe("Matrix-to-IRC PMing", function() {
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
joinRoomDefer.resolve();
return q({});
return Promise.resolve({});
});
sdk.roomState.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
roomStateDefer.resolve({});
return q([
return Promise.resolve([
{
content: {membership: "join"},
user_id: tIrcUserId,
@@ -110,10 +111,10 @@ describe("Matrix-to-IRC PMing", function() {
it("should join group chat rooms invited from matrix then leave them",
function(done) {
// additional actions on group chat rooms
var sendMessageDefer = q.defer();
var leaveRoomDefer = q.defer();
var sendMessageDefer = promiseutil.defer();
var leaveRoomDefer = promiseutil.defer();

var globalPromise = q.all([
var globalPromise = Promise.all([
registerDefer.promise, joinRoomDefer.promise,
roomStateDefer.promise, leaveRoomDefer.promise,
sendMessageDefer.promise
@@ -153,24 +154,24 @@ describe("Matrix-to-IRC PMing", function() {
sdk.joinRoom.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
joinRoomDefer.resolve();
return q({});
return Promise.resolve({});
});
// see if it sends a message (to say it doesn't do group chat)
sdk.sendMessage.andCallFake(function(roomId, content) {
expect(roomId).toEqual(roomMapping.roomId);
sendMessageDefer.resolve();
return q({});
return Promise.resolve({});
});
// when it tries to leave, accept it
sdk.leave.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
leaveRoomDefer.resolve();
return q({});
return Promise.resolve({});
});
sdk.roomState.andCallFake(function(roomId) {
expect(roomId).toEqual(roomMapping.roomId);
roomStateDefer.resolve({});
return q([
return Promise.resolve([
{
content: {membership: "join"},
user_id: tIrcUserId,
@@ -256,17 +257,17 @@ describe("IRC-to-Matrix PMing", function() {
it("should create a 1:1 matrix room and invite the real matrix user when " +
"it receives a PM directed at a virtual user from a real IRC user",
function(done) {
var createRoomDefer = q.defer();
var inviteDefer = q.defer();
var sendMsgDefer = q.defer();
var promises = q.all([
var createRoomDefer = promiseutil.defer();
var inviteDefer = promiseutil.defer();
var sendMsgDefer = promiseutil.defer();
var promises = Promise.all([
createRoomDefer.promise, inviteDefer.promise, sendMsgDefer.promise
]);
// mock create room impl
sdk.createRoom.andCallFake(function(opts) {
expect(opts.visibility).toEqual("private");
createRoomDefer.resolve();
return q({
return Promise.resolve({
room_id: tCreatedRoomId
});
});
@@ -275,7 +276,7 @@ describe("IRC-to-Matrix PMing", function() {
expect(roomId).toEqual(tCreatedRoomId);
expect(userId).toEqual(tRealUserId);
inviteDefer.resolve();
return q({});
return Promise.resolve({});
});
// mock send message impl
sdk.sendMessage.andCallFake(function(roomId, content) {
@@ -285,7 +286,7 @@ describe("IRC-to-Matrix PMing", function() {
msgtype: "m.text"
});
sendMsgDefer.resolve();
return q({});
return Promise.resolve({});
});

// test completes after all the matrix actions are done


+ 4
- 4
spec/unit/names.spec.js View File

@@ -1,5 +1,5 @@
"use strict";
var q = require("q");
var Promise = require("bluebird");
var proxyquire = require("proxyquire");
var test = require("../util/test");

@@ -33,10 +33,10 @@ describe("Username generation", function() {
userId: existingUsernames[uname]
};
}
return q(obj);
return Promise.resolve(obj);
};
storeMock.ircClients.set = function() {
return q();
return Promise.resolve();
};

names = proxyquire("../../lib/irclib/names.js", {
@@ -93,7 +93,7 @@ describe("Username generation", function() {
it("should eventually give up trying usernames", function(done) {
names.MAX_USER_NAME_LENGTH = 3;
storeMock.ircClients.getByUsername = function() {
return q({userId: "@someone:else"});
return Promise.resolve({userId: "@someone:else"});
};
var userId = "@myreallylonguseridhere:localhost";
names.getIrcNames(ircUser, mkMatrixUser(userId)).done(function(info) {


+ 42
- 0
spec/unit/promiseutil.spec.js View File

@@ -0,0 +1,42 @@
"use strict";
var Promise = require("bluebird");
var promiseutil = require("../../lib/promiseutil");

describe("promiseutil.allSettled", function() {
it("waits for all", function(done) {
var promises = [
Promise.resolve("good"),
Promise.reject("bad"),

new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Waited 50ms");
resolve("resolved value");
}, 50);
}),

new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Waited 60ms");
reject("rejected value");
}, 60);
})
];
promiseutil.allSettled(promises).then(function(settled) {
expect(settled.length).toEqual(promises.length);

expect(settled[0].isFulfilled()).toEqual(true);
expect(settled[0].value()).toEqual("good");

expect(settled[1].isRejected()).toEqual(true);
expect(settled[1].reason()).toEqual("bad");

expect(settled[2].isFulfilled()).toEqual(true);
expect(settled[2].value()).toEqual("resolved value");

expect(settled[3].isRejected()).toEqual(true);
expect(settled[3].reason()).toEqual("rejected value");
done();
});
});
});

+ 2
- 2
spec/util/asapi-controller-mock.js View File

@@ -2,7 +2,7 @@
* Mock replacement for AsapiController
*/
"use strict";
var q = require("q");
var Promise = require("bluebird");

/**
* Construct a new mock ASAPI controller.
@@ -34,7 +34,7 @@ module.exports.create = function() {
if (promises.length === 1) {
return promises[0];
}
return q.all(promises);
return Promise.all(promises);
},
_queryAlias: function(alias) {
return resolvers.alias(alias);


+ 4
- 4
spec/util/client-sdk-mock.js View File

@@ -2,7 +2,7 @@
* Mock replacement for 'matrix-js-sdk'.
*/
"use strict";
var q = require("q");
var Promise = require("bluebird");
var suppliedConfig = null;
var mockClient = {};

@@ -60,14 +60,14 @@ module.exports._reset = function() {
// mock up getStateEvent immediately since it is called for every new IRC
// connection.
mockClient.getStateEvent.andCallFake(function() {
return q({});
return Promise.resolve({});
});

// Helper to succeed sdk registration calls.
mockClient._onHttpRegister = function(params) {
mockClient.register.andCallFake(function(username, password) {
expect(username).toEqual(params.expectLocalpart);
return q({
return Promise.resolve({
user_id: params.returnUserId
});
});
@@ -75,7 +75,7 @@ module.exports._reset = function() {
if (params.andResolve) {
params.andResolve.resolve();