leave rooms when empty, use localStorage

This commit is contained in:
Sharon Kennedy 2020-04-22 18:04:48 -04:00
parent 39d97343a5
commit aef215bd7e
14 changed files with 758 additions and 440 deletions

796
dist/bot.js vendored

File diff suppressed because it is too large Load Diff

253
dist/bot.test.js vendored Normal file
View File

@ -0,0 +1,253 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var path = _interopRequireWildcard(require("path"));
var os = _interopRequireWildcard(require("os"));
var fs = _interopRequireWildcard(require("fs"));
var _waitForExpect = _interopRequireDefault(require("wait-for-expect"));
var _matrixJsSdk = require("matrix-js-sdk");
var _bot = _interopRequireDefault(require("./bot"));
require('dotenv').config();
const mockAppendFileSync = jest.fn();
fs.appendFileSync = mockAppendFileSync;
describe('OcrccBot', () => {
beforeEach(() => {
_matrixJsSdk.createClient.mockClear();
_matrixJsSdk.mockInitCrypto.mockClear();
_matrixJsSdk.mockStartClient.mockClear();
_matrixJsSdk.mockRegisterRequest.mockClear();
_matrixJsSdk.mockSetPowerLevel.mockClear();
_matrixJsSdk.mockCreateRoom.mockClear();
_matrixJsSdk.mockLeave.mockClear();
_matrixJsSdk.mockDeactivateAccount.mockClear();
_matrixJsSdk.mockStopClient.mockClear();
_matrixJsSdk.mockClearStores.mockClear();
_matrixJsSdk.mockOnce.mockClear();
_matrixJsSdk.mockOn.mockClear();
_matrixJsSdk.mockLogin.mockClear();
_matrixJsSdk.mockGetDevices.mockClear();
_matrixJsSdk.mockGetDeviceId.mockClear();
_matrixJsSdk.mockDeleteMultipleDevices.mockClear();
_matrixJsSdk.mockGetJoinedRooms.mockClear();
_matrixJsSdk.mockSetDeviceVerified.mockClear();
_matrixJsSdk.mockInvite.mockClear();
_matrixJsSdk.mockKick.mockClear();
_matrixJsSdk.mockGetJoinedRoomMembers.mockClear();
_matrixJsSdk.mockGetUser.mockClear();
_matrixJsSdk.mockSendMessage.mockClear();
_matrixJsSdk.mockSendTextMessage.mockClear();
mockAppendFileSync.mockClear();
_matrixJsSdk.mockGetGroupUsers.mockClear();
});
test('constructor should inititialize class variables', () => {
const bot = new _bot.default();
expect(bot.joinedRooms).toEqual([]);
expect(bot.awaitingFacilitator).toEqual({});
expect(bot.activeChatrooms).toEqual({});
});
test('#createLocalStorage should have correct storage location', () => {
const bot = new _bot.default();
const localStorage = bot.createLocalStorage();
const localStoragePath = path.resolve(path.join(os.homedir(), ".local-storage", `matrix-chatbot-${process.env.BOT_USERNAME}`));
expect(localStorage._location).toBe(localStoragePath);
});
test('#sendMessage should send a text message', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
const testRoom = 'room_id_1234';
const testMsg = 'test message';
bot.sendMessage(testRoom, testMsg);
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockSetDeviceVerified).toHaveBeenCalledTimes(2);
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockSendMessage).toHaveBeenCalledWith(testRoom, testMsg);
});
});
test('#inviteUserToRoom should add member to room and retry on rate limit error', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
bot.inviteUserToRoom(bot.client, 'room_id_1234', process.env.BOT_USERNAME);
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockInvite).toHaveBeenCalledTimes(2);
});
});
test('#kickUserFromRoom should remove member from room and retry on rate limit error', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
bot.kickUserFromRoom(bot.client, 'room_id_1234', process.env.BOT_USERNAME);
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockKick).toHaveBeenCalledTimes(2);
});
});
test('#inviteFacilitators should invite all members from Facilitator room', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
bot.inviteFacilitators();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetJoinedRoomMembers).toHaveBeenCalledWith(process.env.FACILITATOR_ROOM_ID);
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetUser).toHaveBeenCalledTimes(2);
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockInvite).toHaveBeenCalledTimes(2);
});
});
test('#uninviteFacilitators should remove all members that have not accepted the invite', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
bot.uninviteFacilitators();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetJoinedRoomMembers).toHaveBeenCalledWith(process.env.FACILITATOR_ROOM_ID);
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetJoinedRoomMembers).toHaveBeenCalledWith('room_id_1234');
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockKick).toHaveBeenCalled();
});
});
test('#handleBotCrash should notify rooms', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
bot.handleBotCrash('test_room_id', 'test error message');
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockSendTextMessage).toHaveBeenCalledWith('test_room_id', "Something went wrong on our end, please restart the chat and try again.");
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockSendTextMessage).toHaveBeenCalledWith(process.env.FACILITATOR_ROOM_ID, `The Help Bot ran into an error: test error message. Please verify that the chat service is working.`);
});
});
test('#writeToTranscript should parse event and write to transcript file', () => {
const bot = new _bot.default();
bot.start();
bot.activeChatrooms['test_room_id'] = {
transcriptFile: '__mocks__/test_transcript.txt'
};
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
const mockEvent = {
getSender: () => 'test_sender',
getRoomId: () => 'test_room_id',
getContent: () => {
return {
body: 'test content'
};
},
getDate: () => {
return new Date(2020, 2, 17, 0, 0, 0, 0);
}
};
bot.writeToTranscript(mockEvent);
(0, _waitForExpect.default)(() => {
expect(mockAppendFileSync).toHaveBeenCalledWith('__mocks__/test_transcript.txt', 'test_sender [00:00:00]: test content', 'utf8');
});
});
test('#deleteOldDevices should delete old sessions', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
bot.deleteOldDevices();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetDevices).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(mockGetDevicdId).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(deleteMultipleDevices).toHaveBeenCalled();
});
}); // TODO test listeners for membership events and message events
test('#start should start bot and set up listeners', () => {
const bot = new _bot.default();
bot.start();
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockLogin).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.WebStorageSessionStore).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.createClient).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetDevices).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetDeviceId).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockDeleteMultipleDevices).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockInitCrypto).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockGetJoinedRooms).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockOn).toHaveBeenCalled();
});
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
});
});

