safesupport-bot/dist/bot.js

678 lines
23 KiB
JavaScript
Raw Permalink Normal View History

2020-03-16 18:41:56 +00:00
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
2020-03-16 18:41:56 +00:00
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
2020-03-16 18:41:56 +00:00
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"));
2020-07-25 23:07:08 +00:00
var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"));
global.Olm = require("olm");
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
2020-03-16 18:41:56 +00:00
class OcrccBot {
constructor(botConfig) {
this.config = botConfig;
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
this.joinedRooms = [];
2020-09-06 18:07:44 +00:00
this.inactivityTimers = {};
}
createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
2020-03-16 18:41:56 +00:00
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
2020-03-16 18:41:56 +00:00
const localStoragePath = path.resolve(path.join(dir, storageLoc));
return new _nodeLocalstorage.LocalStorage(localStoragePath);
}
2020-03-16 18:41:56 +00:00
async sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
await this.sendMessage(roomId, content);
}
2020-03-16 18:41:56 +00:00
async sendNotice(roomId, message) {
try {
await this.client.sendNotice(roomId, message);
_logger.default.log("info", `SENT *NOTICE*: ${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);
2020-03-16 18:41:56 +00:00
default:
2020-07-25 23:07:08 +00:00
_logger.default.log("error", `ERROR SENDING MESSAGE ${content.body}: ${err}`);
2020-03-16 18:41:56 +00:00
break;
}
}
2020-03-16 18:41:56 +00:00
}
inviteUserToRoom(roomId, member) {
try {
this.client.invite(roomId, member);
} catch (err) {
this.handleBotCrash(roomId, err);
}
}
2020-03-16 18:41:56 +00:00
kickUserFromRoom(roomId, member) {
try {
this.client.kick(roomId, member, this.config.KICK_REASON);
} catch (err) {
this.handleBotCrash(roomId, err);
2020-03-16 18:41:56 +00:00
_logger.default.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
async inviteFacilitators(roomId) {
try {
this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = [];
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);
2020-03-16 18:41:56 +00:00
if (user && user.presence !== "offline" && memberId !== this.config.BOT_USERID) {
invitations.push(memberId);
this.inviteUserToRoom(roomId, memberId);
2020-03-16 18:41:56 +00:00
}
});
if (invitations.length > 0) {
this.localStorage.setItem(`${roomId}-invitations`, invitations);
} else {
_logger.default.log('info', "NO FACILITATORS ONLINE");
2020-03-16 18:41:56 +00:00
this.sendNotice(roomId, "CHAT_OFFLINE");
2020-03-16 18:41:56 +00:00
}
} catch (err) {
this.handleBotCrash(roomId, err);
2020-03-16 18:41:56 +00:00
_logger.default.log("error", `ERROR GETTING FACILITATORS: ${err}`);
}
}
2020-03-16 18:41:56 +00:00
async uninviteFacilitators(roomId) {
try {
this.localStorage.removeItem(`${roomId}-waiting`);
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);
2020-03-16 18:41:56 +00:00
}
});
} catch (err) {
this.handleBotCrash(roomId, err);
_logger.default.log("ERROR UNINVITING FACILITATORS", err);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
handleBotCrash(roomId, error) {
if (roomId) {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
}
2020-03-16 18:41:56 +00:00
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `${this.config.BOT_DISPLAY_NAME} ran into an error: ${error}. Please verify that the chat service is working.`);
}
2020-03-16 18:41:56 +00:00
handleMessageEvent(event) {
2020-09-06 18:07:44 +00:00
const content = event.getContent();
const sender = event.getSender();
const roomId = event.getRoomId(); // do nothing if there's no content
2020-03-16 18:41:56 +00:00
if (!content) {
return;
2020-09-06 18:07:44 +00:00
} // if it's a chat message and the facilitator has joined, reset the inactivity timeout
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`);
if (Boolean(facilitatorId) && sender !== this.config.BOT_USERID) {
this.setInactivityTimeout(roomId);
} // bot commands
2020-03-16 18:41:56 +00:00
if (content.body.startsWith("!bot")) {
return this.handleBotCommand(event);
} // write to transcript
2020-03-16 18:41:56 +00:00
if (this.config.CAPTURE_TRANSCRIPTS) {
return this.writeToTranscript(event);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
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"
2020-03-16 18:41:56 +00:00
});
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
if (!filepath) {
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
}
const message = `${sender} [${time}]: ${content.body}\n`;
fs.appendFileSync(filepath, message, "utf8");
} catch (err) {
_logger.default.log("error", `ERROR APPENDING TO TRANSCRIPT FILE: ${err}`);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
handleBotCommand(event) {
const botCommands = [{
keyword: 'transcript',
function: (senderId, roomId) => {
this.sendTranscript(senderId, roomId);
}
}, {
keyword: 'delete transcript',
function: (senderId, roomId) => {
this.deleteTranscript(senderId, roomId, true);
} // delete transcript and send confirmation message
}, {
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);
2020-03-16 18:41:56 +00:00
}
const args = commandText.substring(command.keyword.length).trim();
command.function(senderId, roomId, args);
} catch (err) {
_logger.default.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
async leaveEmptyRooms() {
try {
const roomData = await this.client.getJoinedRooms();
const joinedRoomsIds = roomData["joined_rooms"];
joinedRoomsIds.forEach(async roomId => {
const room = this.client.getRoom(roomId);
2020-03-16 18:41:56 +00:00
if (room && room.getJoinedMemberCount() === 1) {
try {
await this.client.leave(roomId);
_logger.default.log('info', `LEAVING EMPTY ROOM => ${roomId}`);
} catch (err) {
_logger.default.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`);
}
}
});
} catch (err) {
_logger.default.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
}
}
async sendTranscript(senderId, roomId) {
try {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
this.sendTextMessage(roomId, "Cannot send transcript, there is no transcript for this chat.", senderId);
}
2020-07-25 23:07:08 +00:00
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'
2020-07-25 23:07:08 +00:00
};
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);
}
}
2020-03-16 18:41:56 +00:00
deleteTranscript(senderId, roomId, sendConfirmation = false) {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
return this.sendTextMessage(roomId, "Cannot delete transcript, 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);
}
if (sendConfirmation) {
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
}
_logger.default.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile);
this.localStorage.removeItem(`${roomId}-transcript`);
});
}
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);
2020-03-16 18:41:56 +00:00
_logger.default.log("info", "DELETED OLD DEVICES");
}
}
2020-03-16 18:41:56 +00:00
async trackJoinedRooms() {
const roomData = await this.client.getJoinedRooms();
this.joinedRooms = roomData["joined_rooms"];
2020-03-16 18:41:56 +00:00
_logger.default.log("info", "JOINED ROOMS => " + this.joinedRooms);
}
2020-03-16 18:41:56 +00:00
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);
2020-03-16 18:41:56 +00:00
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
2020-03-16 18:41:56 +00:00
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);
2020-09-06 18:07:44 +00:00
this.setTimeoutforFacilitator(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`)) {
2020-09-06 18:07:44 +00:00
try {
// 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
2020-09-06 18:07:44 +00:00
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
2020-09-06 18:07:44 +00:00
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations
2020-09-06 18:07:44 +00:00
this.uninviteFacilitators(member.roomId); // set transcript file
2020-09-06 18:07:44 +00:00
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);
}
}
2020-09-06 18:07:44 +00:00
} catch (err) {
_logger.default.log("error", `ERROR WHEN FACILITATOR JOINED ROOM ==> ${err}`);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
const room = this.client.getRoom(member.roomId);
2020-09-06 18:07:44 +00:00
if (!room) return;
const roomMembers = await room.getJoinedMembers(); // array
2020-07-25 23:07:08 +00:00
2020-09-06 18:07:44 +00:00
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID); // object
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.BOT_USERID)); // leave if there is nobody in the room
2020-07-25 23:07:08 +00:00
try {
2020-09-06 18:07:44 +00:00
const memberCount = roomMembers.length;
2020-07-25 23:07:08 +00:00
if (memberCount === 1 && isBotInRoom) {
// just the bot left
_logger.default.log("info", `LEAVING EMPTY ROOM: ${member.roomId}`);
2020-07-25 23:07:08 +00:00
this.deleteTranscript(member.userId, member.roomId);
this.localStorage.removeItem(`${member.roomId}-facilitator`);
this.localStorage.removeItem(`${member.roomId}-transcript`);
this.localStorage.removeItem(`${member.roomId}-waiting`);
return await this.client.leave(member.roomId);
}
} catch (err) {
return _logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
} // notify room if the facilitator has left
try {
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
if (isBotInRoom && member.userId === facilitatorId) {
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`); // 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} left the chat at ${chatTime} (room ID: ${roomId})`;
await this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
}
} catch (err) {
_logger.default.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
} // send signal to close the chat if there are no facilitators in the room
try {
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) {
_logger.default.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
}
} catch (err) {
_logger.default.log("error", `ERROR SENDING BOT SIGNAL ==> ${err}`);
2020-03-16 18:41:56 +00:00
}
}
});
}
2020-09-06 18:07:44 +00:00
setTimeoutforFacilitator(roomId) {
setTimeout(() => {
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`);
if (stillWaiting) {
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
}
}, this.config.MAX_WAIT_TIME);
}
setInactivityTimeout(roomId) {
const oldTimeout = this.inactivityTimers[roomId];
if (oldTimeout) {
clearTimeout(oldTimeout);
}
const newTimeout = setTimeout(() => {
this.sendTextMessage(roomId, `This chat has been closed due to inactivity.`);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
}, this.config.MAX_INACTIVE);
this.inactivityTimers[roomId] = newTimeout;
}
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 sendBotSignal(roomId, signal, args) {
let content = {
signal: signal,
args: args
};
2020-09-06 18:07:44 +00:00
try {
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
} catch (err) {
_logger.default.log('error', "ERROR SENDING BOT SIGNAL => " + err);
}
}
async start() {
try {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage;
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
2020-03-16 18:41:56 +00:00
});
2020-07-25 23:07:08 +00:00
this.client.once('sync', async (state, prevState, data) => {
_logger.default.log("info", `SYNC STATUS: ${state}`);
if (state === 'PREPARED') {
await this.deleteOldDevices();
await this.leaveEmptyRooms();
2020-07-25 23:07:08 +00:00
await this.trackJoinedRooms();
await this.setMembershipListeners();
await this.setMessageListeners();
}
});
} catch (err) {
this.handleBotCrash(undefined, err);
_logger.default.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
2020-03-16 18:41:56 +00:00
}
}
2020-03-16 18:41:56 +00:00
}
2020-03-16 18:41:56 +00:00
var _default = OcrccBot;
exports.default = _default;