<commit_before>"use strict";

var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var ident = require("./ident");
var ConnectionInstance = require("./ConnectionInstance");
var IrcRoom = require("../models/IrcRoom");
var log = require("../logging").get("irc-client");

// The length of time to wait before trying to join the channel again
var JOIN_TIMEOUT_MS = 15 * 1000; // 15s

/**
 * Create a new bridged IRC client.
 * @constructor
 * @param {Object} ircUser : The IRC user to create a connection for.
 * @param {Object} matrixUser : Optional. The matrix user this virtual IRC user.
 * @param {boolean} isBot : True if this is the bot
 * @param {IrcEventBroker} eventBroker
 * @param {IdentGenerator} identGenerator
 */
function BridgedClient(ircUser, matrixUser, isBot, eventBroker, identGenerator) {
    this.matrixUser = matrixUser;
    this.setIrcUserInfo(ircUser);
    this._eventBroker = eventBroker;
    this._identGenerator = identGenerator;

    this.isBot = Boolean(isBot);
    this.disabled = this.isBot && !ircUser.server.isBotEnabled();
    this.lastActionTs = Date.now();
    this.inst = null;
    this.instCreationFailed = false;
    this.explicitDisconnect = false;
    this.chanList = [];
    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 + "> ";
    if (this.userId) {
        prefix += "(" + this.userId + ") ";
    }
    this.log = {
        debug: function() {
            arguments[0] = prefix + arguments[0];
            log.debug.apply(log, arguments);
        },
        info: function() {
            arguments[0] = prefix + arguments[0];
            log.info.apply(log, arguments);
        },
        error: function() {
            arguments[0] = prefix + arguments[0];
            log.error.apply(log, arguments);
        }
    };
}
util.inherits(BridgedClient, EventEmitter);

BridgedClient.prototype.setIrcUserInfo = function(ircUser) {
    this.ircUser = ircUser;
    this.server = ircUser.server;
    this.nick = ircUser.nick;
    this.password = ircUser.password ? ircUser.password : ircUser.server.config.password;
    this.userId = this.matrixUser ? this.matrixUser.getId() : ircUser.getUsername();
};

BridgedClient.prototype.isDead = function() {
    if (this.instCreationFailed || (this.inst && this.inst.dead)) {
        return true;
    }
    return false;
};

BridgedClient.prototype.toString = function() {
    let domain = this.server ? this.server.domain : "NO_DOMAIN";
    return `${this.nick}@${domain}#${this._id}~${this.userId}`;
};

/**
 * @return {ConnectionInstance} A new connected connection instance.
 */
BridgedClient.prototype.connect = function() {
    var self = this;
    var server = this.server;
    var defer = promiseutil.defer();

    this._identGenerator.getIrcNames(this.ircUser, this.matrixUser).then(function(nameInfo) {
        self.log.info(
            "Connecting to IRC server %s as %s (user=%s)",
            server.domain, nameInfo.nick, nameInfo.username
        );

        return ConnectionInstance.create(server, {
            nick: nameInfo.nick,
            username: nameInfo.username,
            realname: nameInfo.realname,
            password: <PASSWORD>
        }, function(inst) {
            self._onConnectionCreated(inst, nameInfo);
        });
    }).done(function(connInst) {
        self.inst = connInst;
        self.unsafeClient = connInst.client;
        self.log.debug("connected!");
        self.emit("client-connected", self);
        // we may have been assigned a different nick, so update it from source
        self.nick = connInst.client.nick;
        self._connectDefer.resolve();
        self._keepAlive();
        connInst.client.addListener("registered", function() {
            var oldNick = self.nick;
            if (oldNick !== self.unsafeClient.nick) {
                self.log.info(
                    "REGISTERED: Nick changed from '" + oldNick + "' to '" +
                    self.unsafeClient.nick + "'."
                );
                self.nick = self.unsafeClient.nick;
                self.emit("nick-change", self, oldNick, self.unsafeClient.nick);
            }
        });
        connInst.client.addListener("nick", function(old, newNick) {
            if (old === self.nick) {
                self.log.info(
                    "NICK: Nick changed from '" + old + "' to '" + newNick + "'."
                );
                self.nick = newNick;
                self.emit("nick-change", self, old, newNick);
            }
        });
        defer.resolve(connInst);
    }, function(e) {
        self.log.debug("Failed to connect.");
        self.instCreationFailed = true;
        defer.reject(e);
    });

    return defer.promise;
};