38
dist/index.js vendored
View File

@ -1,10 +1,42 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _bot = _interopRequireDefault(require("./bot"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
require('dotenv').config();
var bot = new _bot["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_GROUP_ID,
FACILITATOR_ROOM_ID,
CHAT_OFFLINE_MESSAGE,
CAPTURE_TRANSCRIPTS
} = 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_GROUP_ID,
FACILITATOR_ROOM_ID,
CHAT_OFFLINE_MESSAGE,
CAPTURE_TRANSCRIPTS
};
const bot = new _bot.default(botConfig);
bot.start();

20
dist/logger.js vendored
View File

@ -1,17 +1,17 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
exports.default = void 0;
var _winston = _interopRequireDefault(require("winston"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var logger = _winston["default"].createLogger({
const logger = _winston.default.createLogger({
level: "info",
format: _winston["default"].format.json(),
format: _winston.default.format.json(),
defaultMeta: {
service: "user-service"
},
@ -19,10 +19,10 @@ var logger = _winston["default"].createLogger({
// - Write all logs with level `error` and below to `error.log`
// - Write all logs with level `info` and below to `combined.log`
//
new _winston["default"].transports.File({
new _winston.default.transports.File({
filename: "error.log",
level: "error"
}), new _winston["default"].transports.File({
}), new _winston.default.transports.File({
filename: "combined.log"
})]
}); //
@ -32,10 +32,10 @@ var logger = _winston["default"].createLogger({
if (process.env.NODE_ENV !== "production") {
logger.add(new _winston["default"].transports.Console({
format: _winston["default"].format.simple()
logger.add(new _winston.default.transports.Console({
format: _winston.default.format.simple()
}));
}
var _default = logger;
exports["default"] = _default;
exports.default = _default;

View File

@ -17,7 +17,6 @@ class OcrccBot {
this.awaitingFacilitator = {};
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
this.joinedRooms = [];
this.activeChatrooms = {};
}
createLocalStorage() {
@ -56,7 +55,7 @@ class OcrccBot {
}
});
});
return this.sendMessage(roomId, content);
await this.sendMessage(roomId, content);
default:
logger.log("error", `ERROR SENDING MESSAGE: ${err}`);
break;
@ -82,7 +81,7 @@ class OcrccBot {
}
async inviteFacilitators(roomId) {
this.awaitingFacilitator[roomId] = true;
this.localStorage.setItem(`${roomId}-waiting`, 'true')
let chatOffline = true;
try {
@ -114,7 +113,7 @@ class OcrccBot {
}
async uninviteFacilitators(roomId) {
this.awaitingFacilitator[roomId] = false;
this.localStorage.removeItem(`${roomId}-waiting`)
try {
const groupUsers = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
@ -173,7 +172,7 @@ class OcrccBot {
const time = date.toLocaleTimeString("en-GB", {
timeZone: "America/New_York"
});
const filepath = this.activeChatrooms[roomId].transcriptFile;
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
const message = `${sender} [${time}]: ${content.body}\n`;
fs.appendFileSync(filepath, message, "utf8");
@ -190,9 +189,6 @@ class OcrccBot {
const command = content.body.substring("!bot".length).trim();
switch (command) {
case "purge rooms":
this.leaveEmptyRooms(senderId);
break;
case "transcript":
this.sendTranscript(senderId, roomId);
break;
@ -246,9 +242,8 @@ class OcrccBot {
async sendTranscript(senderId, roomId) {
try {
const transcriptFile = this.activeChatrooms[roomId]
? this.activeChatrooms[roomId].transcriptFile
: false;
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
if (!transcriptFile) {
this.sendTextMessage(
roomId,
@ -320,17 +315,16 @@ class OcrccBot {
member.userId === this.config.BOT_USERID &&
!this.joinedRooms.includes(member.roomId)
) {
try {
const room = await this.client.joinRoom(member.roomId)
logger.log("info", "AUTO JOINED ROOM" + room.roomId)
logger.log("info", "AUTO JOINED ROOM => " + room.roomId)
this.sendTextMessage(
this.config.FACILITATOR_ROOM_ID,
`A support seeker requested a chat (Room ID: ${room.roomId})`
);
this.inviteFacilitators(room.roomId)
} catch(err) {
logger.log("error", "ERROR JOINING ROOM =>" + err)
logger.log("error", "ERROR JOINING ROOM => " + err)
}
}
@ -339,11 +333,9 @@ class OcrccBot {
if (
member.membership === "join" &&
member.userId !== this.config.BOT_USERID &&
this.awaitingFacilitator[member.roomId]
this.localStorage.getItem(`${member.roomId}-waiting`)
) {
this.activeChatrooms[member.roomId] = {
facilitator: member.userId
};
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId)
const event = {
getType: () => {
return "m.room.power_levels";
@ -380,7 +372,7 @@ class OcrccBot {
});
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
const filepath = path.resolve(path.join("transcripts", filename));
this.activeChatrooms[member.roomId].transcriptFile = filepath;
this.localStorage.setItem(`${member.roomId}-transcript`, filepath)
}
}
@ -388,8 +380,8 @@ class OcrccBot {
member.membership === "leave" &&
member.userId !== this.config.BOT_USERID
) {
if (this.activeChatrooms[member.roomId] && member.userId === this.activeChatrooms[member.roomId].facilitator) {
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
if (member.userId === facilitatorId) {
this.sendTextMessage(
member.roomId,
`${member.name} has left the chat.`
@ -404,13 +396,15 @@ class OcrccBot {
if (memberCount === 1) { // just the bot
logger.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
this.client.leave(event.roomId)
this.client.leave(member.roomId)
this.localStorage.removeItem(`${member.roomId}-facilitator`)
this.localStorage.removeItem(`${member.roomId}-transcript`)
}
}
});
}
setMessageListeners() {
async setMessageListeners() {
// encrypted messages
this.client.on("Event.decrypted", (event, err) => {
if (err) {
@ -442,6 +436,7 @@ class OcrccBot {
async start() {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage
try {
const auth = {
@ -465,7 +460,7 @@ class OcrccBot {
await this.trackJoinedRooms()
await this.client.initCrypto()
await this.setMembershipListeners();
this.setMessageListeners();
await this.setMessageListeners();
this.client.startClient({ initialSyncLimit: 0 })
} catch(err) {
this.handleBotCrash(undefined, err);

View File

@ -0,0 +1,5 @@
@help-bot:rhok.space [1:00:21 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [1:00:22 PM]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [1:00:28 PM]: hi
@help-bot:rhok.space [1:00:42 PM]: Facilitator Demo Account has left the chat.
@help-bot:rhok.space [1:00:42 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,5 @@
@help-bot:rhok.space [1:02:18 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [1:02:19 PM]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [1:02:23 PM]: ASDF
@help-bot:rhok.space [1:03:01 PM]: Facilitator Demo Account has left the chat.
@help-bot:rhok.space [1:03:02 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,6 @@
@help-bot:rhok.space [4:22:04 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [4:22:04 PM]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [4:22:15 PM]: hiiii
@39102030-6be0-43f8-9f77-2e4c961d719a:rhok.space [4:22:18 PM]: hihi
@ocrcc-facilitator-demo:rhok.space [4:22:25 PM]: oih
@help-bot:rhok.space [4:22:40 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,12 @@
@help-bot:rhok.space [4:23:09 PM]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [4:23:14 PM]: so
@9a3d4822-8ba4-4931-9736-db9d0ff2fdcb:rhok.space [4:23:20 PM]: ☺️
@9a3d4822-8ba4-4931-9736-db9d0ff2fdcb:rhok.space [4:23:27 PM]: 😄
@help-bot:rhok.space [4:23:35 PM]: Apr 22, 2020 - 4:23:09 PM - !IsZMQlwOgpsrfZdBQo:rhok.space.txt
@help-bot:rhok.space [4:23:35 PM]: Apr 22, 2020 - 4:23:09 PM - !IsZMQlwOgpsrfZdBQo:rhok.space.txt
@help-bot:rhok.space [4:24:17 PM]: Apr 22, 2020 - 4:23:09 PM - !IsZMQlwOgpsrfZdBQo:rhok.space.txt
@help-bot:rhok.space [4:24:17 PM]: Apr 22, 2020 - 4:23:09 PM - !IsZMQlwOgpsrfZdBQo:rhok.space.txt
@help-bot:rhok.space [4:24:17 PM]: Apr 22, 2020 - 4:23:09 PM - !IsZMQlwOgpsrfZdBQo:rhok.space.txt
@9a3d4822-8ba4-4931-9736-db9d0ff2fdcb:rhok.space [4:24:27 PM]: hey hey
@ocrcc-facilitator-demo:rhok.space [4:24:32 PM]: cool beans
@help-bot:rhok.space [4:24:45 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,5 @@
@help-bot:rhok.space [4:26:25 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [4:26:25 PM]: Facilitator Demo Account has joined the chat.
@df279781-646c-46e9-ad6a-565a4e31d0bb:rhok.space [4:26:36 PM]: so
@ocrcc-facilitator-demo:rhok.space [4:26:41 PM]: asdf
@help-bot:rhok.space [4:33:26 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,3 @@
@help-bot:rhok.space [4:33:45 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [4:33:45 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [4:34:48 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,5 @@
@help-bot:rhok.space [4:50:37 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [4:50:37 PM]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [4:50:45 PM]: hihi
@edd84c88-b2ab-4910-9eeb-595881f1c145:rhok.space [4:50:56 PM]: asdfasdf
@help-bot:rhok.space [4:51:04 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,5 @@
@help-bot:rhok.space [4:58:09 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [4:58:10 PM]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [4:58:28 PM]: kj
@e5221f47-38ce-47ae-b1c7-2921bd035362:rhok.space [4:58:34 PM]: kk
@help-bot:rhok.space [4:58:47 PM]: Facilitator Demo Account has left the chat.

View File

@ -0,0 +1,2 @@
@help-bot:rhok.space [5:28:23 PM]: Facilitator Demo Account has joined the chat.
@help-bot:rhok.space [5:28:24 PM]: Facilitator Demo Account has joined the chat.