fetch and use admin settings

This commit is contained in:
Sharon Kennedy 2020-11-30 22:47:32 -05:00
parent 687dfa84e9
commit d3747cc654
10 changed files with 212 additions and 171 deletions

View File

@ -1,7 +0,0 @@
MATRIX_SERVER_URL=
BOT_DISPLAY_NAME=
BOT_USERNAME=
BOT_PASSWORD=
BOT_USERID=
FACILITATOR_ROOM_ID=
CAPTURE_TRANSCRIPTS

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ node_modules
*.log *.log
__mocks__/test_transcript.txt __mocks__/test_transcript.txt
transcripts/*.txt transcripts/*.txt
config.json

72
dist/bot.js vendored
View File

@ -30,15 +30,15 @@ const BOT_SIGNAL_END_CHAT = 'END_CHAT';
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'; const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE';
class OcrccBot { class OcrccBot {
constructor(botConfig) { constructor(config) {
this.config = botConfig; this.config = config;
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL); this.client = matrix.createClient(this.config.matrixServerUrl);
this.joinedRooms = []; this.joinedRooms = [];
this.inactivityTimers = {}; this.inactivityTimers = {};
} }
createLocalStorage() { createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`; const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage")); const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
if (!fs.existsSync(dir)) { if (!fs.existsSync(dir)) {
@ -122,7 +122,7 @@ class OcrccBot {
kickUserFromRoom(roomId, member) { kickUserFromRoom(roomId, member) {
try { try {
this.client.kick(roomId, member, this.config.KICK_REASON); this.client.kick(roomId, member, this.config.kickReason);
} catch (err) { } catch (err) {
this.handleBotCrash(roomId, err); this.handleBotCrash(roomId, err);
@ -134,12 +134,12 @@ class OcrccBot {
try { try {
this.localStorage.setItem(`${roomId}-waiting`, 'true'); this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = []; let invitations = [];
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID); const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
const members = Object.keys(roomMembers["joined"]); const members = Object.keys(roomMembers["joined"]);
members.forEach(memberId => { members.forEach(memberId => {
const user = this.client.getUser(memberId); const user = this.client.getUser(memberId);
if (user && user.presence !== "offline" && memberId !== this.config.BOT_USERID) { if (user && user.presence !== "offline" && memberId !== this.config.botUserId) {
invitations.push(memberId); invitations.push(memberId);
this.inviteUserToRoom(roomId, memberId); this.inviteUserToRoom(roomId, memberId);
} }
@ -162,7 +162,7 @@ class OcrccBot {
async uninviteFacilitators(roomId) { async uninviteFacilitators(roomId) {
try { try {
this.localStorage.removeItem(`${roomId}-waiting`); this.localStorage.removeItem(`${roomId}-waiting`);
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID); const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId); const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
const roomMembersIds = Object.keys(supportRoomMembers["joined"]); const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]); const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
@ -181,10 +181,10 @@ class OcrccBot {
handleBotCrash(roomId, error) { handleBotCrash(roomId, error) {
if (roomId) { if (roomId) {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE); this.sendTextMessage(roomId, this.config.botErrorMessage);
} }
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.`); this.sendTextMessage(this.config.facilitatorRoomId, `${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`);
} }
handleMessageEvent(event) { handleMessageEvent(event) {
@ -199,7 +199,7 @@ class OcrccBot {
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`); const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`);
if (Boolean(facilitatorId) && sender !== this.config.BOT_USERID) { if (Boolean(facilitatorId) && sender !== this.config.botUserId) {
this.setInactivityTimeout(roomId); this.setInactivityTimeout(roomId);
} // bot commands } // bot commands
@ -209,7 +209,7 @@ class OcrccBot {
} // write to transcript } // write to transcript
if (this.config.CAPTURE_TRANSCRIPTS) { if (this.config.captureTranscripts) {
return this.writeToTranscript(event); return this.writeToTranscript(event);
} }
} }
@ -406,12 +406,12 @@ class OcrccBot {
const auth = { const auth = {
session: err.data.session, session: err.data.session,
type: "m.login.password", type: "m.login.password",
user: this.config.BOT_USERID, user: this.config.botUserId,
identifier: { identifier: {
type: "m.id.user", type: "m.id.user",
user: this.config.BOT_USERID user: this.config.botUserId
}, },
password: this.config.BOT_PASSWORD password: this.config.botPassword
}; };
await this.client.deleteMultipleDevices(oldDevices, auth); await this.client.deleteMultipleDevices(oldDevices, auth);
@ -429,7 +429,7 @@ class OcrccBot {
async setMembershipListeners() { async setMembershipListeners() {
// Automatically accept all room invitations // Automatically accept all room invitations
this.client.on("RoomMember.membership", async (event, member) => { this.client.on("RoomMember.membership", async (event, member) => {
if (member.membership === "invite" && member.userId === this.config.BOT_USERID && !this.joinedRooms.includes(member.roomId)) { if (member.membership === "invite" && member.userId === this.config.botUserId && !this.joinedRooms.includes(member.roomId)) {
try { try {
const roomData = await this.client.getJoinedRooms(); const roomData = await this.client.getJoinedRooms();
const joinedRooms = roomData["joined_rooms"]; const joinedRooms = roomData["joined_rooms"];
@ -444,7 +444,7 @@ class OcrccBot {
const chatTime = inviteDate.toLocaleTimeString(); const chatTime = inviteDate.toLocaleTimeString();
const roomId = room.roomId.split(':')[0]; const roomId = room.roomId.split(':')[0];
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`; const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); this.sendTextMessage(this.config.facilitatorRoomId, notification);
this.inviteFacilitators(room.roomId); this.inviteFacilitators(room.roomId);
this.setTimeoutforFacilitator(room.roomId); this.setTimeoutforFacilitator(room.roomId);
} }
@ -453,10 +453,10 @@ class OcrccBot {
} }
} }
if (member.membership === "join" && member.userId !== this.config.BOT_USERID && this.localStorage.getItem(`${member.roomId}-waiting`)) { if (member.membership === "join" && member.userId !== this.config.botUserId && this.localStorage.getItem(`${member.roomId}-waiting`)) {
try { try {
// make sure it's a facilitator joining // make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID); const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
const members = Object.keys(roomMembers["joined"]); const members = Object.keys(roomMembers["joined"]);
const isFacilitator = members.includes(member.userId); const isFacilitator = members.includes(member.userId);
@ -470,7 +470,7 @@ class OcrccBot {
getContent: () => { getContent: () => {
return { return {
users: { users: {
[this.config.BOT_USERID]: 100, [this.config.botUserId]: 100,
[member.userId]: 50 [member.userId]: 50
} }
}; };
@ -482,13 +482,13 @@ class OcrccBot {
const chatTime = currentDate.toLocaleTimeString(); const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0]; const roomId = member.roomId.split(':')[0];
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`; 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(this.config.facilitatorRoomId, notification); // send notification to chat room
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations
this.uninviteFacilitators(member.roomId); // set transcript file this.uninviteFacilitators(member.roomId); // set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) { if (this.config.captureTranscripts) {
const currentDate = new Date(); const currentDate = new Date();
const dateOpts = { const dateOpts = {
year: "numeric", year: "numeric",
@ -509,14 +509,14 @@ class OcrccBot {
} }
} }
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) { if (member.membership === "leave" && member.userId !== this.config.botUserId) {
const room = this.client.getRoom(member.roomId); const room = this.client.getRoom(member.roomId);
if (!room) return; if (!room) return;
const roomMembers = await room.getJoinedMembers(); // array const roomMembers = await room.getJoinedMembers(); // array
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID); // object const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId); // object
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.BOT_USERID)); // leave if there is nobody in the room const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId)); // leave if there is nobody in the room
try { try {
const memberCount = roomMembers.length; const memberCount = roomMembers.length;
@ -546,7 +546,7 @@ class OcrccBot {
const chatTime = currentDate.toLocaleTimeString(); const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0]; const roomId = member.roomId.split(':')[0];
const notification = `${member.name} left the chat at ${chatTime} (room ID: ${roomId})`; const notification = `${member.name} left the chat at ${chatTime} (room ID: ${roomId})`;
await this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); await this.sendTextMessage(this.config.facilitatorRoomId, notification);
} }
} catch (err) { } catch (err) {
_logger.default.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`); _logger.default.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
@ -557,7 +557,7 @@ class OcrccBot {
const facilitators = facilitatorRoomMembers['joined']; const facilitators = facilitatorRoomMembers['joined'];
let facilitatorInRoom = false; let facilitatorInRoom = false;
roomMembers.forEach(member => { roomMembers.forEach(member => {
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) { if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
facilitatorInRoom = true; facilitatorInRoom = true;
} }
}); });
@ -581,10 +581,10 @@ class OcrccBot {
if (stillWaiting) { if (stillWaiting) {
_logger.default.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`); _logger.default.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(roomId, this.config.CHAT_NOT_AVAILABLE_MESSAGE); await this.sendTextMessage(roomId, this.config.chatNotAvailableMessage);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT); this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
} }
}, this.config.MAX_WAIT_TIME); }, this.config.maxWaitTime);
} }
setInactivityTimeout(roomId) { setInactivityTimeout(roomId) {
@ -597,9 +597,9 @@ class OcrccBot {
const newTimeout = setTimeout(async () => { const newTimeout = setTimeout(async () => {
_logger.default.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`); _logger.default.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(roomId, `This chat has been closed due to inactivity.`); await this.sendTextMessage(roomId, this.config.chatInactiveMessage);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT); this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
}, this.config.MAX_INACTIVE); }, this.config.maxInactiveTime);
this.inactivityTimers[roomId] = newTimeout; this.inactivityTimers[roomId] = newTimeout;
} }
@ -640,18 +640,18 @@ class OcrccBot {
const localStorage = this.createLocalStorage(); const localStorage = this.createLocalStorage();
this.localStorage = localStorage; this.localStorage = localStorage;
const auth = { const auth = {
user: this.config.BOT_USERNAME, user: this.config.botUsername,
password: this.config.BOT_PASSWORD, password: this.config.botPassword,
initial_device_display_name: this.config.BOT_DISPLAY_NAME initial_device_display_name: this.config.botDisplayName
}; };
const account = await this.client.login("m.login.password", auth); const account = await this.client.login("m.login.password", auth);
_logger.default.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`); _logger.default.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
let opts = { let opts = {
baseUrl: this.config.MATRIX_SERVER_URL, baseUrl: this.config.matrixServerUrl,
accessToken: account.access_token, accessToken: account.access_token,
userId: this.config.BOT_USERID, userId: this.config.botUserId,
deviceId: account.device_id, deviceId: account.device_id,
sessionStore: new matrix.WebStorageSessionStore(localStorage) sessionStore: new matrix.WebStorageSessionStore(localStorage)
}; };

42
dist/index.js vendored
View File

@ -2,48 +2,14 @@
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _config = _interopRequireDefault(require("../config.json"));
var _bot = _interopRequireDefault(require("./bot")); var _bot = _interopRequireDefault(require("./bot"));
require('dotenv').config(); const bot = new _bot.default(_config.default);
const ENCRYPTION_CONFIG = {
algorithm: "m.megolm.v1.aes-sha2"
};
const KICK_REASON = "A facilitator has already joined this chat.";
const BOT_ERROR_MESSAGE = "Something went wrong on our end, please restart the chat and try again.";
const MAX_RETRIES = 3;
const {
MATRIX_SERVER_URL,
BOT_USERNAME,
BOT_USERID,
BOT_PASSWORD,
BOT_DISPLAY_NAME,
FACILITATOR_ROOM_ID,
CAPTURE_TRANSCRIPTS,
CHAT_NOT_AVAILABLE_MESSAGE,
MAX_WAIT_TIME,
MAX_INACTIVE
} = process.env;
const botConfig = {
ENCRYPTION_CONFIG,
KICK_REASON,
BOT_ERROR_MESSAGE,
MAX_RETRIES,
MATRIX_SERVER_URL,
BOT_USERNAME,
BOT_USERID,
BOT_PASSWORD,
BOT_DISPLAY_NAME,
FACILITATOR_ROOM_ID,
CAPTURE_TRANSCRIPTS,
CHAT_NOT_AVAILABLE_MESSAGE,
MAX_WAIT_TIME,
MAX_INACTIVE
};
const bot = new _bot.default(botConfig);
try { try {
bot.start(); bot.start();
} catch (err) { } catch (err) {
console.log("AAAAAAAAAAAAA", err); console.log("Unable to start bot", err);
} }

54
dist/setup.js vendored Normal file
View File

@ -0,0 +1,54 @@
"use strict";
const fs = require('fs');
const fetch = require('node-fetch');
const config = require('../config.json');
const getSettings = async () => {
try {
const url = `${config.settingsEndpoint}?homeserver=${encodeURIComponent(config.matrixServerUrl)}`;
if (!config.matrixServerUrl) {
throw new Error("The matrix server url is not provided");
}
console.log(`Fetching settings for ${config.matrixServerUrl}`);
const res = await fetch(url);
const data = await res.json();
const {
fields,
schedule = []
} = data;
return Object.entries(fields).reduce((settingsObj, [k, v]) => {
const [scope, key] = k.split('_');
if (scope === 'platfrom') {
settingsObj[key] = v;
}
return settingsObj;
}, {});
} catch (err) {
console.log("Error fetching settings", err);
return null;
}
};
const writeConfig = async () => {
const settings = await getSettings();
if (!settings) {
return console.log('No settings to update');
}
const updatedSettings = Object.assign(config, settings);
fs.writeFile('config.json', JSON.stringify(updatedSettings, null, 2), function (err) {
if (err) return console.log("Error updating settings", err);
console.log(`Updated settings to config.json`);
console.log(updatedSettings);
});
};
writeConfig();

View File

@ -6,6 +6,7 @@
"scripts": { "scripts": {
"develop": "nodemon --exec babel-node src/index.js", "develop": "nodemon --exec babel-node src/index.js",
"build": "babel src -d dist", "build": "babel src -d dist",
"setup": "node src/setup.js",
"start": "yarn build && node dist/index.js", "start": "yarn build && node dist/index.js",
"test": "jest" "test": "jest"
}, },
@ -14,6 +15,7 @@
"dependencies": { "dependencies": {
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"matrix-js-sdk": "^6.2.1", "matrix-js-sdk": "^6.2.1",
"node-fetch": "^2.6.1",
"node-localstorage": "^2.1.5", "node-localstorage": "^2.1.5",
"node-webcrypto-ossl": "^2.1.0", "node-webcrypto-ossl": "^2.1.0",
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz", "olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",

View File

@ -14,17 +14,16 @@ import encrypt from "./encrypt-attachment";
const BOT_SIGNAL_END_CHAT = 'END_CHAT' const BOT_SIGNAL_END_CHAT = 'END_CHAT'
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE' const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'
class OcrccBot { class OcrccBot {
constructor(botConfig) { constructor(config) {
this.config = botConfig this.config = config
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL); this.client = matrix.createClient(this.config.matrixServerUrl);
this.joinedRooms = []; this.joinedRooms = [];
this.inactivityTimers = {}; this.inactivityTimers = {};
} }
createLocalStorage() { createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`; const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage")); const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
if (!fs.existsSync(dir)) { if (!fs.existsSync(dir)) {
fs.mkdirSync(dir); fs.mkdirSync(dir);
@ -101,33 +100,41 @@ class OcrccBot {
kickUserFromRoom(roomId, member) { kickUserFromRoom(roomId, member) {
try { try {
this.client.kick(roomId, member, this.config.KICK_REASON) this.client.kick(roomId, member, this.config.kickReason)
} catch(err) { } catch(err) {
this.handleBotCrash(roomId, err); this.handleBotCrash(roomId, err);
logger.log("error", `ERROR KICKING OUT MEMBER: ${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) { async inviteFacilitators(roomId) {
try { try {
this.localStorage.setItem(`${roomId}-waiting`, 'true') this.localStorage.setItem(`${roomId}-waiting`, 'true')
let invitations = [] let invitations = []
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID) const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
const members = Object.keys(roomMembers["joined"]); const members = Object.keys(roomMembers["joined"]);
members.forEach(memberId => { for (const memberId of members) {
const user = this.client.getUser(memberId); const invited = await this.inviteFacilitatorIfOnline(roomId, memberId)
if ( invitations.push(invited)
user &&
(user.presence !== "offline") &&
memberId !== this.config.BOT_USERID
) {
invitations.push(memberId)
this.inviteUserToRoom(roomId, memberId);
} }
});
if (invitations.length > 0) { if (invitations.filter(i => i).length > 0) {
this.localStorage.setItem(`${roomId}-invitations`, invitations) this.localStorage.setItem(`${roomId}-invitations`, invitations)
} else { } else {
logger.log('info', "NO FACILITATORS ONLINE") logger.log('info', "NO FACILITATORS ONLINE")
@ -144,7 +151,7 @@ class OcrccBot {
async uninviteFacilitators(roomId) { async uninviteFacilitators(roomId) {
try { try {
this.localStorage.removeItem(`${roomId}-waiting`) this.localStorage.removeItem(`${roomId}-waiting`)
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID) const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId) const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
const roomMembersIds = Object.keys(supportRoomMembers["joined"]); const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
@ -166,12 +173,12 @@ class OcrccBot {
handleBotCrash(roomId, error) { handleBotCrash(roomId, error) {
if (roomId) { if (roomId) {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE); this.sendTextMessage(roomId, this.config.botErrorMessage);
} }
this.sendTextMessage( this.sendTextMessage(
this.config.FACILITATOR_ROOM_ID, this.config.facilitatorRoomId,
`${this.config.BOT_DISPLAY_NAME} ran into an error: ${error}. Please verify that the chat service is working.` `${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`
); );
} }
@ -187,7 +194,7 @@ class OcrccBot {
// if it's a chat message and the facilitator has joined, reset the inactivity timeout // if it's a chat message and the facilitator has joined, reset the inactivity timeout
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`) const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`)
if (Boolean(facilitatorId) && sender !== this.config.BOT_USERID) { if (Boolean(facilitatorId) && sender !== this.config.botUserId) {
this.setInactivityTimeout(roomId) this.setInactivityTimeout(roomId)
} }
@ -197,7 +204,7 @@ class OcrccBot {
} }
// write to transcript // write to transcript
if (this.config.CAPTURE_TRANSCRIPTS) { if (this.config.captureTranscripts) {
return this.writeToTranscript(event); return this.writeToTranscript(event);
} }
} }
@ -417,9 +424,9 @@ class OcrccBot {
const auth = { const auth = {
session: err.data.session, session: err.data.session,
type: "m.login.password", type: "m.login.password",
user: this.config.BOT_USERID, user: this.config.botUserId,
identifier: { type: "m.id.user", user: this.config.BOT_USERID }, identifier: { type: "m.id.user", user: this.config.botUserId },
password: this.config.BOT_PASSWORD password: this.config.botPassword
}; };
await this.client.deleteMultipleDevices(oldDevices, auth) await this.client.deleteMultipleDevices(oldDevices, auth)
@ -438,7 +445,7 @@ class OcrccBot {
this.client.on("RoomMember.membership", async (event, member) => { this.client.on("RoomMember.membership", async (event, member) => {
if ( if (
member.membership === "invite" && member.membership === "invite" &&
member.userId === this.config.BOT_USERID && member.userId === this.config.botUserId &&
!this.joinedRooms.includes(member.roomId) !this.joinedRooms.includes(member.roomId)
) { ) {
try { try {
@ -452,7 +459,7 @@ class OcrccBot {
const chatTime = inviteDate.toLocaleTimeString() const chatTime = inviteDate.toLocaleTimeString()
const roomId = room.roomId.split(':')[0] const roomId = room.roomId.split(':')[0]
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})` const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); this.sendTextMessage(this.config.facilitatorRoomId, notification);
this.inviteFacilitators(room.roomId) this.inviteFacilitators(room.roomId)
this.setTimeoutforFacilitator(room.roomId) this.setTimeoutforFacilitator(room.roomId)
} }
@ -463,12 +470,12 @@ class OcrccBot {
if ( if (
member.membership === "join" && member.membership === "join" &&
member.userId !== this.config.BOT_USERID && member.userId !== this.config.botUserId &&
this.localStorage.getItem(`${member.roomId}-waiting`) this.localStorage.getItem(`${member.roomId}-waiting`)
) { ) {
try { try {
// make sure it's a facilitator joining // make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID) const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
const members = Object.keys(roomMembers["joined"]); const members = Object.keys(roomMembers["joined"]);
const isFacilitator = members.includes(member.userId) const isFacilitator = members.includes(member.userId)
@ -482,7 +489,7 @@ class OcrccBot {
getContent: () => { getContent: () => {
return { return {
users: { users: {
[this.config.BOT_USERID]: 100, [this.config.botUserId]: 100,
[member.userId]: 50 [member.userId]: 50
} }
}; };
@ -495,7 +502,7 @@ class OcrccBot {
const chatTime = currentDate.toLocaleTimeString() const chatTime = currentDate.toLocaleTimeString()
const roomId = member.roomId.split(':')[0] const roomId = member.roomId.split(':')[0]
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})` const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); this.sendTextMessage(this.config.facilitatorRoomId, notification);
// send notification to chat room // send notification to chat room
this.sendTextMessage( this.sendTextMessage(
@ -507,7 +514,7 @@ class OcrccBot {
this.uninviteFacilitators(member.roomId); this.uninviteFacilitators(member.roomId);
// set transcript file // set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) { if (this.config.captureTranscripts) {
const currentDate = new Date(); const currentDate = new Date();
const dateOpts = { const dateOpts = {
year: "numeric", year: "numeric",
@ -530,14 +537,14 @@ class OcrccBot {
if ( if (
member.membership === "leave" && member.membership === "leave" &&
member.userId !== this.config.BOT_USERID member.userId !== this.config.botUserId
) { ) {
const room = this.client.getRoom(member.roomId) const room = this.client.getRoom(member.roomId)
if (!room) return; if (!room) return;
const roomMembers = await room.getJoinedMembers() // array const roomMembers = await room.getJoinedMembers() // array
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID) // object const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId) // object
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.BOT_USERID)) const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId))
// leave if there is nobody in the room // leave if there is nobody in the room
try { try {
@ -567,7 +574,7 @@ class OcrccBot {
const chatTime = currentDate.toLocaleTimeString() const chatTime = currentDate.toLocaleTimeString()
const roomId = member.roomId.split(':')[0] const roomId = member.roomId.split(':')[0]
const notification = `${member.name} left the chat at ${chatTime} (room ID: ${roomId})` const notification = `${member.name} left the chat at ${chatTime} (room ID: ${roomId})`
await this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); await this.sendTextMessage(this.config.facilitatorRoomId, notification);
} }
} catch(err) { } catch(err) {
logger.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`); logger.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
@ -579,7 +586,7 @@ class OcrccBot {
let facilitatorInRoom = false; let facilitatorInRoom = false;
roomMembers.forEach(member => { roomMembers.forEach(member => {
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) { if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
facilitatorInRoom = true facilitatorInRoom = true
} }
}) })
@ -603,11 +610,11 @@ class OcrccBot {
logger.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`); logger.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage( await this.sendTextMessage(
roomId, roomId,
this.config.CHAT_NOT_AVAILABLE_MESSAGE this.config.chatNotAvailableMessage
); );
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT) this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
} }
}, this.config.MAX_WAIT_TIME) }, this.config.maxWaitTime)
} }
setInactivityTimeout(roomId) { setInactivityTimeout(roomId) {
@ -621,10 +628,10 @@ class OcrccBot {
logger.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`); logger.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage( await this.sendTextMessage(
roomId, roomId,
`This chat has been closed due to inactivity.` this.config.chatInactiveMessage
); );
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT) this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
}, this.config.MAX_INACTIVE) }, this.config.maxInactiveTime)
this.inactivityTimers[roomId] = newTimeout; this.inactivityTimers[roomId] = newTimeout;
} }
@ -665,17 +672,17 @@ class OcrccBot {
this.localStorage = localStorage this.localStorage = localStorage
const auth = { const auth = {
user: this.config.BOT_USERNAME, user: this.config.botUsername,
password: this.config.BOT_PASSWORD, password: this.config.botPassword,
initial_device_display_name: this.config.BOT_DISPLAY_NAME initial_device_display_name: this.config.botDisplayName
} }
const account = await this.client.login("m.login.password", auth) const account = await this.client.login("m.login.password", auth)
logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`); logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
let opts = { let opts = {
baseUrl: this.config.MATRIX_SERVER_URL, baseUrl: this.config.matrixServerUrl,
accessToken: account.access_token, accessToken: account.access_token,
userId: this.config.BOT_USERID, userId: this.config.botUserId,
deviceId: account.device_id, deviceId: account.device_id,
sessionStore: new matrix.WebStorageSessionStore(localStorage) sessionStore: new matrix.WebStorageSessionStore(localStorage)
}; };

View File

@ -1,46 +1,9 @@
require('dotenv').config() import config from '../config.json';
import OcrccBot from './bot';
const ENCRYPTION_CONFIG = { algorithm: "m.megolm.v1.aes-sha2" }; const bot = new OcrccBot(config);
const KICK_REASON = "A facilitator has already joined this chat.";
const BOT_ERROR_MESSAGE =
"Something went wrong on our end, please restart the chat and try again.";
const MAX_RETRIES = 3;
const {
MATRIX_SERVER_URL,
BOT_USERNAME,
BOT_USERID,
BOT_PASSWORD,
BOT_DISPLAY_NAME,
FACILITATOR_ROOM_ID,
CAPTURE_TRANSCRIPTS,
CHAT_NOT_AVAILABLE_MESSAGE,
MAX_WAIT_TIME,
MAX_INACTIVE,
} = process.env;
const botConfig = {
ENCRYPTION_CONFIG,
KICK_REASON,
BOT_ERROR_MESSAGE,
MAX_RETRIES,
MATRIX_SERVER_URL,
BOT_USERNAME,
BOT_USERID,
BOT_PASSWORD,
BOT_DISPLAY_NAME,
FACILITATOR_ROOM_ID,
CAPTURE_TRANSCRIPTS,
CHAT_NOT_AVAILABLE_MESSAGE,
MAX_WAIT_TIME,
MAX_INACTIVE,
}
import OcrccBot from './bot'
const bot = new OcrccBot(botConfig);
try { try {
bot.start(); bot.start();
} catch(err) { } catch(err) {
console.log("AAAAAAAAAAAAA", err) console.log("Unable to start bot", err)
} }

50
src/setup.js Normal file
View File

@ -0,0 +1,50 @@
const fs = require('fs');
const fetch = require('node-fetch');
const config = require('../config.json');
const getSettings = async () => {
try {
const url = `${config.settingsEndpoint}?homeserver=${encodeURIComponent(config.matrixServerUrl)}`;
if (!config.matrixServerUrl) {
throw new Error("The matrix server url is not provided")
}
console.log(`Fetching settings for ${config.matrixServerUrl}`);
const res = await fetch(url);
const data = await res.json();
const { fields, schedule = [] } = data;
return Object.entries(fields).reduce(((settingsObj, [k,v]) => {
const [scope, key] = k.split('_');
if (scope === 'platfrom') {
settingsObj[key] = v;
}
return settingsObj
}), {});
} catch (err) {
console.log("Error fetching settings", err);
return null
}
};
const writeConfig = async () => {
const settings = await getSettings()
if (!settings) {
return console.log('No settings to update')
}
const updatedSettings = Object.assign(config, settings)
fs.writeFile('config.json', JSON.stringify(updatedSettings, null, 2), function (err) {
if (err) return console.log("Error updating settings", err);
console.log(`Updated settings to config.json`);
console.log(updatedSettings);
});
}
writeConfig();

View File

@ -3954,6 +3954,11 @@ node-environment-flags@^1.0.5:
object.getownpropertydescriptors "^2.0.3" object.getownpropertydescriptors "^2.0.3"
semver "^5.7.0" semver "^5.7.0"
node-fetch@^2.6.1:
version "2.6.1"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052"
integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==
node-int64@^0.4.0: node-int64@^0.4.0:
version "0.4.0" version "0.4.0"
resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"