thelounge/src/client.js

623 lines
14 KiB
JavaScript
Raw Normal View History

"use strict";
2018-01-11 12:33:36 +01:00
const _ = require("lodash");
const colors = require("colors/safe");
const pkg = require("../package.json");
const Chan = require("./models/chan");
const crypto = require("crypto");
const Msg = require("./models/msg");
const Network = require("./models/network");
const ircFramework = require("irc-framework");
const Helper = require("./helper");
const UAParser = require("ua-parser-js");
2014-09-13 23:29:45 +02:00
module.exports = Client;
2018-01-11 12:33:36 +01:00
let id = 0;
const events = [
"away",
"connection",
"unhandled",
2017-04-22 14:51:21 +02:00
"banlist",
2014-09-13 23:29:45 +02:00
"ctcp",
2017-09-19 17:22:50 +02:00
"chghost",
2014-09-13 23:29:45 +02:00
"error",
2016-02-12 12:24:13 +01:00
"invite",
2014-09-13 23:29:45 +02:00
"join",
"kick",
"mode",
"motd",
"message",
"names",
"nick",
"part",
"quit",
"topic",
"welcome",
"list",
"whois",
2014-09-13 23:29:45 +02:00
];
2018-01-11 12:33:36 +01:00
const inputs = [
2017-04-24 12:40:53 +02:00
"ban",
"ctcp",
2016-03-06 10:24:56 +01:00
"msg",
"part",
"rejoin",
2014-09-13 23:29:45 +02:00
"action",
2016-11-19 09:24:39 +01:00
"away",
2014-09-13 23:29:45 +02:00
"connect",
2016-04-14 10:56:02 +02:00
"disconnect",
2014-09-13 23:29:45 +02:00
"invite",
"kick",
"mode",
"nick",
2014-09-13 23:29:45 +02:00
"notice",
"query",
2014-09-13 23:29:45 +02:00
"quit",
"raw",
"topic",
2016-05-29 04:07:34 +02:00
"list",
"whois",
].reduce(function(plugins, name) {
2018-01-11 12:33:36 +01:00
const plugin = require(`./plugins/inputs/${name}`);
plugin.commands.forEach((command) => plugins[command] = plugin);
return plugins;
}, {});
2014-09-13 23:29:45 +02:00
function Client(manager, name, config = {}) {
2014-09-13 23:29:45 +02:00
_.merge(this, {
awayMessage: config.awayMessage || "",
lastActiveChannel: -1,
attachedClients: {},
2014-09-13 23:29:45 +02:00
config: config,
id: id++,
2014-09-16 21:47:01 +02:00
name: name,
2014-09-13 23:29:45 +02:00
networks: [],
sockets: manager.sockets,
manager: manager,
2014-09-13 23:29:45 +02:00
});
2016-05-31 23:28:31 +02:00
2018-01-11 12:33:36 +01:00
const client = this;
2016-05-31 23:28:31 +02:00
2018-01-11 12:33:36 +01:00
let delay = 0;
(client.config.networks || []).forEach((n) => {
setTimeout(function() {
client.connect(n);
}, delay);
delay += 1000;
});
2016-04-16 13:32:38 +02:00
if (typeof client.config.sessions !== "object") {
client.config.sessions = {};
}
2017-07-10 21:47:03 +02:00
_.forOwn(client.config.sessions, (session) => {
if (session.pushSubscription) {
this.registerPushSubscription(session, session.pushSubscription, true);
}
});
if (client.name) {
log.info(`User ${colors.bold(client.name)} loaded`);
}
2014-09-13 23:29:45 +02:00
}
Client.prototype.emit = function(event, data) {
if (this.sockets !== null) {
this.sockets.in(this.id).emit(event, data);
}
2014-09-13 19:18:42 +02:00
};
2014-09-13 23:29:45 +02:00
2016-10-09 10:54:44 +02:00
Client.prototype.find = function(channelId) {
2018-01-11 12:33:36 +01:00
let network = null;
let chan = null;
2018-01-11 12:33:36 +01:00
for (const i in this.networks) {
const n = this.networks[i];
2016-10-09 10:54:44 +02:00
chan = _.find(n.channels, {id: channelId});
2014-09-13 23:29:45 +02:00
if (chan) {
network = n;
break;
}
}
2014-09-13 23:29:45 +02:00
if (network && chan) {
return {
network: network,
chan: chan,
2014-09-13 23:29:45 +02:00
};
}
2016-10-09 10:54:44 +02:00
return false;
2014-09-13 23:29:45 +02:00
};
Client.prototype.connect = function(args) {
2018-01-11 12:33:36 +01:00
const client = this;
const nick = args.nick || "lounge-user";
let webirc = null;
let channels = [];
2016-06-19 19:12:42 +02:00
if (args.channels) {
2018-01-11 12:33:36 +01:00
let badName = false;
2016-06-19 19:12:42 +02:00
args.channels.forEach((chan) => {
2016-06-19 19:12:42 +02:00
if (!chan.name) {
badName = true;
return;
}
channels.push(new Chan({
2017-04-01 10:33:17 +02:00
name: chan.name,
key: chan.key || "",
2018-01-30 17:46:34 +01:00
type: chan.type,
}));
});
2016-06-19 19:12:42 +02:00
if (badName && client.name) {
log.warn("User '" + client.name + "' on network '" + args.name + "' has an invalid channel which has been ignored");
}
// `join` is kept for backwards compatibility when updating from versions <2.0
// also used by the "connect" window
} else if (args.join) {
channels = args.join
2016-10-09 10:54:44 +02:00
.replace(/,/g, " ")
2016-06-19 19:12:42 +02:00
.split(/\s+/g)
.map(function(chan) {
return new Chan({
name: chan,
2016-06-19 19:12:42 +02:00
});
});
}
args.ip = args.ip || (client.config && client.config.ip) || client.ip;
args.hostname = args.hostname || (client.config && client.config.hostname) || client.hostname;
2018-01-11 12:33:36 +01:00
const network = new Network({
name: args.name || (Helper.config.displayNetwork ? "" : Helper.config.defaults.name) || "",
host: args.host || "",
port: parseInt(args.port, 10) || (args.tls ? 6697 : 6667),
tls: !!args.tls,
password: args.password,
username: args.username || nick.replace(/[^a-zA-Z0-9]/g, ""),
realname: args.realname || "The Lounge User",
2016-04-03 07:12:49 +02:00
commands: args.commands,
ip: args.ip,
hostname: args.hostname,
channels: channels,
});
2016-05-12 13:15:38 +02:00
network.setNick(nick);
client.networks.push(network);
client.emit("network", {
networks: [network.getFilteredClone(this.lastActiveChannel, -1)],
});
2018-01-11 12:33:36 +01:00
if (Helper.config.lockNetwork) {
2016-02-21 13:02:35 +01:00
// This check is needed to prevent invalid user configurations
2018-01-11 12:33:36 +01:00
if (!Helper.config.public && args.host && args.host.length > 0 && args.host !== Helper.config.defaults.host) {
network.channels[0].pushMessage(client, new Msg({
type: Msg.Type.ERROR,
text: "Hostname you specified is not allowed.",
}), true);
2016-02-21 13:02:35 +01:00
return;
}
2018-01-11 12:33:36 +01:00
network.host = Helper.config.defaults.host;
network.port = Helper.config.defaults.port;
network.tls = Helper.config.defaults.tls;
2016-02-21 13:02:35 +01:00
}
if (network.host.length === 0) {
network.channels[0].pushMessage(client, new Msg({
type: Msg.Type.ERROR,
text: "You must specify a hostname to connect.",
}), true);
2016-02-21 13:02:35 +01:00
return;
}
2018-01-11 12:33:36 +01:00
if (Helper.config.webirc && network.host in Helper.config.webirc) {
if (!args.hostname) {
args.hostname = args.ip;
}
2016-04-03 07:12:49 +02:00
if (args.ip) {
2018-01-11 12:33:36 +01:00
if (Helper.config.webirc[network.host] instanceof Function) {
webirc = Helper.config.webirc[network.host](client, args);
2016-04-03 07:12:49 +02:00
} else {
webirc = {
2018-01-11 12:33:36 +01:00
password: Helper.config.webirc[network.host],
username: pkg.name,
2016-04-03 07:12:49 +02:00
address: args.ip,
hostname: args.hostname,
2016-04-03 07:12:49 +02:00
};
}
} else {
log.warn("Cannot find a valid WEBIRC configuration for " + nick
+ "!" + network.username + "@" + network.host);
}
}
network.irc = new ircFramework.Client({
2017-12-31 10:20:20 +01:00
version: false, // We handle it ourselves
host: network.host,
port: network.port,
nick: nick,
2018-01-11 12:33:36 +01:00
username: Helper.config.useHexIp ? Helper.ip2hex(args.ip) : network.username,
gecos: network.realname,
password: network.password,
tls: network.tls,
2018-01-11 12:33:36 +01:00
outgoing_addr: Helper.config.bind,
rejectUnauthorized: false,
2017-09-19 17:22:50 +02:00
enable_chghost: true,
enable_echomessage: true,
2016-04-13 09:10:44 +02:00
auto_reconnect: true,
2016-07-02 20:45:41 +02:00
auto_reconnect_wait: 10000 + Math.floor(Math.random() * 1000), // If multiple users are connected to the same network, randomize their reconnections a little
auto_reconnect_max_retries: 360, // At least one hour (plus timeouts) worth of reconnections
2016-04-03 07:12:49 +02:00
webirc: webirc,
2014-09-13 23:29:45 +02:00
});
network.irc.requestCap([
"znc.in/self-message", // Legacy echo-message for ZNc
]);
events.forEach((plugin) => {
2018-01-11 12:33:36 +01:00
require(`./plugins/irc-events/${plugin}`).apply(client, [
network.irc,
network,
]);
});
network.irc.connect();
client.save();
2014-09-13 23:29:45 +02:00
};
Client.prototype.generateToken = function(callback) {
crypto.randomBytes(64, (err, buf) => {
2016-10-09 10:54:44 +02:00
if (err) {
throw err;
}
callback(buf.toString("hex"));
2016-05-31 23:28:31 +02:00
});
};
Client.prototype.calculateTokenHash = function(token) {
return crypto.createHash("sha512").update(token).digest("hex");
};
Client.prototype.updateSession = function(token, ip, request) {
const client = this;
const agent = UAParser(request.headers["user-agent"] || "");
let friendlyAgent = "";
2017-08-13 20:37:12 +02:00
if (agent.browser.name) {
friendlyAgent = `${agent.browser.name} ${agent.browser.major}`;
} else {
friendlyAgent = "Unknown browser";
}
2017-08-13 20:37:12 +02:00
if (agent.os.name) {
2017-08-08 21:46:55 +02:00
friendlyAgent += ` on ${agent.os.name} ${agent.os.version}`;
}
client.config.sessions[token] = _.assign(client.config.sessions[token], {
lastUse: Date.now(),
ip: ip,
agent: friendlyAgent,
});
client.manager.updateUser(client.name, {
sessions: client.config.sessions,
});
};
2016-05-31 23:28:31 +02:00
Client.prototype.setPassword = function(hash, callback) {
2018-01-11 12:33:36 +01:00
const client = this;
2016-05-31 23:28:31 +02:00
client.manager.updateUser(client.name, {
password: hash,
}, function(err) {
if (err) {
return callback(false);
}
2016-05-31 23:28:31 +02:00
client.config.password = hash;
return callback(true);
2016-05-31 23:28:31 +02:00
});
};
2014-09-13 23:29:45 +02:00
Client.prototype.input = function(data) {
2018-01-11 12:33:36 +01:00
const client = this;
data.text.split("\n").forEach((line) => {
data.text = line;
client.inputLine(data);
});
};
Client.prototype.inputLine = function(data) {
2018-01-11 12:33:36 +01:00
const client = this;
const target = client.find(data.target);
if (!target) {
return;
}
// Sending a message to a channel is higher priority than merely opening one
// so that reloading the page will open this channel
this.lastActiveChannel = target.chan.id;
2016-03-06 10:24:56 +01:00
2018-01-11 12:33:36 +01:00
let text = data.text;
2016-03-06 10:24:56 +01:00
// This is either a normal message or a command escaped with a leading '/'
if (text.charAt(0) !== "/" || text.charAt(1) === "/") {
if (target.chan.type === Chan.Type.LOBBY) {
target.chan.pushMessage(this, new Msg({
type: Msg.Type.ERROR,
text: "Messages can not be sent to lobbies.",
}));
return;
}
2016-03-06 10:24:56 +01:00
text = "say " + text.replace(/^\//, "");
} else {
text = text.substr(1);
2014-09-13 23:29:45 +02:00
}
2016-03-06 10:24:56 +01:00
2018-01-11 12:33:36 +01:00
const args = text.split(" ");
const cmd = args.shift().toLowerCase();
2016-03-06 10:24:56 +01:00
2018-01-11 12:33:36 +01:00
const irc = target.network.irc;
let connected = irc && irc.connection && irc.connection.connected;
if (cmd in inputs) {
2018-01-11 12:33:36 +01:00
const plugin = inputs[cmd];
if (connected || plugin.allowDisconnected) {
connected = true;
plugin.input.apply(client, [target.network, target.chan, cmd, args]);
}
} else if (connected) {
irc.raw(text);
}
if (!connected) {
target.chan.pushMessage(this, new Msg({
type: Msg.Type.ERROR,
text: "You are not connected to the IRC network, unable to send your command.",
}));
2016-03-06 10:24:56 +01:00
}
2014-09-13 23:29:45 +02:00
};
Client.prototype.more = function(data) {
const client = this;
const target = client.find(data.target);
2014-09-13 23:29:45 +02:00
if (!target) {
return null;
2014-09-13 23:29:45 +02:00
}
const chan = target.chan;
let messages = [];
let index = 0;
// If client requests -1, send last 100 messages
if (data.lastId < 0) {
index = chan.messages.length;
} else {
index = chan.messages.findIndex((val) => val.id === data.lastId);
}
// If requested id is not found, an empty array will be sent
if (index > 0) {
messages = chan.messages.slice(Math.max(0, index - 100), index);
}
return {
2014-09-13 23:29:45 +02:00
chan: chan.id,
messages: messages,
};
2014-09-13 23:29:45 +02:00
};
Client.prototype.open = function(socketId, target) {
// Opening a window like settings
if (target === null) {
2017-07-10 21:47:03 +02:00
this.attachedClients[socketId].openChannel = -1;
return;
}
target = this.find(target);
if (!target) {
return;
}
target.chan.firstUnread = 0;
target.chan.unread = 0;
2017-09-03 17:57:07 +02:00
target.chan.highlight = 0;
2017-07-10 21:47:03 +02:00
this.attachedClients[socketId].openChannel = target.chan.id;
this.lastActiveChannel = target.chan.id;
this.emit("open", target.chan.id);
};
2014-09-24 21:42:36 +02:00
Client.prototype.sort = function(data) {
const order = data.order;
2014-09-24 21:42:36 +02:00
if (!_.isArray(order)) {
return;
}
2014-09-24 21:42:36 +02:00
switch (data.type) {
2014-09-24 21:42:36 +02:00
case "networks":
this.networks.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
// Sync order to connected clients
this.emit("sync_sort", {order: this.networks.map((obj) => obj.id), type: data.type, target: data.target});
2014-09-24 21:42:36 +02:00
break;
2018-01-11 12:33:36 +01:00
case "channels": {
const network = _.find(this.networks, {id: data.target});
2014-09-24 21:42:36 +02:00
if (!network) {
return;
}
network.channels.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
// Sync order to connected clients
this.emit("sync_sort", {order: network.channels.map((obj) => obj.id), type: data.type, target: data.target});
2014-09-24 21:42:36 +02:00
break;
}
2018-01-11 12:33:36 +01:00
}
this.save();
2014-09-24 21:42:36 +02:00
};
Client.prototype.names = function(data) {
2018-01-11 12:33:36 +01:00
const client = this;
const target = client.find(data.target);
if (!target) {
return;
}
client.emit("names", {
id: target.chan.id,
2017-11-16 21:32:03 +01:00
users: target.chan.getSortedUsers(target.network.irc),
});
};
2017-08-30 19:26:45 +02:00
Client.prototype.quit = function(signOut) {
const sockets = this.sockets.sockets;
const room = sockets.adapter.rooms[this.id];
if (room && room.sockets) {
for (const user in room.sockets) {
const socket = sockets.connected[user];
if (socket) {
2017-08-30 19:26:45 +02:00
if (signOut) {
socket.emit("sign-out");
}
socket.disconnect();
}
2014-09-29 17:49:38 +02:00
}
}
this.networks.forEach((network) => {
if (network.irc) {
2017-08-18 21:04:16 +02:00
network.irc.quit(Helper.config.leaveMessage);
}
network.destroy();
2014-09-13 23:29:45 +02:00
});
2014-09-13 19:18:42 +02:00
};
2014-10-11 22:44:56 +02:00
2017-07-10 21:47:03 +02:00
Client.prototype.clientAttach = function(socketId, token) {
2018-01-11 12:33:36 +01:00
const client = this;
let save = false;
if (client.awayMessage && _.size(client.attachedClients) === 0) {
client.networks.forEach(function(network) {
// Only remove away on client attachment if
// there is no away message on this network
if (!network.awayMessage) {
network.irc.raw("AWAY");
}
});
}
2017-07-10 21:47:03 +02:00
client.attachedClients[socketId] = {
token: token,
openChannel: client.lastActiveChannel,
2017-07-10 21:47:03 +02:00
};
// Update old networks to store ip and hostmask
client.networks.forEach((network) => {
if (!network.ip) {
save = true;
network.ip = (client.config && client.config.ip) || client.ip;
}
if (!network.hostname) {
2018-01-11 12:33:36 +01:00
const hostmask = (client.config && client.config.hostname) || client.hostname;
if (hostmask) {
save = true;
network.hostmask = hostmask;
}
}
});
if (save) {
client.save();
}
};
Client.prototype.clientDetach = function(socketId) {
const client = this;
delete this.attachedClients[socketId];
if (client.awayMessage && _.size(client.attachedClients) === 0) {
client.networks.forEach(function(network) {
// Only set away on client deattachment if
// there is no away message on this network
if (!network.awayMessage) {
network.irc.raw("AWAY", client.awayMessage);
}
});
}
};
2017-07-10 21:47:03 +02:00
Client.prototype.registerPushSubscription = function(session, subscription, noSave) {
if (!_.isPlainObject(subscription) || !_.isPlainObject(subscription.keys)
|| typeof subscription.endpoint !== "string" || !/^https?:\/\//.test(subscription.endpoint)
|| typeof subscription.keys.p256dh !== "string" || typeof subscription.keys.auth !== "string") {
session.pushSubscription = null;
return;
}
const data = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth,
},
2017-07-10 21:47:03 +02:00
};
session.pushSubscription = data;
if (!noSave) {
this.manager.updateUser(this.name, {
sessions: this.config.sessions,
2017-07-10 21:47:03 +02:00
});
}
return data;
};
Client.prototype.unregisterPushSubscription = function(token) {
this.config.sessions[token].pushSubscription = null;
this.manager.updateUser(this.name, {
sessions: this.config.sessions,
2017-07-10 21:47:03 +02:00
});
};
2016-11-19 22:00:54 +01:00
Client.prototype.save = _.debounce(function SaveClient() {
if (Helper.config.public) {
2014-10-12 07:15:03 +02:00
return;
}
2014-11-09 17:01:22 +01:00
2016-11-19 22:00:54 +01:00
const client = this;
const json = {};
json.networks = this.networks.map((n) => n.export());
client.manager.updateUser(client.name, json);
2016-11-19 22:00:54 +01:00
}, 1000, {maxWait: 10000});