safesupport-bot/src/bot.js

712 lines
23 KiB
JavaScript

import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as util from "util";
import { LocalStorage } from "node-localstorage";
global.Olm = require("olm");
import * as matrix from "matrix-js-sdk";
import logger from "./logger";
import encrypt from "./encrypt-attachment";
const BOT_SIGNAL_END_CHAT = 'END_CHAT'
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'
class OcrccBot {
constructor(config) {
this.config = config
this.client = matrix.createClient(this.config.matrixServerUrl);
this.joinedRooms = [];
this.inactivityTimers = {};
}
createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
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 LocalStorage(localStoragePath);
}
async sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
await this.sendMessage(roomId, content);
}
async sendNotice(roomId, message) {
try {
await this.client.sendNotice(roomId, message)
logger.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.log("error", `ERROR VERIFYING DEVICE: ${err}`);
}
});
});
await this.sendNotice(roomId, message);
default:
logger.log("error", `ERROR SENDING *NOTICE*: ${err}`);
break;
}
}
}
async sendMessage(roomId, content) {
try {
await this.client.sendMessage(roomId, content)
logger.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.log("error", `ERROR VERIFYING DEVICE: ${err}`);
}
});
});
await this.sendMessage(roomId, content);
default:
logger.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.kickReason)
} catch(err) {
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
}
}
async inviteFacilitatorIfOnline(roomId, memberId) {
const user = this.client.getUser(memberId);
if (
user &&
(user.presence !== "offline") &&
memberId !== this.config.botUserId
) {
invitations.push(memberId)
this.inviteUserToRoom(roomId, memberId);
return memberId
} else {
return null
}
}
async inviteFacilitators(roomId) {
try {
this.localStorage.setItem(`${roomId}-waiting`, 'true')
let invitations = []
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
const members = Object.keys(roomMembers["joined"]);
for (const memberId of members) {
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId)
invitations.push(invited)
}
if (invitations.filter(i => i).length > 0) {
this.localStorage.setItem(`${roomId}-invitations`, invitations)
} else {
logger.log('info', "NO FACILITATORS ONLINE")
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE)
}
} catch(err) {
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR GETTING FACILITATORS: ${err}`);
}
}
async uninviteFacilitators(roomId) {
try {
this.localStorage.removeItem(`${roomId}-waiting`)
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
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.log("ERROR UNINVITING FACILITATORS", err);
}
}
handleBotCrash(roomId, error) {
if (roomId) {
this.sendTextMessage(roomId, this.config.botErrorMessage);
}
this.sendTextMessage(
this.config.facilitatorRoomId,
`${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`
);
}
handleMessageEvent(event) {
const content = event.getContent();
const sender = event.getSender()
const roomId = event.getRoomId();
// do nothing if there's no content
if (!content) {
return;
}
// 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.botUserId) {
this.setInactivityTimeout(roomId)
}
// bot commands
if (content.body.startsWith("!bot")) {
return this.handleBotCommand(event);
}
// write to transcript
if (this.config.captureTranscripts) {
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.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.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, 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
);
}
const args = commandText.substring(command.keyword.length).trim()
command.function(senderId, roomId, args)
} catch (err) {
logger.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
}
}
async leaveEmptyRooms() {
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 {
await this.client.leave(roomId)
logger.log('info', `LEAVING EMPTY ROOM => ${roomId}`)
} catch(err) {
logger.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`)
}
}
})
} catch(err) {
logger.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
);
}
if (this.client.isRoomEncrypted(roomId)) {
let encryptInfo;
const filename = path.basename(transcriptFile) || "Transcript";
const data = fs.readFileSync(transcriptFile);
const encryptResult = await encrypt.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.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.log("error", `ERROR UPLOADING CONTENT: ${err}`);
this.sendTextMessage(
roomId,
"There was an error uploading the transcript.",
senderId
);
}
}
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.log('error', "UNABLE TO DELETE TRANSCRIPT FILE => " + transcriptFile)
logger.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.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.log("info", "RETRYING DELETE OLD DEVICES WITH AUTH")
const auth = {
session: err.data.session,
type: "m.login.password",
user: this.config.botUserId,
identifier: { type: "m.id.user", user: this.config.botUserId },
password: this.config.botPassword
};
await this.client.deleteMultipleDevices(oldDevices, auth)
logger.log("info", "DELETED OLD DEVICES")
}
}
async trackJoinedRooms() {
const roomData = await this.client.getJoinedRooms()
this.joinedRooms = roomData["joined_rooms"]
logger.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.botUserId &&
!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.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.facilitatorRoomId, notification);
this.inviteFacilitators(room.roomId)
this.setTimeoutforFacilitator(room.roomId)
}
} catch(err) {
logger.log("error", "ERROR JOINING ROOM => " + err)
}
}
if (
member.membership === "join" &&
member.userId !== this.config.botUserId &&
this.localStorage.getItem(`${member.roomId}-waiting`)
) {
try {
// make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
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.botUserId]: 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.facilitatorRoomId, 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.captureTranscripts) {
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)
}
}
} catch(err) {
logger.log("error", `ERROR WHEN FACILITATOR JOINED ROOM ==> ${err}`);
}
}
if (
member.membership === "leave" &&
member.userId !== this.config.botUserId
) {
const room = this.client.getRoom(member.roomId)
if (!room) return;
const roomMembers = await room.getJoinedMembers() // array
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId) // object
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId))
// leave if there is nobody in the room
try {
const memberCount = roomMembers.length
if (memberCount === 1 && isBotInRoom) { // just the bot left
logger.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`)
this.localStorage.removeItem(`${member.roomId}-waiting`)
return await this.client.leave(member.roomId)
}
} catch(err) {
return logger.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.facilitatorRoomId, notification);
}
} catch(err) {
logger.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.botUserId && Boolean(facilitators[member.userId])) {
facilitatorInRoom = true
}
})
if (!facilitatorInRoom) {
logger.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT)
}
} catch(err) {
logger.log("error", `ERROR SENDING BOT SIGNAL ==> ${err}`);
}
}
})
}
setTimeoutforFacilitator(roomId) {
setTimeout(async() => {
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`)
if (stillWaiting) {
logger.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(
roomId,
this.config.chatNotAvailableMessage
);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
}
}, this.config.maxWaitTime)
}
setInactivityTimeout(roomId) {
const oldTimeout = this.inactivityTimers[roomId];
if (oldTimeout) {
clearTimeout(oldTimeout);
}
const newTimeout = setTimeout(async() => {
logger.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(
roomId,
this.config.chatInactiveMessage
);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
}, this.config.maxInactiveTime)
this.inactivityTimers[roomId] = newTimeout;
}
async setMessageListeners() {
// encrypted messages
this.client.on("Event.decrypted", (event, err) => {
if (err) {
return logger.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,
}
try {
await this.client.sendStateEvent(roomId, 'm.bot.signal', content)
} catch(err) {
logger.log('error', "ERROR SENDING BOT SIGNAL => " + err)
}
}
async start() {
try {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage
const auth = {
user: this.config.botUsername,
password: this.config.botPassword,
initial_device_display_name: this.config.botDisplayName
}
const account = await this.client.login("m.login.password", auth)
logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
let opts = {
baseUrl: this.config.matrixServerUrl,
accessToken: account.access_token,
userId: this.config.botUserId,
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.log("info", `SYNC STATUS: ${state}`)
if (state === 'PREPARED') {
await this.deleteOldDevices()
await this.leaveEmptyRooms()
await this.trackJoinedRooms()
await this.setMembershipListeners();
await this.setMessageListeners();
}
});
} catch(err) {
this.handleBotCrash(undefined, err);
logger.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
}
}
}
export default OcrccBot;