safesupport-bot/dist/bot.js
2020-09-05 18:12:33 -04:00

632 lines
21 KiB
JavaScript

"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var fs = _interopRequireWildcard(require("fs"));
var os = _interopRequireWildcard(require("os"));
var path = _interopRequireWildcard(require("path"));
var util = _interopRequireWildcard(require("util"));
var _nodeLocalstorage = require("node-localstorage");
var matrix = _interopRequireWildcard(require("matrix-js-sdk"));
var _logger = _interopRequireDefault(require("./logger"));
var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"));
global.Olm = require("olm");
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
class OcrccBot {
constructor(botConfig) {
this.config = botConfig;
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
this.joinedRooms = [];
}
createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
const localStoragePath = path.resolve(path.join(dir, storageLoc));
return new _nodeLocalstorage.LocalStorage(localStoragePath);
}
sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
this.sendMessage(roomId, content);
}
async sendNotice(roomId, message) {
_logger.default.log("info", `SENDING *NOTICE*: ${message}`);
try {
await this.client.sendNotice(roomId, message);
} catch (err) {
switch (err["name"]) {
case "UnknownDeviceError":
Object.keys(err.devices).forEach(userId => {
Object.keys(err.devices[userId]).map(async deviceId => {
try {
await this.client.setDeviceVerified(userId, deviceId, true);
} catch (err) {
_logger.default.log("error", `ERROR VERIFYING DEVICE: ${err}`);
}
});
});
await this.sendNotice(roomId, message);
default:
_logger.default.log("error", `ERROR SENDING *NOTICE*: ${err}`);
break;
}
}
}
async sendMessage(roomId, content) {
try {
await this.client.sendMessage(roomId, content);
_logger.default.log("info", `SENT MESSAGE: ${content.body}`);
} catch (err) {
switch (err["name"]) {
case "UnknownDeviceError":
Object.keys(err.devices).forEach(userId => {
Object.keys(err.devices[userId]).map(async deviceId => {
try {
await this.client.setDeviceVerified(userId, deviceId, true);
} catch (err) {
_logger.default.log("error", `ERROR VERIFYING DEVICE: ${err}`);
}
});
});
await this.sendMessage(roomId, content);
default:
_logger.default.log("error", `ERROR SENDING MESSAGE ${content.body}: ${err}`);
break;
}
}
}
inviteUserToRoom(roomId, member) {
try {
this.client.invite(roomId, member);
} catch (err) {
this.handleBotCrash(roomId, err);
}
}
kickUserFromRoom(roomId, member) {
try {
this.client.kick(roomId, member, this.config.KICK_REASON);
} catch (err) {
this.handleBotCrash(roomId, err);
_logger.default.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
}
}
async inviteFacilitators(roomId) {
this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = [];
try {
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const members = Object.keys(roomMembers["joined"]);
members.forEach(memberId => {
const user = this.client.getUser(memberId);
if (user && user.presence !== "offline" && memberId !== this.config.BOT_USERID) {
invitations.push(memberId);
this.inviteUserToRoom(roomId, memberId);
}
});
if (invitations.length > 0) {
this.localStorage.setItem(`${roomId}-invitations`, invitations);
} else {
_logger.default.log('info', "NO FACILITATORS ONLINE");
this.sendNotice(roomId, "CHAT_OFFLINE");
}
} catch (err) {
this.handleBotCrash(roomId, err);
_logger.default.log("error", `ERROR GETTING FACILITATORS: ${err}`);
}
}
async uninviteFacilitators(roomId) {
this.localStorage.removeItem(`${roomId}-waiting`);
try {
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
if (!roomMembersIds || !facilitatorsIds) return;
facilitatorsIds.forEach(f => {
if (!roomMembersIds.includes(f)) {
this.kickUserFromRoom(roomId, f);
}
});
} catch (err) {
this.handleBotCrash(roomId, err);
_logger.default.log("ERROR UNINVITING FACILITATORS", err);
}
}
handleBotCrash(roomId, error) {
if (roomId) {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
}
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`);
}
handleMessageEvent(event) {
const content = event.getContent(); // do nothing if there's no content
if (!content) {
return;
} // bot commands
if (content.body.startsWith("!bot")) {
return this.handleBotCommand(event);
} // write to transcript
if (this.config.CAPTURE_TRANSCRIPTS) {
return this.writeToTranscript(event);
}
}
writeToTranscript(event) {
try {
const sender = event.getSender();
const roomId = event.getRoomId();
const content = event.getContent();
const date = event.getDate();
const time = date.toLocaleTimeString("en-GB", {
timeZone: "America/New_York"
});
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
if (!filepath) {
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
}
const message = `${sender} [${time}]: ${content.body}\n`;
fs.appendFileSync(filepath, message, "utf8");
} catch (err) {
_logger.default.log("error", `ERROR APPENDING TO TRANSCRIPT FILE: ${err}`);
}
}
handleBotCommand(event) {
const botCommands = [{
keyword: 'transcript',
function: (senderId, roomId) => {
this.sendTranscript(senderId, roomId);
}
}, {
keyword: 'delete transcript',
function: (senderId, roomId) => {
this.deleteTranscript(senderId, roomId);
}
}, {
keyword: 'say',
function: (senderId, roomId, message) => {
this.sendTextMessage(roomId, message, senderId);
}
}, {
keyword: 'hi',
function: (senderId, roomId) => {
const responses = ["Hi!", "Hello", "Hey :)", "Hi there", "Bleep bloop"];
const message = responses[Math.floor(Math.random() * responses.length)];
this.sendTextMessage(roomId, message, senderId);
}
}];
try {
const senderId = event.getSender();
const roomId = event.getRoomId();
const content = event.getContent();
const commandText = content.body.substring("!bot".length).trim();
const command = botCommands.find(c => commandText.startsWith(c.keyword));
if (!command) {
this.sendTextMessage(roomId, `Sorry, I don't know that command. I'm not a very smart bot.`, senderId);
}
const args = commandText.substring(command.keyword.length).trim();
command.function(senderId, roomId, args);
} catch (err) {
_logger.default.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
}
}
async leaveEmptyRooms(senderId) {
try {
const roomData = await this.client.getJoinedRooms();
const joinedRoomsIds = roomData["joined_rooms"];
joinedRoomsIds.forEach(async roomId => {
const room = this.client.getRoom(roomId);
if (room && room.getJoinedMemberCount() === 1) {
try {
_logger.default.log('info', "LEAVING EMPTY ROOM => " + roomId);
await this.client.leave(roomId);
} catch (err) {
_logger.default.log('error', "ERROR LEAVING EMPTY ROOM => " + err);
}
}
});
} catch (err) {
_logger.default.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
}
}
async sendTranscript(senderId, roomId) {
try {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
}
if (this.client.isRoomEncrypted(roomId)) {
let encryptInfo;
const filename = path.basename(transcriptFile) || "Transcript";
const data = fs.readFileSync(transcriptFile);
const encryptResult = await _encryptAttachment.default.encryptAttachment(data);
const buffer = Buffer.from(encryptResult.data);
encryptInfo = encryptResult.info;
const url = await this.client.uploadContent(buffer, {
rawResponse: false,
name: filename
});
encryptInfo.url = url.content_uri;
encryptInfo.mimetype = 'text/plain';
const content = {
msgtype: "m.file",
body: filename,
info: {
mimetype: 'text/plain'
},
file: encryptInfo,
url: url.content_uri,
showToUser: senderId,
mimetype: 'text/plain'
};
this.sendMessage(roomId, content);
} else {
const filename = path.basename(transcriptFile) || "Transcript";
const file = fs.readFileSync(transcriptFile);
const stats = fs.statSync(transcriptFile);
const url = await this.client.uploadContent(file, {
rawResponse: false,
name: filename
});
_logger.default.log('info', url);
const content = {
msgtype: "m.file",
body: filename,
info: {
size: stats.size,
mimetype: 'text/plain'
},
url: url.content_uri,
showToUser: senderId,
mimetype: 'text/plain'
};
this.sendMessage(roomId, content);
}
} catch (err) {
_logger.default.log("error", `ERROR UPLOADING CONTENT: ${err}`);
this.sendTextMessage(roomId, "There was an error uploading the transcript.", senderId);
}
}
deleteTranscript(senderId, roomId) {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
return this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
}
fs.unlink(transcriptFile, err => {
if (err) {
_logger.default.log('error', "UNABLE TO DELETE TRANSCRIPT FILE => " + transcriptFile);
_logger.default.log('error', err);
return this.sendTextMessage(roomId, `There was an error deleting the transcript: ${err}`, senderId);
}
this.localStorage.removeItem(`${roomId}-transcript`);
_logger.default.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile);
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
});
}
async deleteOldDevices() {
const currentDeviceId = this.client.getDeviceId();
const deviceData = await this.client.getDevices();
const allDeviceIds = deviceData.devices.map(d => d.device_id);
const oldDevices = allDeviceIds.filter(id => id !== currentDeviceId);
try {
await this.client.deleteMultipleDevices(oldDevices);
} catch (err) {
_logger.default.log("info", "RETRYING DELETE OLD DEVICES WITH AUTH");
const auth = {
session: err.data.session,
type: "m.login.password",
user: this.config.BOT_USERID,
identifier: {
type: "m.id.user",
user: this.config.BOT_USERID
},
password: this.config.BOT_PASSWORD
};
await this.client.deleteMultipleDevices(oldDevices, auth);
_logger.default.log("info", "DELETED OLD DEVICES");
}
}
async trackJoinedRooms() {
const roomData = await this.client.getJoinedRooms();
this.joinedRooms = roomData["joined_rooms"];
_logger.default.log("info", "JOINED ROOMS => " + this.joinedRooms);
}
async setMembershipListeners() {
// Automatically accept all room invitations
this.client.on("RoomMember.membership", async (event, member) => {
if (member.membership === "invite" && member.userId === this.config.BOT_USERID && !this.joinedRooms.includes(member.roomId)) {
try {
const roomData = await this.client.getJoinedRooms();
const joinedRooms = roomData["joined_rooms"];
if (!joinedRooms.includes(member.roomId)) {
const room = await this.client.joinRoom(member.roomId);
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
const inviteDate = event.getDate();
const chatDate = inviteDate.toLocaleDateString();
const chatTime = inviteDate.toLocaleTimeString();
const roomId = room.roomId.split(':')[0];
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
this.inviteFacilitators(room.roomId);
}
} catch (err) {
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
}
}
if (member.membership === "join" && member.userId !== this.config.BOT_USERID && this.localStorage.getItem(`${member.roomId}-waiting`)) {
// make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const members = Object.keys(roomMembers["joined"]);
const isFacilitator = members.includes(member.userId);
if (isFacilitator) {
// made facilitator a moderator in the room
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
const event = {
getType: () => {
return "m.room.power_levels";
},
getContent: () => {
return {
users: {
[this.config.BOT_USERID]: 100,
[member.userId]: 50
}
};
}
};
this.client.setPowerLevel(member.roomId, member.userId, 50, event); // send notification to Support Chat Notifications room
const currentDate = new Date();
const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0];
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); // send notification to chat room
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations
this.uninviteFacilitators(member.roomId); // set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) {
const currentDate = new Date();
const dateOpts = {
year: "numeric",
month: "short",
day: "numeric"
};
const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
const chatTime = currentDate.toLocaleTimeString("en-GB", {
timeZone: "America/New_York"
});
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
const filepath = path.resolve(path.join("transcripts", filename));
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
}
}
}
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
// ensure bot is still in the room
const roomData = await this.client.getJoinedRooms();
const joinedRooms = roomData["joined_rooms"];
const isBotInRoom = joinedRooms.includes(member.roomId);
const room = this.client.getRoom(member.roomId);
if (!room) return; // notify room if the facilitator has left
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
if (isBotInRoom && member.userId === facilitatorId) {
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`);
} // leave if there is nobody in the room
try {
const memberCount = room.getJoinedMemberCount();
if (memberCount === 1 && isBotInRoom) {
// just the bot left
_logger.default.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
this.deleteTranscript(member.userId, member.roomId);
this.localStorage.removeItem(`${member.roomId}-facilitator`);
this.localStorage.removeItem(`${member.roomId}-transcript`);
return this.client.leave(member.roomId);
}
} catch (err) {
_logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
} // send signal to close the chat if there are no facilitators in the room
try {
const roomMembers = await room.getJoinedMembers();
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const facilitators = facilitatorRoomMembers['joined'];
let facilitatorInRoom = false;
roomMembers.forEach(member => {
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
facilitatorInRoom = true;
}
});
if (!facilitatorInRoom) {
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
}
} catch (err) {
_logger.default.log("error", `ERROR SENDING BOT SIGNAL ==> ${err}`);
}
}
});
}
async setMessageListeners() {
// encrypted messages
this.client.on("Event.decrypted", (event, err) => {
if (err) {
return _logger.default.log("error", `ERROR DECRYPTING EVENT: ${err}`);
}
if (event.getType() === "m.room.message") {
this.handleMessageEvent(event);
}
}); // unencrypted messages
this.client.on("Room.timeline", (event, room, toStartOfTimeline) => {
if (event.getType() === "m.room.message" && !event.isEncrypted()) {
this.handleMessageEvent(event);
}
});
}
async leaveOldRooms() {
const roomData = await this.client.getJoinedRooms();
roomData["joined_rooms"].forEach(async roomId => {
try {
await this.client.leave(roomId);
} catch (err) {
_logger.default.log('error', "ERROR LEAVING ROOM => " + err);
}
});
}
async sendBotSignal(roomId, signal, args) {
let content = {
signal: signal,
args: args
};
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
}
async start() {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage;
try {
const auth = {
user: this.config.BOT_USERNAME,
password: this.config.BOT_PASSWORD,
initial_device_display_name: this.config.BOT_DISPLAY_NAME
};
const account = await this.client.login("m.login.password", auth);
_logger.default.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
let opts = {
baseUrl: this.config.MATRIX_SERVER_URL,
accessToken: account.access_token,
userId: this.config.BOT_USERID,
deviceId: account.device_id,
sessionStore: new matrix.WebStorageSessionStore(localStorage)
};
this.client = matrix.createClient(opts);
await this.client.initCrypto();
this.client.startClient({
initialSyncLimit: 0
});
this.client.once('sync', async (state, prevState, data) => {
_logger.default.log("info", `SYNC STATUS: ${state}`);
if (state === 'PREPARED') {
await this.deleteOldDevices();
await this.trackJoinedRooms();
await this.setMembershipListeners();
await this.setMessageListeners();
}
});
} catch (err) {
this.handleBotCrash(undefined, err);
_logger.default.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
}
}
}
var _default = OcrccBot;
exports.default = _default;