BridgedClient.prototype.disconnect = function(reason) {<commit_msg>Send IRC errors to Matrix users<commit_after>"use strict";

var Promise = require("bluebird");
var promiseutil = require("../promiseutil");
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var ident = require("./ident");
var ConnectionInstance = require("./ConnectionInstance");
var IrcRoom = require("../models/IrcRoom");
var log = require("../logging").get("irc-client");

// The length of time to wait before trying to join the channel again
var JOIN_TIMEOUT_MS = 15 * 1000; // 15s

/**
 * Create a new bridged IRC client.
 * @constructor
 * @param {Object} ircUser : The IRC user to create a connection for.
 * @param {Object} matrixUser : Optional. The matrix user this virtual IRC user.
 * @param {boolean} isBot : True if this is the bot
 * @param {IrcEventBroker} eventBroker
 * @param {IdentGenerator} identGenerator
 */
function BridgedClient(ircUser, matrixUser, isBot, eventBroker, identGenerator) {
    this.matrixUser = matrixUser;
    this.setIrcUserInfo(ircUser);
    this._eventBroker = eventBroker;
    this._identGenerator = identGenerator;

    this.isBot = Boolean(isBot);
    this.disabled = this.isBot && !ircUser.server.isBotEnabled();
    this.lastActionTs = Date.now();
    this.inst = null;
    this.instCreationFailed = false;
    this.explicitDisconnect = false;
    this.chanList = [];
    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 + "> ";
    if (this.userId) {
        prefix += "(" + this.userId + ") ";
    }
    this.log = {
        debug: function() {
            arguments[0] = prefix + arguments[0];
            log.debug.apply(log, arguments);
        },
        info: function() {
            arguments[0] = prefix + arguments[0];
            log.info.apply(log, arguments);
        },
        error: function() {
            arguments[0] = prefix + arguments[0];
            log.error.apply(log, arguments);
        }
    };
}
util.inherits(BridgedClient, EventEmitter);

BridgedClient.prototype.setIrcUserInfo = function(ircUser) {
    this.ircUser = ircUser;
    this.server = ircUser.server;
    this.nick = ircUser.nick;
    this.password = <PASSWORD> ? <PASSWORD> : <PASSWORD>;
    this.userId = this.matrixUser ? this.matrixUser.getId() : ircUser.getUsername();
};

BridgedClient.prototype.isDead = function() {
    if (this.instCreationFailed || (this.inst && this.inst.dead)) {
        return true;
    }
    return false;
};

BridgedClient.prototype.toString = function() {
    let domain = this.server ? this.server.domain : "NO_DOMAIN";
    return `${this.nick}@${domain}#${this._id}~${this.userId}`;
};

/**
 * @return {ConnectionInstance} A new connected connection instance.
 */
BridgedClient.prototype.connect = function() {
    var self = this;
    var server = this.server;
    var defer = promiseutil.defer();

    this._identGenerator.getIrcNames(this.ircUser, this.matrixUser).then(function(nameInfo) {
        self.log.info(
            "Connecting to IRC server %s as %s (user=%s)",
            server.domain, nameInfo.nick, nameInfo.username
        );

        return ConnectionInstance.create(server, {
            nick: nameInfo.nick,
            username: nameInfo.username,
            realname: nameInfo.realname,
            password: <PASSWORD>
        }, function(inst) {
            self._onConnectionCreated(inst, nameInfo);
        });
    }).done(function(connInst) {
        self.inst = connInst;
        self.unsafeClient = connInst.client;
        self.log.debug("connected!");
        self.emit("client-connected", self);
        // we may have been assigned a different nick, so update it from source
        self.nick = connInst.client.nick;
        self._connectDefer.resolve();
        self._keepAlive();
        connInst.client.addListener("registered", function() {
            var oldNick = self.nick;
            if (oldNick !== self.unsafeClient.nick) {
                self.log.info(
                    "REGISTERED: Nick changed from '" + oldNick + "' to '" +
                    self.unsafeClient.nick + "'."
                );
                self.nick = self.unsafeClient.nick;
                self.emit("nick-change", self, oldNick, self.unsafeClient.nick);
            }
        });
        connInst.client.addListener("nick", function(old, newNick) {
            if (old === self.nick) {
                self.log.info(
                    "NICK: Nick changed from '" + old + "' to '" + newNick + "'."
                );
                self.nick = newNick;
                self.emit("nick-change", self, old, newNick);
            }
        });
        connInst.client.addListener("error", function(err) {
            if (!err || !err.command || connInst.dead) {
                return;
            }
            var msg = "Received an error on " + self.server.domain + ": " + err.command + "\n";
            msg += JSON.stringify(err.args);
            self._eventBroker.sendMetadata(self, msg);
        });
        defer.resolve(connInst);
    }, function(e) {
        self.log.debug("Failed to connect.");
        self.instCreationFailed = true;
        defer.reject(e);
    });

    return defer.promise;
};

BridgedClient.prototype.disconnect = function(reason) {
{'fraction_non_alphanumeric': 0.1382938026013772, 'fraction_numerical': 0.0036342769701606732, 'mean_word_length': 2.4240340537000655, 'pattern_counts': {'":': 1, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4406195', 'n_tokens_mistral': 3113, 'n_tokens_neox': 3010, 'n_words': 675}