Compare commits
No commits in common. "master" and "feature/add-dockerfile" have entirely different histories.
master
...
feature/ad
7
.env.sample
Normal file
7
.env.sample
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
MATRIX_SERVER_URL=
|
||||||
|
BOT_DISPLAY_NAME=
|
||||||
|
BOT_USERNAME=
|
||||||
|
BOT_PASSWORD=
|
||||||
|
BOT_USERID=
|
||||||
|
FACILITATOR_ROOM_ID=
|
||||||
|
CHAT_OFFLINE_MESSAGE=
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -3,4 +3,3 @@ node_modules
|
|||||||
*.log
|
*.log
|
||||||
__mocks__/test_transcript.txt
|
__mocks__/test_transcript.txt
|
||||||
transcripts/*.txt
|
transcripts/*.txt
|
||||||
config.json
|
|
@ -1,10 +1,5 @@
|
|||||||
FROM node:10-alpine
|
FROM node:10-alpine
|
||||||
|
|
||||||
RUN apk add g++ make python
|
|
||||||
RUN apk add tzdata
|
|
||||||
|
|
||||||
ENV TZ America/Montreal
|
|
||||||
|
|
||||||
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
|
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
|
||||||
|
|
||||||
WORKDIR /home/node/app
|
WORKDIR /home/node/app
|
||||||
|
29
README.md
29
README.md
@ -1,10 +1,20 @@
|
|||||||
# Safe Support Chat Bot
|
# Safe Support Chat Bot
|
||||||
|
|
||||||
A simple Matrix bot that handles inviting, uninviting, and notifying Riot users on the recieving end of the [Safe Support chatbox](https://github.com/Safe-Support-Chat/ocrcc-chatbox).
|
A simple Matrix bot that handles inviting, uninviting, and notifying Riot users on the recieving end of the [Safe Support chatbox](https://github.com/nomadic-labs/safesupport-chatbox).
|
||||||
|
|
||||||
The bot configuration file is `config.json`. It can also pull in user-set configurations from the Safe Support Chat Admin app. To do so, run the command `yarn setup` before starting the bot.
|
|
||||||
|
|
||||||
|
The bot can be configured with an `.env` file with the following variables:
|
||||||
|
|
||||||
|
```
|
||||||
|
MATRIX_SERVER_URL=
|
||||||
|
BOT_DISPLAY_NAME=
|
||||||
|
BOT_USERNAME=
|
||||||
|
BOT_PASSWORD=
|
||||||
|
BOT_USERID=
|
||||||
|
FACILITATOR_ROOM_ID=
|
||||||
|
FACILITATOR_GROUP_ID=
|
||||||
|
CHAT_OFFLINE_MESSAGE=
|
||||||
|
CAPTURE_TRANSCRIPTS=
|
||||||
|
```
|
||||||
## What does the bot do?
|
## What does the bot do?
|
||||||
* The bot receives an invitation to every chatroom created by the embedded chatbox, and automatically accepts
|
* The bot receives an invitation to every chatroom created by the embedded chatbox, and automatically accepts
|
||||||
* Upon joining a new room, the bot invites all of the members of the Facilitators community
|
* Upon joining a new room, the bot invites all of the members of the Facilitators community
|
||||||
@ -20,7 +30,7 @@ The bot configuration file is `config.json`. It can also pull in user-set config
|
|||||||
### Bot commands
|
### Bot commands
|
||||||
|
|
||||||
|Command|Response|
|
|Command|Response|
|
||||||
--- | ---
|
--- | ---
|
||||||
|`!bot hi`|Bot responds with a greeting|
|
|`!bot hi`|Bot responds with a greeting|
|
||||||
|`!bot transcript`|Bot sends the chat transcript as a .txt file|
|
|`!bot transcript`|Bot sends the chat transcript as a .txt file|
|
||||||
|`!bot transcript please`|Bot happily sends the transcript :)|
|
|`!bot transcript please`|Bot happily sends the transcript :)|
|
||||||
@ -30,7 +40,7 @@ If you prefer to develop locally instead of on Glitch:
|
|||||||
|
|
||||||
Clone the project
|
Clone the project
|
||||||
```
|
```
|
||||||
git clone https://github.com/Safe-Support-Chat/ocrcc-bot.git
|
git clone https://github.com/nomadic-labs/safesupport-bot.git
|
||||||
```
|
```
|
||||||
|
|
||||||
Install dependencies
|
Install dependencies
|
||||||
@ -39,14 +49,9 @@ cd safesupport-bot
|
|||||||
yarn
|
yarn
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy the sample config file and add in the missing values.
|
Copy the sample `.env` file and add in your own variables
|
||||||
```
|
```
|
||||||
cp sample.config.json config.json
|
cp .env.sample .env
|
||||||
```
|
|
||||||
|
|
||||||
Pull in the user-defined settings (if there are any).
|
|
||||||
```
|
|
||||||
yarn setup
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Start the local server
|
Start the local server
|
||||||
|
@ -157,10 +157,6 @@ export const mockGetGroupUsers = jest.fn(() => {
|
|||||||
|
|
||||||
export const mockGetUser = jest.fn().mockReturnValue({ presence: 'online'});
|
export const mockGetUser = jest.fn().mockReturnValue({ presence: 'online'});
|
||||||
|
|
||||||
export const mockSendStateEvent = jest.fn(() => {
|
|
||||||
return Promise.resolve();
|
|
||||||
});
|
|
||||||
|
|
||||||
export const mockClient = {
|
export const mockClient = {
|
||||||
registerRequest: mockRegisterRequest,
|
registerRequest: mockRegisterRequest,
|
||||||
initCrypto: mockInitCrypto,
|
initCrypto: mockInitCrypto,
|
||||||
@ -190,7 +186,6 @@ export const mockClient = {
|
|||||||
getJoinedRoomMembers: mockGetJoinedRoomMembers,
|
getJoinedRoomMembers: mockGetJoinedRoomMembers,
|
||||||
getUser: mockGetUser,
|
getUser: mockGetUser,
|
||||||
getGroupUsers: mockGetGroupUsers,
|
getGroupUsers: mockGetGroupUsers,
|
||||||
sendStateEvent: mockSendStateEvent,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const WebStorageSessionStore = jest.fn()
|
export const WebStorageSessionStore = jest.fn()
|
||||||
|
568
dist/bot.js
vendored
568
dist/bot.js
vendored
@ -23,22 +23,18 @@ var matrix = _interopRequireWildcard(require("matrix-js-sdk"));
|
|||||||
|
|
||||||
var _logger = _interopRequireDefault(require("./logger"));
|
var _logger = _interopRequireDefault(require("./logger"));
|
||||||
|
|
||||||
var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"));
|
|
||||||
|
|
||||||
global.Olm = require("olm");
|
global.Olm = require("olm");
|
||||||
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
|
|
||||||
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE';
|
|
||||||
|
|
||||||
class OcrccBot {
|
class OcrccBot {
|
||||||
constructor(config) {
|
constructor(botConfig) {
|
||||||
this.config = config;
|
this.config = botConfig;
|
||||||
this.client = matrix.createClient(this.config.matrixServerUrl);
|
this.awaitingFacilitator = {};
|
||||||
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
this.inactivityTimers = {};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createLocalStorage() {
|
createLocalStorage() {
|
||||||
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
|
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
|
||||||
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)) {
|
||||||
@ -49,47 +45,20 @@ class OcrccBot {
|
|||||||
return new _nodeLocalstorage.LocalStorage(localStoragePath);
|
return new _nodeLocalstorage.LocalStorage(localStoragePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTextMessage(roomId, msgText, showToUser = null) {
|
sendTextMessage(roomId, msgText, showToUser = null) {
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: msgText,
|
body: msgText,
|
||||||
showToUser: showToUser
|
showToUser: showToUser
|
||||||
};
|
};
|
||||||
await this.sendMessage(roomId, content);
|
this.sendMessage(roomId, content);
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
async sendMessage(roomId, content) {
|
||||||
|
_logger.default.log("info", `SENDING MESSAGE: ${content.body}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.client.sendMessage(roomId, content);
|
await this.client.sendMessage(roomId, content);
|
||||||
|
|
||||||
_logger.default.log("info", `SENT MESSAGE: ${content.body}`);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@ -105,16 +74,24 @@ class OcrccBot {
|
|||||||
await this.sendMessage(roomId, content);
|
await this.sendMessage(roomId, content);
|
||||||
|
|
||||||
default:
|
default:
|
||||||
_logger.default.log("error", `ERROR SENDING MESSAGE ${content.body}: ${err}`);
|
_logger.default.log("error", `ERROR SENDING MESSAGE: ${err}`);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inviteUserToRoom(roomId, member) {
|
||||||
|
try {
|
||||||
|
this.client.invite(roomId, member);
|
||||||
|
} catch (err) {
|
||||||
|
this.handleBotCrash(roomId, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
kickUserFromRoom(roomId, member) {
|
kickUserFromRoom(roomId, member) {
|
||||||
try {
|
try {
|
||||||
this.client.kick(roomId, member, this.config.kickReason);
|
this.client.kick(roomId, member, this.config.KICK_REASON);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
|
|
||||||
@ -122,50 +99,27 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async inviteFacilitatorIfOnline(roomId, memberId) {
|
|
||||||
const user = this.client.getUser(memberId);
|
|
||||||
|
|
||||||
if (user && user.presence !== "offline" && memberId !== this.config.botUserId) {
|
|
||||||
try {
|
|
||||||
this.client.invite(roomId, memberId);
|
|
||||||
|
|
||||||
_logger.default.log("info", `CHAT INVITATION SENT TO ${memberId} FOR ROOM ${roomId}`);
|
|
||||||
|
|
||||||
return memberId;
|
|
||||||
} catch (err) {
|
|
||||||
this.handleBotCrash(roomId, err);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
|
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
||||||
|
let chatOffline = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
const data = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID);
|
||||||
let invitations = [];
|
const members = data.chunk;
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
|
members.forEach(member => {
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const memberId = member.user_id;
|
||||||
|
const user = this.client.getUser(memberId);
|
||||||
|
|
||||||
for (const memberId of members) {
|
if (user && user.presence === "online" && memberId !== this.config.BOT_USERID) {
|
||||||
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId);
|
chatOffline = false;
|
||||||
invitations.push(invited);
|
this.inviteUserToRoom(roomId, memberId);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (invitations.filter(i => i).length > 0) {
|
if (chatOffline) {
|
||||||
this.localStorage.setItem(`${roomId}-invitations`, invitations);
|
_logger.default.log('info', "NO FACILITATORS ONLINE");
|
||||||
} else {
|
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE); // send notification to Support Chat Notifications room
|
|
||||||
|
|
||||||
const currentDate = new Date();
|
this.sendTextMessage(roomId, this.config.CHAT_OFFLINE_MESSAGE);
|
||||||
const closedTime = currentDate.toLocaleTimeString();
|
|
||||||
const roomRef = roomId.split(':')[0];
|
|
||||||
const notification = `No facilitators were online, chat closed at ${closedTime} (room ID: ${roomRef})`;
|
|
||||||
|
|
||||||
_logger.default.log('info', `NO FACILITATORS ONLINE, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
|
|
||||||
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
@ -175,15 +129,15 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async uninviteFacilitators(roomId) {
|
async uninviteFacilitators(roomId) {
|
||||||
|
this.localStorage.removeItem(`${roomId}-waiting`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.localStorage.removeItem(`${roomId}-waiting`);
|
const groupUsers = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID);
|
||||||
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
|
const roomMembers = await this.client.getJoinedRoomMembers(roomId);
|
||||||
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
|
const membersIds = Object.keys(roomMembers["joined"]);
|
||||||
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
|
const facilitatorsIds = groupUsers.chunk.map(f => f.user_id);
|
||||||
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
|
|
||||||
if (!roomMembersIds || !facilitatorsIds) return;
|
|
||||||
facilitatorsIds.forEach(f => {
|
facilitatorsIds.forEach(f => {
|
||||||
if (!roomMembersIds.includes(f)) {
|
if (!membersIds.includes(f)) {
|
||||||
this.kickUserFromRoom(roomId, f);
|
this.kickUserFromRoom(roomId, f);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -196,27 +150,17 @@ class OcrccBot {
|
|||||||
|
|
||||||
handleBotCrash(roomId, error) {
|
handleBotCrash(roomId, error) {
|
||||||
if (roomId) {
|
if (roomId) {
|
||||||
this.sendTextMessage(roomId, this.config.botErrorMessage);
|
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, `${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`);
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMessageEvent(event) {
|
handleMessageEvent(event) {
|
||||||
const content = event.getContent();
|
const content = event.getContent(); // do nothing if there's no content
|
||||||
const sender = event.getSender();
|
|
||||||
const roomId = event.getRoomId(); // do nothing if there's no content
|
|
||||||
|
|
||||||
if (!content) {
|
if (!content) {
|
||||||
return;
|
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
|
} // bot commands
|
||||||
|
|
||||||
|
|
||||||
@ -225,7 +169,7 @@ class OcrccBot {
|
|||||||
} // write to transcript
|
} // write to transcript
|
||||||
|
|
||||||
|
|
||||||
if (this.config.captureTranscripts) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
return this.writeToTranscript(event);
|
return this.writeToTranscript(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -242,7 +186,7 @@ class OcrccBot {
|
|||||||
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
|
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!filepath) {
|
if (!filepath) {
|
||||||
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
|
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `${sender} [${time}]: ${content.body}\n`;
|
const message = `${sender} [${time}]: ${content.body}\n`;
|
||||||
@ -253,56 +197,37 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleBotCommand(event) {
|
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);
|
|
||||||
}
|
|
||||||
}, {
|
|
||||||
keyword: 'bug',
|
|
||||||
function: (senderId, roomId) => {
|
|
||||||
const message = `Please report the issue at ${this.config.bugReportUrl}`;
|
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const senderId = event.getSender();
|
const senderId = event.getSender();
|
||||||
const roomId = event.getRoomId();
|
const roomId = event.getRoomId();
|
||||||
const content = event.getContent();
|
const content = event.getContent();
|
||||||
const commandText = content.body.substring("!bot".length).trim();
|
const command = content.body.substring("!bot".length).trim();
|
||||||
const command = botCommands.find(c => commandText.startsWith(c.keyword));
|
|
||||||
|
|
||||||
if (!command) {
|
switch (command) {
|
||||||
this.sendTextMessage(roomId, `Sorry, I don't know that command. I'm not a very smart bot.`, senderId);
|
case "transcript":
|
||||||
|
this.sendTranscript(senderId, roomId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "transcript please":
|
||||||
|
this.sendTranscript(senderId, roomId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "hi":
|
||||||
|
const responses = ["Hi!", "Hello", "Hey :)", "Hi there", "Bleep bloop"];
|
||||||
|
const message = responses[Math.floor(Math.random() * responses.length)];
|
||||||
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
this.sendTextMessage(roomId, `Sorry, I don't know that command. I'm not a very smart bot.`, senderId);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
const args = commandText.substring(command.keyword.length).trim();
|
|
||||||
command.function(senderId, roomId, args);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
_logger.default.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveEmptyRooms() {
|
async leaveEmptyRooms(senderId) {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms();
|
const roomData = await this.client.getJoinedRooms();
|
||||||
const joinedRoomsIds = roomData["joined_rooms"];
|
const joinedRoomsIds = roomData["joined_rooms"];
|
||||||
@ -311,16 +236,16 @@ class OcrccBot {
|
|||||||
|
|
||||||
if (room && room.getJoinedMemberCount() === 1) {
|
if (room && room.getJoinedMemberCount() === 1) {
|
||||||
try {
|
try {
|
||||||
await this.client.leave(roomId);
|
_logger.default.log('info', "LEAVING EMPTY ROOM => " + roomId);
|
||||||
|
|
||||||
_logger.default.log('info', `LEAVING EMPTY ROOM => ${roomId}`);
|
await this.client.leave(roomId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`);
|
_logger.default.log('error', "ERROR LEAVING EMPTY ROOM => " + err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
|
_logger.default.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -329,58 +254,22 @@ class OcrccBot {
|
|||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
this.sendTextMessage(roomId, "Cannot send transcript, there is no transcript for this chat.", senderId);
|
this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.client.isRoomEncrypted(roomId)) {
|
const filename = path.basename(transcriptFile) || "Transcript";
|
||||||
let encryptInfo;
|
const stream = fs.createReadStream(transcriptFile);
|
||||||
const filename = path.basename(transcriptFile) || "Transcript";
|
const contentUrl = await this.client.uploadContent({
|
||||||
const data = fs.readFileSync(transcriptFile);
|
stream: stream,
|
||||||
const encryptResult = await _encryptAttachment.default.encryptAttachment(data);
|
name: filename
|
||||||
const buffer = Buffer.from(encryptResult.data);
|
});
|
||||||
encryptInfo = encryptResult.info;
|
const content = {
|
||||||
const url = await this.client.uploadContent(buffer, {
|
msgtype: "m.file",
|
||||||
rawResponse: false,
|
body: filename,
|
||||||
name: filename
|
url: JSON.parse(contentUrl).content_uri,
|
||||||
});
|
showToUser: senderId
|
||||||
encryptInfo.url = url.content_uri;
|
};
|
||||||
encryptInfo.mimetype = 'text/plain';
|
this.sendMessage(roomId, content);
|
||||||
const content = {
|
|
||||||
msgtype: "m.file",
|
|
||||||
body: filename,
|
|
||||||
info: {
|
|
||||||
mimetype: 'text/plain'
|
|
||||||
},
|
|
||||||
file: encryptInfo,
|
|
||||||
url: url.content_uri,
|
|
||||||
showToUser: senderId,
|
|
||||||
mimetype: 'text/plain'
|
|
||||||
};
|
|
||||||
this.sendMessage(roomId, content);
|
|
||||||
} else {
|
|
||||||
const filename = path.basename(transcriptFile) || "Transcript";
|
|
||||||
const file = fs.readFileSync(transcriptFile);
|
|
||||||
const stats = fs.statSync(transcriptFile);
|
|
||||||
const url = await this.client.uploadContent(file, {
|
|
||||||
rawResponse: false,
|
|
||||||
name: filename
|
|
||||||
});
|
|
||||||
|
|
||||||
_logger.default.log('info', url);
|
|
||||||
|
|
||||||
const content = {
|
|
||||||
msgtype: "m.file",
|
|
||||||
body: filename,
|
|
||||||
info: {
|
|
||||||
size: stats.size,
|
|
||||||
mimetype: 'text/plain'
|
|
||||||
},
|
|
||||||
url: url.content_uri,
|
|
||||||
showToUser: senderId,
|
|
||||||
mimetype: 'text/plain'
|
|
||||||
};
|
|
||||||
this.sendMessage(roomId, content);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", `ERROR UPLOADING CONTENT: ${err}`);
|
_logger.default.log("error", `ERROR UPLOADING CONTENT: ${err}`);
|
||||||
|
|
||||||
@ -388,32 +277,6 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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() {
|
async deleteOldDevices() {
|
||||||
const currentDeviceId = this.client.getDeviceId();
|
const currentDeviceId = this.client.getDeviceId();
|
||||||
const deviceData = await this.client.getDevices();
|
const deviceData = await this.client.getDevices();
|
||||||
@ -428,12 +291,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.botUserId,
|
user: this.config.BOT_USERID,
|
||||||
identifier: {
|
identifier: {
|
||||||
type: "m.id.user",
|
type: "m.id.user",
|
||||||
user: this.config.botUserId
|
user: this.config.BOT_USERID
|
||||||
},
|
},
|
||||||
password: this.config.botPassword
|
password: this.config.BOT_PASSWORD
|
||||||
};
|
};
|
||||||
await this.client.deleteMultipleDevices(oldDevices, auth);
|
await this.client.deleteMultipleDevices(oldDevices, auth);
|
||||||
|
|
||||||
@ -451,187 +314,82 @@ 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.botUserId && !this.joinedRooms.includes(member.roomId)) {
|
if (member.membership === "invite" && member.userId === this.config.BOT_USERID && !this.joinedRooms.includes(member.roomId)) {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms();
|
const room = await this.client.joinRoom(member.roomId);
|
||||||
const joinedRooms = roomData["joined_rooms"];
|
|
||||||
|
|
||||||
if (!joinedRooms.includes(member.roomId)) {
|
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
|
||||||
const room = await this.client.joinRoom(member.roomId);
|
|
||||||
|
|
||||||
_logger.default.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);
|
||||||
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) {
|
} catch (err) {
|
||||||
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
|
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
|
||||||
}
|
}
|
||||||
}
|
} // When a facilitator joins a support session, make them a moderator
|
||||||
|
// revoke the other invitations
|
||||||
|
|
||||||
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) {
|
if (member.membership === "join" && member.userId !== this.config.BOT_USERID && this.localStorage.getItem(`${member.roomId}-waiting`)) {
|
||||||
// made facilitator a moderator in the room
|
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
|
||||||
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
|
const event = {
|
||||||
const event = {
|
getType: () => {
|
||||||
getType: () => {
|
return "m.room.power_levels";
|
||||||
return "m.room.power_levels";
|
},
|
||||||
},
|
getContent: () => {
|
||||||
getContent: () => {
|
return {
|
||||||
return {
|
users: {
|
||||||
users: {
|
[this.config.BOT_USERID]: 100,
|
||||||
[this.config.botUserId]: 100,
|
[member.userId]: 50
|
||||||
[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.default.log("error", `ERROR WHEN FACILITATOR JOINED ROOM ==> ${err}`);
|
this.client.setPowerLevel(member.roomId, member.userId, 50, event);
|
||||||
|
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`);
|
||||||
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `${member.name} joined the chat (Room ID: ${member.roomId})`);
|
||||||
|
this.uninviteFacilitators(member.roomId);
|
||||||
|
|
||||||
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
|
const currentDate = new Date();
|
||||||
|
const dateOpts = {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric"
|
||||||
|
};
|
||||||
|
const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
|
||||||
|
const chatTime = currentDate.toLocaleTimeString("en-GB", {
|
||||||
|
timeZone: "America/New_York"
|
||||||
|
});
|
||||||
|
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
|
||||||
|
const filepath = path.resolve(path.join("transcripts", filename));
|
||||||
|
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (member.membership === "leave" && member.userId !== this.config.botUserId) {
|
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
|
||||||
// notify room if the facilitator has left
|
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
||||||
try {
|
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
|
||||||
|
|
||||||
if (member.userId === facilitatorId) {
|
if (member.userId === facilitatorId) {
|
||||||
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`); // send notification to Support Chat Notifications room
|
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`);
|
||||||
|
} // leave if there is nobody in the 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.default.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 memberCount = room.getJoinedMemberCount();
|
||||||
// leave if there is nobody in the room
|
|
||||||
|
|
||||||
try {
|
if (memberCount === 1) {
|
||||||
const memberCount = roomMembers.length;
|
// just the bot
|
||||||
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId));
|
_logger.default.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
|
||||||
|
|
||||||
if (memberCount === 1 && isBotInRoom) {
|
this.client.leave(member.roomId);
|
||||||
// just the bot left
|
this.localStorage.removeItem(`${member.roomId}-facilitator`);
|
||||||
_logger.default.log("info", `LEAVING EMPTY ROOM: ${member.roomId}`);
|
this.localStorage.removeItem(`${member.roomId}-transcript`);
|
||||||
|
|
||||||
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}`);
|
|
||||||
} // send signal to close the chat if there are no facilitators in the room
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
|
||||||
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId); // object
|
|
||||||
|
|
||||||
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.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}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeoutforFacilitator(roomId) {
|
|
||||||
setTimeout(async () => {
|
|
||||||
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`);
|
|
||||||
|
|
||||||
if (stillWaiting) {
|
|
||||||
await this.sendTextMessage(roomId, this.config.chatNotAvailableMessage);
|
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT); // send notification to Support Chat Notifications room
|
|
||||||
|
|
||||||
const currentDate = new Date();
|
|
||||||
const closedTime = currentDate.toLocaleTimeString();
|
|
||||||
const roomRef = roomId.split(':')[0];
|
|
||||||
const notification = `No facilitators joined the chat within the maximum wait time, chat closed at ${closedTime} (room ID: ${roomRef})`;
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
|
|
||||||
_logger.default.log("info", `NO FACILITATORS JOINED THE CHAT WITHIN THE MAXIMUM WAIT TIME, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
|
|
||||||
}
|
|
||||||
}, this.config.maxWaitTime * 1000); // convert seconds to milliseconds
|
|
||||||
}
|
|
||||||
|
|
||||||
setInactivityTimeout(roomId) {
|
|
||||||
const oldTimeout = this.inactivityTimers[roomId];
|
|
||||||
|
|
||||||
if (oldTimeout) {
|
|
||||||
clearTimeout(oldTimeout);
|
|
||||||
}
|
|
||||||
|
|
||||||
const newTimeout = setTimeout(async () => {
|
|
||||||
_logger.default.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 * 1000); // convert seconds to milliseconds
|
|
||||||
|
|
||||||
this.inactivityTimers[roomId] = newTimeout;
|
|
||||||
}
|
|
||||||
|
|
||||||
async setMessageListeners() {
|
async setMessageListeners() {
|
||||||
// encrypted messages
|
// encrypted messages
|
||||||
this.client.on("Event.decrypted", (event, err) => {
|
this.client.on("Event.decrypted", (event, err) => {
|
||||||
@ -651,55 +409,47 @@ class OcrccBot {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendBotSignal(roomId, signal, args) {
|
async leaveOldRooms() {
|
||||||
let content = {
|
const roomData = await this.client.getJoinedRooms();
|
||||||
signal: signal,
|
roomData["joined_rooms"].forEach(async roomId => {
|
||||||
args: args
|
try {
|
||||||
};
|
await this.client.leave(roomId);
|
||||||
|
} catch (err) {
|
||||||
try {
|
_logger.default.log('error', "ERROR LEAVING ROOM => " + err);
|
||||||
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
|
}
|
||||||
} catch (err) {
|
});
|
||||||
_logger.default.log('error', "ERROR SENDING BOT SIGNAL => " + err);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
|
const localStorage = this.createLocalStorage();
|
||||||
|
this.localStorage = localStorage;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const localStorage = this.createLocalStorage();
|
|
||||||
this.localStorage = localStorage;
|
|
||||||
const auth = {
|
const auth = {
|
||||||
user: this.config.botUsername,
|
user: this.config.BOT_USERNAME,
|
||||||
password: this.config.botPassword,
|
password: this.config.BOT_PASSWORD,
|
||||||
initial_device_display_name: this.config.botDisplayName
|
initial_device_display_name: this.config.BOT_DISPLAY_NAME
|
||||||
};
|
};
|
||||||
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.matrixServerUrl,
|
baseUrl: this.config.MATRIX_SERVER_URL,
|
||||||
accessToken: account.access_token,
|
accessToken: account.access_token,
|
||||||
userId: this.config.botUserId,
|
userId: this.config.BOT_USERID,
|
||||||
deviceId: account.device_id,
|
deviceId: account.device_id,
|
||||||
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
||||||
};
|
};
|
||||||
this.client = matrix.createClient(opts);
|
this.client = matrix.createClient(opts);
|
||||||
|
await this.deleteOldDevices();
|
||||||
|
await this.trackJoinedRooms();
|
||||||
await this.client.initCrypto();
|
await this.client.initCrypto();
|
||||||
|
await this.setMembershipListeners();
|
||||||
|
await this.setMessageListeners();
|
||||||
this.client.startClient({
|
this.client.startClient({
|
||||||
initialSyncLimit: 0
|
initialSyncLimit: 0
|
||||||
});
|
});
|
||||||
this.client.once('sync', async (state, prevState, data) => {
|
|
||||||
_logger.default.log("info", `SYNC STATUS: ${state}`);
|
|
||||||
|
|
||||||
if (state === 'PREPARED') {
|
|
||||||
await this.deleteOldDevices();
|
|
||||||
await this.leaveEmptyRooms();
|
|
||||||
await this.trackJoinedRooms();
|
|
||||||
await this.setMembershipListeners();
|
|
||||||
await this.setMessageListeners();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(undefined, err);
|
this.handleBotCrash(undefined, err);
|
||||||
|
|
||||||
|
72
dist/bot.test.js
vendored
72
dist/bot.test.js
vendored
@ -18,36 +18,6 @@ var _bot = _interopRequireDefault(require("./bot"));
|
|||||||
|
|
||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
|
|
||||||
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,
|
|
||||||
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_ROOM_ID,
|
|
||||||
CHAT_OFFLINE_MESSAGE,
|
|
||||||
CAPTURE_TRANSCRIPTS
|
|
||||||
};
|
|
||||||
const mockAppendFileSync = jest.fn();
|
const mockAppendFileSync = jest.fn();
|
||||||
fs.appendFileSync = mockAppendFileSync;
|
fs.appendFileSync = mockAppendFileSync;
|
||||||
describe('OcrccBot', () => {
|
describe('OcrccBot', () => {
|
||||||
@ -103,21 +73,21 @@ describe('OcrccBot', () => {
|
|||||||
mockAppendFileSync.mockClear();
|
mockAppendFileSync.mockClear();
|
||||||
|
|
||||||
_matrixJsSdk.mockGetGroupUsers.mockClear();
|
_matrixJsSdk.mockGetGroupUsers.mockClear();
|
||||||
|
|
||||||
_matrixJsSdk.mockSendStateEvent.mockClear();
|
|
||||||
});
|
});
|
||||||
test('constructor should inititialize class variables', () => {
|
test('constructor should inititialize class variables', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
expect(bot.joinedRooms).toEqual([]);
|
expect(bot.joinedRooms).toEqual([]);
|
||||||
|
expect(bot.awaitingFacilitator).toEqual({});
|
||||||
|
expect(bot.activeChatrooms).toEqual({});
|
||||||
});
|
});
|
||||||
test('#createLocalStorage should have correct storage location', () => {
|
test('#createLocalStorage should have correct storage location', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
const localStorage = bot.createLocalStorage();
|
const localStorage = bot.createLocalStorage();
|
||||||
const localStoragePath = path.resolve(path.join(os.homedir(), ".local-storage", `matrix-chatbot-${process.env.BOT_USERNAME}`));
|
const localStoragePath = path.resolve(path.join(os.homedir(), ".local-storage", `matrix-chatbot-${process.env.BOT_USERNAME}`));
|
||||||
expect(localStorage._location).toBe(localStoragePath);
|
expect(localStorage._location).toBe(localStoragePath);
|
||||||
});
|
});
|
||||||
test('#sendMessage should send a text message', () => {
|
test('#sendMessage should send a text message', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -133,7 +103,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#inviteUserToRoom should add member to room and retry on rate limit error', () => {
|
test('#inviteUserToRoom should add member to room and retry on rate limit error', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -144,7 +114,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#kickUserFromRoom should remove member from room and retry on rate limit error', () => {
|
test('#kickUserFromRoom should remove member from room and retry on rate limit error', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -155,7 +125,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#inviteFacilitators should invite all members from Facilitator room', () => {
|
test('#inviteFacilitators should invite all members from Facilitator room', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -172,7 +142,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#uninviteFacilitators should remove all members that have not accepted the invite', () => {
|
test('#uninviteFacilitators should remove all members that have not accepted the invite', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -189,7 +159,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#handleBotCrash should notify rooms', () => {
|
test('#handleBotCrash should notify rooms', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -203,9 +173,11 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#writeToTranscript should parse event and write to transcript file', () => {
|
test('#writeToTranscript should parse event and write to transcript file', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
bot.localStorage.setItem(`test_room_id-transcript`, '__mocks__/test_transcript.txt');
|
bot.activeChatrooms['test_room_id'] = {
|
||||||
|
transcriptFile: '__mocks__/test_transcript.txt'
|
||||||
|
};
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
@ -227,7 +199,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#deleteOldDevices should delete old sessions', () => {
|
test('#deleteOldDevices should delete old sessions', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@ -245,7 +217,7 @@ describe('OcrccBot', () => {
|
|||||||
}); // TODO test listeners for membership events and message events
|
}); // TODO test listeners for membership events and message events
|
||||||
|
|
||||||
test('#start should start bot and set up listeners', () => {
|
test('#start should start bot and set up listeners', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default();
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockLogin).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockLogin).toHaveBeenCalled();
|
||||||
@ -278,16 +250,4 @@ describe('OcrccBot', () => {
|
|||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#sendBotSignal should send custom state event', () => {
|
|
||||||
const bot = new _bot.default(botConfig);
|
|
||||||
bot.start();
|
|
||||||
const test_room_id = 'test_room_id';
|
|
||||||
const signal = 'END_CHAT';
|
|
||||||
bot.sendBotSignal(test_room_id, signal);
|
|
||||||
(0, _waitForExpect.default)(() => {
|
|
||||||
expect(_matrixJsSdk.mockSendStateEvent).toHaveBeenCalledWith(test_room_id, 'm.bot.signal', {
|
|
||||||
signal
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
173
dist/encrypt-attachment.js
vendored
173
dist/encrypt-attachment.js
vendored
@ -1,173 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
|
|
||||||
// this is from https://github.com/matrix-org/browser-encrypt-attachment
|
|
||||||
// which is the library used by matrix-reack-sdk to encrypt and decrypt attachments
|
|
||||||
// just dropped in node-webcrypto-ossl to replace window.crypto
|
|
||||||
// and Buffer for base64 encoding/decoding instead of window.btoa/window.atob
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encrypt an attachment.
|
|
||||||
* @param {ArrayBuffer} plaintextBuffer The attachment data buffer.
|
|
||||||
* @return {Promise} A promise that resolves with an object when the attachment is encrypted.
|
|
||||||
* The object has a "data" key with an ArrayBuffer of encrypted data and an "info" key
|
|
||||||
* with an object containing the info needed to decrypt the data.
|
|
||||||
*/
|
|
||||||
const {
|
|
||||||
Crypto
|
|
||||||
} = require("node-webcrypto-ossl");
|
|
||||||
|
|
||||||
const crypto = new Crypto();
|
|
||||||
|
|
||||||
function encryptAttachment(plaintextBuffer) {
|
|
||||||
var cryptoKey; // The AES key object.
|
|
||||||
|
|
||||||
var exportedKey; // The AES key exported as JWK.
|
|
||||||
|
|
||||||
var ciphertextBuffer; // ArrayBuffer of encrypted data.
|
|
||||||
|
|
||||||
var sha256Buffer; // ArrayBuffer of digest.
|
|
||||||
|
|
||||||
var ivArray; // Uint8Array of AES IV
|
|
||||||
// Generate an IV where the first 8 bytes are random and the high 8 bytes
|
|
||||||
// are zero. We set the counter low bits to 0 since it makes it unlikely
|
|
||||||
// that the 64 bit counter will overflow.
|
|
||||||
|
|
||||||
ivArray = new Uint8Array(16);
|
|
||||||
crypto.getRandomValues(ivArray.subarray(0, 8)); // Load the encryption key.
|
|
||||||
|
|
||||||
return crypto.subtle.generateKey({
|
|
||||||
"name": "AES-CTR",
|
|
||||||
length: 256
|
|
||||||
}, true, ["encrypt", "decrypt"]).then(function (generateKeyResult) {
|
|
||||||
cryptoKey = generateKeyResult; // Export the Key as JWK.
|
|
||||||
|
|
||||||
return crypto.subtle.exportKey("jwk", cryptoKey);
|
|
||||||
}).then(function (exportKeyResult) {
|
|
||||||
exportedKey = exportKeyResult; // Encrypt the input ArrayBuffer.
|
|
||||||
// Use half of the iv as the counter by setting the "length" to 64.
|
|
||||||
|
|
||||||
return crypto.subtle.encrypt({
|
|
||||||
name: "AES-CTR",
|
|
||||||
counter: ivArray,
|
|
||||||
length: 64
|
|
||||||
}, cryptoKey, plaintextBuffer);
|
|
||||||
}).then(function (encryptResult) {
|
|
||||||
ciphertextBuffer = encryptResult; // SHA-256 the encrypted data.
|
|
||||||
|
|
||||||
return crypto.subtle.digest("SHA-256", ciphertextBuffer);
|
|
||||||
}).then(function (digestResult) {
|
|
||||||
sha256Buffer = digestResult;
|
|
||||||
return {
|
|
||||||
data: ciphertextBuffer,
|
|
||||||
info: {
|
|
||||||
v: "v2",
|
|
||||||
key: exportedKey,
|
|
||||||
iv: encodeBase64(ivArray),
|
|
||||||
hashes: {
|
|
||||||
sha256: encodeBase64(new Uint8Array(sha256Buffer))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Decrypt an attachment.
|
|
||||||
* @param {ArrayBuffer} ciphertextBuffer The encrypted attachment data buffer.
|
|
||||||
* @param {Object} info The information needed to decrypt the attachment.
|
|
||||||
* @param {Object} info.key AES-CTR JWK key object.
|
|
||||||
* @param {string} info.iv Base64 encoded 16 byte AES-CTR IV.
|
|
||||||
* @param {string} info.hashes.sha256 Base64 encoded SHA-256 hash of the ciphertext.
|
|
||||||
* @return {Promise} A promise that resolves with an ArrayBuffer when the attachment is decrypted.
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function decryptAttachment(ciphertextBuffer, info) {
|
|
||||||
if (info === undefined || info.key === undefined || info.iv === undefined || info.hashes === undefined || info.hashes.sha256 === undefined) {
|
|
||||||
throw new Error("Invalid info. Missing info.key, info.iv or info.hashes.sha256 key");
|
|
||||||
}
|
|
||||||
|
|
||||||
var cryptoKey; // The AES key object.
|
|
||||||
|
|
||||||
var ivArray = decodeBase64(info.iv);
|
|
||||||
var expectedSha256base64 = info.hashes.sha256; // Load the AES from the "key" key of the info object.
|
|
||||||
|
|
||||||
return crypto.subtle.importKey("jwk", info.key, {
|
|
||||||
"name": "AES-CTR"
|
|
||||||
}, false, ["encrypt", "decrypt"]).then(function (importKeyResult) {
|
|
||||||
cryptoKey = importKeyResult; // Check the sha256 hash
|
|
||||||
|
|
||||||
return crypto.subtle.digest("SHA-256", ciphertextBuffer);
|
|
||||||
}).then(function (digestResult) {
|
|
||||||
if (encodeBase64(new Uint8Array(digestResult)) != expectedSha256base64) {
|
|
||||||
throw new Error("Mismatched SHA-256 digest");
|
|
||||||
}
|
|
||||||
|
|
||||||
var counterLength;
|
|
||||||
|
|
||||||
if (info.v == "v1" || info.v == "v2") {
|
|
||||||
// Version 1 and 2 use a 64 bit counter.
|
|
||||||
counterLength = 64;
|
|
||||||
} else {
|
|
||||||
// Version 0 uses a 128 bit counter.
|
|
||||||
counterLength = 128;
|
|
||||||
}
|
|
||||||
|
|
||||||
return crypto.subtle.decrypt({
|
|
||||||
name: "AES-CTR",
|
|
||||||
counter: ivArray,
|
|
||||||
length: counterLength
|
|
||||||
}, cryptoKey, ciphertextBuffer);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Encode a typed array of uint8 as base64.
|
|
||||||
* @param {Uint8Array} uint8Array The data to encode.
|
|
||||||
* @return {string} The base64 without padding.
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function encodeBase64(uint8Array) {
|
|
||||||
// Misinterpt the Uint8Array as Latin-1.
|
|
||||||
// window.btoa expects a unicode string with codepoints in the range 0-255.
|
|
||||||
var latin1String = String.fromCharCode.apply(null, uint8Array); // Use the builtin base64 encoder.
|
|
||||||
// var paddedBase64 = window.btoa(latin1String);
|
|
||||||
|
|
||||||
var paddedBase64 = Buffer.from(latin1String, 'binary').toString('base64'); // Calculate the unpadded length.
|
|
||||||
|
|
||||||
var inputLength = uint8Array.length;
|
|
||||||
var outputLength = 4 * Math.floor((inputLength + 2) / 3) + (inputLength + 2) % 3 - 2; // Return the unpadded base64.
|
|
||||||
|
|
||||||
return paddedBase64.slice(0, outputLength);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Decode a base64 string to a typed array of uint8.
|
|
||||||
* This will decode unpadded base64, but will also accept base64 with padding.
|
|
||||||
* @param {string} base64 The unpadded base64 to decode.
|
|
||||||
* @return {Uint8Array} The decoded data.
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function decodeBase64(base64) {
|
|
||||||
// Pad the base64 up to the next multiple of 4.
|
|
||||||
var paddedBase64 = base64 + "===".slice(0, (4 - base64.length % 4) % 4); // Decode the base64 as a misinterpreted Latin-1 string.
|
|
||||||
// window.atob returns a unicode string with codepoints in the range 0-255.
|
|
||||||
// var latin1String = window.atob(paddedBase64);
|
|
||||||
|
|
||||||
var latin1String = Buffer.from(paddedBase64, 'base64').toString('binary'); // Encode the string as a Uint8Array as Latin-1.
|
|
||||||
|
|
||||||
var uint8Array = new Uint8Array(latin1String.length);
|
|
||||||
|
|
||||||
for (var i = 0; i < latin1String.length; i++) {
|
|
||||||
uint8Array[i] = latin1String.charCodeAt(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
return uint8Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
exports.encryptAttachment = encryptAttachment;
|
|
||||||
exports.decryptAttachment = decryptAttachment;
|
|
||||||
} catch (e) {// Ignore unknown variable "exports" errors when this is loaded directly into a browser
|
|
||||||
// This means that we can test it without having to use browserify.
|
|
||||||
// The intention is that the library is used using browserify.
|
|
||||||
}
|
|
43
dist/index.js
vendored
43
dist/index.js
vendored
@ -2,14 +2,41 @@
|
|||||||
|
|
||||||
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"));
|
||||||
|
|
||||||
const bot = new _bot.default(_config.default);
|
require('dotenv').config();
|
||||||
|
|
||||||
try {
|
const ENCRYPTION_CONFIG = {
|
||||||
bot.start();
|
algorithm: "m.megolm.v1.aes-sha2"
|
||||||
} catch (err) {
|
};
|
||||||
console.log("Unable to start bot", err);
|
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();
|
54
dist/setup.js
vendored
54
dist/setup.js
vendored
@ -1,54 +0,0 @@
|
|||||||
"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 === 'platform') {
|
|
||||||
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();
|
|
@ -1,12 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "private-safesupport-bot",
|
"name": "safesupport-bot",
|
||||||
"version": "3.1.0",
|
"version": "1.0.0",
|
||||||
"description": "Chatbot to manage interactions on Safe Support Chat",
|
"description": "Chatbot to manage interactions on Safe Support Chat",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"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,10 +13,8 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"matrix-js-sdk": "^6.2.1",
|
"matrix-js-sdk": "^5.0.1",
|
||||||
"node-fetch": "^2.6.1",
|
|
||||||
"node-localstorage": "^2.1.5",
|
"node-localstorage": "^2.1.5",
|
||||||
"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",
|
||||||
"uuidv4": "^6.0.2",
|
"uuidv4": "^6.0.2",
|
||||||
"winston": "^3.2.1"
|
"winston": "^3.2.1"
|
||||||
|
@ -1,16 +0,0 @@
|
|||||||
{
|
|
||||||
"matrixServerUrl": "",
|
|
||||||
"settingsEndpoint": "",
|
|
||||||
"facilitatorRoomId": "",
|
|
||||||
"kickReason": "A facilitator has already joined this chat.",
|
|
||||||
"botErrorMessage": "Something went wrong on our end, please restart the chat and try again.",
|
|
||||||
"botUserId": "",
|
|
||||||
"botUsername": "",
|
|
||||||
"botPassword": "",
|
|
||||||
"botDisplayName": "Help Bot",
|
|
||||||
"captureTranscripts": true,
|
|
||||||
"chatNotAvailableMessage": "The support chat is not available right now.",
|
|
||||||
"chatInactiveMessage": "This chat has been closed due to inactivity.",
|
|
||||||
"maxWaitTime": 180,
|
|
||||||
"maxInactiveTime": 3600
|
|
||||||
}
|
|
577
src/bot.js
577
src/bot.js
@ -9,21 +9,17 @@ global.Olm = require("olm");
|
|||||||
import * as matrix from "matrix-js-sdk";
|
import * as matrix from "matrix-js-sdk";
|
||||||
|
|
||||||
import logger from "./logger";
|
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 {
|
class OcrccBot {
|
||||||
constructor(config) {
|
constructor(botConfig) {
|
||||||
this.config = config
|
this.config = botConfig
|
||||||
this.client = matrix.createClient(this.config.matrixServerUrl);
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
this.inactivityTimers = {};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createLocalStorage() {
|
createLocalStorage() {
|
||||||
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
|
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
|
||||||
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);
|
||||||
@ -32,20 +28,21 @@ class OcrccBot {
|
|||||||
return new LocalStorage(localStoragePath);
|
return new LocalStorage(localStoragePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTextMessage(roomId, msgText, showToUser = null) {
|
sendTextMessage(roomId, msgText, showToUser = null) {
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: msgText,
|
body: msgText,
|
||||||
showToUser: showToUser
|
showToUser: showToUser
|
||||||
};
|
};
|
||||||
|
|
||||||
await this.sendMessage(roomId, content);
|
this.sendMessage(roomId, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async sendNotice(roomId, message) {
|
async sendNotice(roomId, message) {
|
||||||
|
logger.log("info", `SENDING *NOTICE*: ${message}`)
|
||||||
try {
|
try {
|
||||||
await this.client.sendNotice(roomId, message)
|
await this.client.sendNotice(roomId, message)
|
||||||
logger.log("info", `SENT *NOTICE*: ${message}`)
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@ -67,9 +64,9 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async sendMessage(roomId, content) {
|
async sendMessage(roomId, content) {
|
||||||
|
logger.log("info", `SENDING MESSAGE: ${content.body}`)
|
||||||
try {
|
try {
|
||||||
await this.client.sendMessage(roomId, content)
|
await this.client.sendMessage(roomId, content)
|
||||||
logger.log("info", `SENT MESSAGE: ${content.body}`)
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@ -84,65 +81,54 @@ class OcrccBot {
|
|||||||
});
|
});
|
||||||
await this.sendMessage(roomId, content);
|
await this.sendMessage(roomId, content);
|
||||||
default:
|
default:
|
||||||
logger.log("error", `ERROR SENDING MESSAGE ${content.body}: ${err}`);
|
logger.log("error", `ERROR SENDING MESSAGE: ${err}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inviteUserToRoom(roomId, member) {
|
||||||
|
try {
|
||||||
|
this.client.invite(roomId, member)
|
||||||
|
} catch(err) {
|
||||||
|
this.handleBotCrash(roomId, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
kickUserFromRoom(roomId, member) {
|
kickUserFromRoom(roomId, member) {
|
||||||
try {
|
try {
|
||||||
this.client.kick(roomId, member, this.config.kickReason)
|
this.client.kick(roomId, member, this.config.KICK_REASON)
|
||||||
} 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
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
this.client.invite(roomId, memberId)
|
|
||||||
logger.log("info", `CHAT INVITATION SENT TO ${memberId} FOR ROOM ${roomId}`)
|
|
||||||
return memberId
|
|
||||||
} catch(err) {
|
|
||||||
this.handleBotCrash(roomId, err);
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
|
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
||||||
|
let chatOffline = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
const data = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
|
||||||
let invitations = []
|
const members = data.chunk
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
|
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
|
||||||
|
|
||||||
for (const memberId of members) {
|
members.forEach(member => {
|
||||||
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId)
|
const memberId = member.user_id;
|
||||||
invitations.push(invited)
|
const user = this.client.getUser(memberId);
|
||||||
}
|
if (
|
||||||
|
user &&
|
||||||
|
user.presence === "online" &&
|
||||||
|
memberId !== this.config.BOT_USERID
|
||||||
|
) {
|
||||||
|
chatOffline = false;
|
||||||
|
this.inviteUserToRoom(roomId, memberId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (invitations.filter(i => i).length > 0) {
|
if (chatOffline) {
|
||||||
this.localStorage.setItem(`${roomId}-invitations`, invitations)
|
logger.log('info', "NO FACILITATORS ONLINE")
|
||||||
} else {
|
this.sendTextMessage(roomId, this.config.CHAT_OFFLINE_MESSAGE);
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE)
|
this.sendNotice(roomId, "Chat is offline")
|
||||||
|
|
||||||
// send notification to Support Chat Notifications room
|
|
||||||
const currentDate = new Date()
|
|
||||||
const closedTime = currentDate.toLocaleTimeString()
|
|
||||||
const roomRef = roomId.split(':')[0]
|
|
||||||
const notification = `No facilitators were online, chat closed at ${closedTime} (room ID: ${roomRef})`
|
|
||||||
logger.log('info', `NO FACILITATORS ONLINE, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`)
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
@ -153,19 +139,21 @@ class OcrccBot {
|
|||||||
|
|
||||||
|
|
||||||
async uninviteFacilitators(roomId) {
|
async uninviteFacilitators(roomId) {
|
||||||
|
this.localStorage.removeItem(`${roomId}-waiting`)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.localStorage.removeItem(`${roomId}-waiting`)
|
const groupUsers = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
|
||||||
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
|
const roomMembers = await this.client.getJoinedRoomMembers(roomId)
|
||||||
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
|
|
||||||
|
|
||||||
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
|
const roomMemberIds = Object.keys(roomMembers["joined"]);
|
||||||
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
|
const groupMemberIds = groupUsers["chunk"]
|
||||||
|
|
||||||
if (!roomMembersIds || !facilitatorsIds) return;
|
if (!roomMemberIds || !groupMemberIds) return;
|
||||||
|
|
||||||
|
const facilitatorsIds = groupMemberIds.map(f => f.user_id);
|
||||||
|
|
||||||
facilitatorsIds.forEach(f => {
|
facilitatorsIds.forEach(f => {
|
||||||
if (!roomMembersIds.includes(f)) {
|
if (!roomMemberIds.includes(f)) {
|
||||||
this.kickUserFromRoom(roomId, f);
|
this.kickUserFromRoom(roomId, f);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -177,39 +165,30 @@ class OcrccBot {
|
|||||||
|
|
||||||
handleBotCrash(roomId, error) {
|
handleBotCrash(roomId, error) {
|
||||||
if (roomId) {
|
if (roomId) {
|
||||||
this.sendTextMessage(roomId, this.config.botErrorMessage);
|
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
this.config.facilitatorRoomId,
|
this.config.FACILITATOR_ROOM_ID,
|
||||||
`${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`
|
`The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMessageEvent(event) {
|
handleMessageEvent(event) {
|
||||||
const content = event.getContent();
|
const content = event.getContent();
|
||||||
const sender = event.getSender()
|
|
||||||
const roomId = event.getRoomId();
|
|
||||||
|
|
||||||
// do nothing if there's no content
|
// do nothing if there's no content
|
||||||
if (!content) {
|
if (!content) {
|
||||||
return;
|
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
|
// bot commands
|
||||||
if (content.body.startsWith("!bot")) {
|
if (content.body.startsWith("!bot")) {
|
||||||
return this.handleBotCommand(event);
|
return this.handleBotCommand(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
// write to transcript
|
// write to transcript
|
||||||
if (this.config.captureTranscripts) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
return this.writeToTranscript(event);
|
return this.writeToTranscript(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -226,7 +205,7 @@ class OcrccBot {
|
|||||||
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
|
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
|
||||||
|
|
||||||
if (!filepath) {
|
if (!filepath) {
|
||||||
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
|
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `${sender} [${time}]: ${content.body}\n`;
|
const message = `${sender} [${time}]: ${content.body}\n`;
|
||||||
@ -238,24 +217,23 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleBotCommand(event) {
|
handleBotCommand(event) {
|
||||||
const botCommands = [
|
try {
|
||||||
{
|
const senderId = event.getSender();
|
||||||
keyword: 'transcript',
|
const roomId = event.getRoomId();
|
||||||
function: (senderId, roomId) => { this.sendTranscript(senderId, roomId) }
|
const content = event.getContent();
|
||||||
},
|
const command = content.body.substring("!bot".length).trim();
|
||||||
{
|
|
||||||
keyword: 'delete transcript',
|
switch (command) {
|
||||||
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId, true) } // delete transcript and send confirmation message
|
case "transcript":
|
||||||
},
|
this.sendTranscript(senderId, roomId);
|
||||||
{
|
break;
|
||||||
keyword: 'say',
|
case "transcript please":
|
||||||
function: (senderId, roomId, message) => {
|
this.sendTranscript(senderId, roomId);
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
break;
|
||||||
}
|
case "delete transcript":
|
||||||
},
|
this.deleteTranscript(senderId, roomId);
|
||||||
{
|
break;
|
||||||
keyword: 'hi',
|
case "hi":
|
||||||
function: (senderId, roomId) => {
|
|
||||||
const responses = [
|
const responses = [
|
||||||
"Hi!",
|
"Hi!",
|
||||||
"Hello",
|
"Hello",
|
||||||
@ -263,41 +241,24 @@ class OcrccBot {
|
|||||||
"Hi there",
|
"Hi there",
|
||||||
"Bleep bloop"
|
"Bleep bloop"
|
||||||
];
|
];
|
||||||
const message = responses[Math.floor(Math.random() * responses.length)];
|
const message =
|
||||||
|
responses[Math.floor(Math.random() * responses.length)];
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
}
|
break;
|
||||||
},
|
default:
|
||||||
{
|
this.sendTextMessage(
|
||||||
keyword: 'bug',
|
roomId,
|
||||||
function: (senderId, roomId) => {
|
`Sorry, I don't know that command. I'm not a very smart bot.`,
|
||||||
const message = `Please report the issue at ${this.config.bugReportUrl}`
|
senderId
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
);
|
||||||
}
|
break;
|
||||||
}
|
}
|
||||||
]
|
|
||||||
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) {
|
} catch (err) {
|
||||||
logger.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
logger.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveEmptyRooms() {
|
async leaveEmptyRooms(senderId) {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms()
|
const roomData = await this.client.getJoinedRooms()
|
||||||
const joinedRoomsIds = roomData["joined_rooms"]
|
const joinedRoomsIds = roomData["joined_rooms"]
|
||||||
@ -305,15 +266,15 @@ class OcrccBot {
|
|||||||
const room = this.client.getRoom(roomId)
|
const room = this.client.getRoom(roomId)
|
||||||
if (room && room.getJoinedMemberCount() === 1) {
|
if (room && room.getJoinedMemberCount() === 1) {
|
||||||
try {
|
try {
|
||||||
|
logger.log('info', "LEAVING EMPTY ROOM => " + roomId)
|
||||||
await this.client.leave(roomId)
|
await this.client.leave(roomId)
|
||||||
logger.log('info', `LEAVING EMPTY ROOM => ${roomId}`)
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`)
|
logger.log('error', "ERROR LEAVING EMPTY ROOM => " + err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
|
logger.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -324,59 +285,27 @@ class OcrccBot {
|
|||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
"Cannot send transcript, there is no transcript for this chat.",
|
"There is no transcript for this chat.",
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.client.isRoomEncrypted(roomId)) {
|
const filename = path.basename(transcriptFile) || "Transcript";
|
||||||
let encryptInfo;
|
const stream = fs.createReadStream(transcriptFile);
|
||||||
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 = {
|
const contentUrl = await this.client.uploadContent({
|
||||||
msgtype: "m.file",
|
stream: stream,
|
||||||
body: filename,
|
name: filename
|
||||||
info: {
|
})
|
||||||
mimetype: 'text/plain'
|
|
||||||
},
|
|
||||||
file: encryptInfo,
|
|
||||||
url: url.content_uri,
|
|
||||||
showToUser: senderId,
|
|
||||||
mimetype: 'text/plain'
|
|
||||||
};
|
|
||||||
|
|
||||||
this.sendMessage(roomId, content);
|
const content = {
|
||||||
|
msgtype: "m.file",
|
||||||
} else {
|
body: filename,
|
||||||
const filename = path.basename(transcriptFile) || "Transcript";
|
url: JSON.parse(contentUrl).content_uri,
|
||||||
const file = fs.readFileSync(transcriptFile);
|
showToUser: senderId
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
this.sendMessage(roomId, content);
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", `ERROR UPLOADING CONTENT: ${err}`);
|
logger.log("error", `ERROR UPLOADING CONTENT: ${err}`);
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
@ -387,13 +316,13 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteTranscript(senderId, roomId, sendConfirmation=false) {
|
deleteTranscript(senderId, roomId) {
|
||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
|
||||||
|
|
||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
return this.sendTextMessage(
|
return this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
"Cannot delete transcript, there is no transcript for this chat.",
|
"There is no transcript for this chat.",
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -409,17 +338,13 @@ class OcrccBot {
|
|||||||
senderId
|
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`)
|
this.localStorage.removeItem(`${roomId}-transcript`)
|
||||||
|
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
|
||||||
|
this.sendTextMessage(
|
||||||
|
roomId,
|
||||||
|
`The transcript file has been deleted.`,
|
||||||
|
senderId
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -436,9 +361,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.botUserId,
|
user: this.config.BOT_USERID,
|
||||||
identifier: { type: "m.id.user", user: this.config.botUserId },
|
identifier: { type: "m.id.user", user: this.config.BOT_USERID },
|
||||||
password: this.config.botPassword
|
password: this.config.BOT_PASSWORD
|
||||||
};
|
};
|
||||||
|
|
||||||
await this.client.deleteMultipleDevices(oldDevices, auth)
|
await this.client.deleteMultipleDevices(oldDevices, auth)
|
||||||
@ -457,202 +382,97 @@ 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.botUserId &&
|
member.userId === this.config.BOT_USERID &&
|
||||||
!this.joinedRooms.includes(member.roomId)
|
!this.joinedRooms.includes(member.roomId)
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms()
|
const room = await this.client.joinRoom(member.roomId)
|
||||||
const joinedRooms = roomData["joined_rooms"]
|
logger.log("info", "AUTO JOINED ROOM => " + room.roomId)
|
||||||
if (!joinedRooms.includes(member.roomId)) {
|
this.sendTextMessage(
|
||||||
const room = await this.client.joinRoom(member.roomId)
|
this.config.FACILITATOR_ROOM_ID,
|
||||||
logger.log("info", "AUTO JOINED ROOM => " + room.roomId)
|
`A support seeker requested a chat (Room ID: ${room.roomId})`
|
||||||
const inviteDate = event.getDate()
|
);
|
||||||
const chatDate = inviteDate.toLocaleDateString()
|
this.inviteFacilitators(room.roomId)
|
||||||
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) {
|
} catch(err) {
|
||||||
logger.log("error", "ERROR JOINING ROOM => " + err)
|
logger.log("error", "ERROR JOINING ROOM => " + err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// When a facilitator joins a support session, make them a moderator
|
||||||
|
// revoke the other invitations
|
||||||
if (
|
if (
|
||||||
member.membership === "join" &&
|
member.membership === "join" &&
|
||||||
member.userId !== this.config.botUserId &&
|
member.userId !== this.config.BOT_USERID &&
|
||||||
this.localStorage.getItem(`${member.roomId}-waiting`)
|
this.localStorage.getItem(`${member.roomId}-waiting`)
|
||||||
) {
|
) {
|
||||||
try {
|
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId)
|
||||||
// make sure it's a facilitator joining
|
const event = {
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
|
getType: () => {
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
return "m.room.power_levels";
|
||||||
const isFacilitator = members.includes(member.userId)
|
},
|
||||||
|
getContent: () => {
|
||||||
if (isFacilitator) {
|
return {
|
||||||
// made facilitator a moderator in the room
|
users: {
|
||||||
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId)
|
[this.config.BOT_USERID]: 100,
|
||||||
const event = {
|
[member.userId]: 50
|
||||||
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}`);
|
this.client.setPowerLevel(member.roomId, member.userId, 50, event);
|
||||||
|
this.sendTextMessage(
|
||||||
|
member.roomId,
|
||||||
|
`${member.name} has joined the chat.`
|
||||||
|
);
|
||||||
|
this.sendTextMessage(
|
||||||
|
this.config.FACILITATOR_ROOM_ID,
|
||||||
|
`${member.name} joined the chat (Room ID: ${member.roomId})`
|
||||||
|
);
|
||||||
|
this.uninviteFacilitators(member.roomId);
|
||||||
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
|
const currentDate = new Date();
|
||||||
|
const dateOpts = {
|
||||||
|
year: "numeric",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric"
|
||||||
|
};
|
||||||
|
const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
|
||||||
|
const chatTime = currentDate.toLocaleTimeString("en-GB", {
|
||||||
|
timeZone: "America/New_York"
|
||||||
|
});
|
||||||
|
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
|
||||||
|
const filepath = path.resolve(path.join("transcripts", filename));
|
||||||
|
this.localStorage.setItem(`${member.roomId}-transcript`, filepath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
member.membership === "leave" &&
|
member.membership === "leave" &&
|
||||||
member.userId !== this.config.botUserId
|
member.userId !== this.config.BOT_USERID
|
||||||
) {
|
) {
|
||||||
|
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
|
||||||
// notify room if the facilitator has left
|
if (member.userId === facilitatorId) {
|
||||||
try {
|
this.sendTextMessage(
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
|
member.roomId,
|
||||||
if (member.userId === facilitatorId) {
|
`${member.name} has left the chat.`
|
||||||
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}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const room = this.client.getRoom(member.roomId)
|
|
||||||
if (!room) return;
|
|
||||||
const roomMembers = await room.getJoinedMembers() // array
|
|
||||||
|
|
||||||
// leave if there is nobody in the room
|
// leave if there is nobody in the room
|
||||||
try {
|
const room = this.client.getRoom(member.roomId)
|
||||||
const memberCount = roomMembers.length
|
if (!room) return
|
||||||
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId))
|
|
||||||
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}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// send signal to close the chat if there are no facilitators in the room
|
const memberCount = room.getJoinedMemberCount()
|
||||||
try {
|
|
||||||
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId) // object
|
|
||||||
const facilitators = facilitatorRoomMembers['joined']
|
|
||||||
let facilitatorInRoom = false;
|
|
||||||
|
|
||||||
roomMembers.forEach(member => {
|
if (memberCount === 1) { // just the bot left
|
||||||
if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
|
logger.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
|
||||||
facilitatorInRoom = true
|
this.deleteTranscript(member.userId, member.roomId);
|
||||||
}
|
this.localStorage.removeItem(`${member.roomId}-facilitator`)
|
||||||
})
|
this.localStorage.removeItem(`${member.roomId}-transcript`)
|
||||||
|
this.client.leave(member.roomId)
|
||||||
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) {
|
|
||||||
await this.sendTextMessage(
|
|
||||||
roomId,
|
|
||||||
this.config.chatNotAvailableMessage
|
|
||||||
);
|
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
|
||||||
|
|
||||||
// send notification to Support Chat Notifications room
|
|
||||||
const currentDate = new Date()
|
|
||||||
const closedTime = currentDate.toLocaleTimeString()
|
|
||||||
const roomRef = roomId.split(':')[0]
|
|
||||||
const notification = `No facilitators joined the chat within the maximum wait time, chat closed at ${closedTime} (room ID: ${roomRef})`;
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
logger.log("info", `NO FACILITATORS JOINED THE CHAT WITHIN THE MAXIMUM WAIT TIME, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
|
|
||||||
}
|
|
||||||
}, this.config.maxWaitTime * 1000) // convert seconds to milliseconds
|
|
||||||
}
|
|
||||||
|
|
||||||
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 * 1000) // convert seconds to milliseconds
|
|
||||||
|
|
||||||
this.inactivityTimers[roomId] = newTimeout;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async setMessageListeners() {
|
async setMessageListeners() {
|
||||||
@ -673,53 +493,46 @@ class OcrccBot {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendBotSignal (roomId, signal, args) {
|
async leaveOldRooms() {
|
||||||
let content = {
|
const roomData = await this.client.getJoinedRooms()
|
||||||
signal: signal,
|
|
||||||
args: args,
|
roomData["joined_rooms"].forEach(async roomId => {
|
||||||
}
|
try {
|
||||||
try {
|
await this.client.leave(roomId)
|
||||||
await this.client.sendStateEvent(roomId, 'm.bot.signal', content)
|
} catch(err) {
|
||||||
} catch(err) {
|
logger.log('error', "ERROR LEAVING ROOM => " + err)
|
||||||
logger.log('error', "ERROR SENDING BOT SIGNAL => " + err)
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
try {
|
const localStorage = this.createLocalStorage();
|
||||||
const localStorage = this.createLocalStorage();
|
this.localStorage = localStorage
|
||||||
this.localStorage = localStorage
|
|
||||||
|
|
||||||
|
try {
|
||||||
const auth = {
|
const auth = {
|
||||||
user: this.config.botUsername,
|
user: this.config.BOT_USERNAME,
|
||||||
password: this.config.botPassword,
|
password: this.config.BOT_PASSWORD,
|
||||||
initial_device_display_name: this.config.botDisplayName
|
initial_device_display_name: this.config.BOT_DISPLAY_NAME
|
||||||
}
|
}
|
||||||
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.matrixServerUrl,
|
baseUrl: this.config.MATRIX_SERVER_URL,
|
||||||
accessToken: account.access_token,
|
accessToken: account.access_token,
|
||||||
userId: this.config.botUserId,
|
userId: this.config.BOT_USERID,
|
||||||
deviceId: account.device_id,
|
deviceId: account.device_id,
|
||||||
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
||||||
};
|
};
|
||||||
|
|
||||||
this.client = matrix.createClient(opts);
|
this.client = matrix.createClient(opts);
|
||||||
|
await this.deleteOldDevices()
|
||||||
|
await this.trackJoinedRooms()
|
||||||
await this.client.initCrypto()
|
await this.client.initCrypto()
|
||||||
|
await this.setMembershipListeners();
|
||||||
|
await this.setMessageListeners();
|
||||||
this.client.startClient({ initialSyncLimit: 0 })
|
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) {
|
} catch(err) {
|
||||||
this.handleBotCrash(undefined, err);
|
this.handleBotCrash(undefined, err);
|
||||||
logger.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
|
logger.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
|
||||||
|
@ -32,8 +32,7 @@ import {
|
|||||||
mockKick,
|
mockKick,
|
||||||
mockGetJoinedRoomMembers,
|
mockGetJoinedRoomMembers,
|
||||||
mockGetUser,
|
mockGetUser,
|
||||||
mockGetGroupUsers,
|
mockGetGroupUsers
|
||||||
mockSendStateEvent,
|
|
||||||
} from "matrix-js-sdk";
|
} from "matrix-js-sdk";
|
||||||
|
|
||||||
import OcrccBot from './bot'
|
import OcrccBot from './bot'
|
||||||
@ -49,6 +48,7 @@ const {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
|
FACILITATOR_GROUP_ID,
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
CHAT_OFFLINE_MESSAGE,
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS
|
||||||
@ -64,6 +64,7 @@ const botConfig = {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
|
FACILITATOR_GROUP_ID,
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
CHAT_OFFLINE_MESSAGE,
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS
|
||||||
@ -101,7 +102,6 @@ describe('OcrccBot', () => {
|
|||||||
mockSendTextMessage.mockClear()
|
mockSendTextMessage.mockClear()
|
||||||
mockAppendFileSync.mockClear()
|
mockAppendFileSync.mockClear()
|
||||||
mockGetGroupUsers.mockClear()
|
mockGetGroupUsers.mockClear()
|
||||||
mockSendStateEvent.mockClear()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@ -327,17 +327,4 @@ describe('OcrccBot', () => {
|
|||||||
expect(mockStartClient).toHaveBeenCalled()
|
expect(mockStartClient).toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test('#sendBotSignal should send custom state event', () => {
|
|
||||||
const bot = new OcrccBot(botConfig)
|
|
||||||
bot.start()
|
|
||||||
const test_room_id = 'test_room_id'
|
|
||||||
const signal = 'END_CHAT'
|
|
||||||
|
|
||||||
bot.sendBotSignal(test_room_id, signal)
|
|
||||||
|
|
||||||
waitForExpect(() => {
|
|
||||||
expect(mockSendStateEvent).toHaveBeenCalledWith(test_room_id, 'm.bot.signal', { signal })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
@ -1,156 +0,0 @@
|
|||||||
// this is from https://github.com/matrix-org/browser-encrypt-attachment
|
|
||||||
// which is the library used by matrix-reack-sdk to encrypt and decrypt attachments
|
|
||||||
// just dropped in node-webcrypto-ossl to replace window.crypto
|
|
||||||
// and Buffer for base64 encoding/decoding instead of window.btoa/window.atob
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encrypt an attachment.
|
|
||||||
* @param {ArrayBuffer} plaintextBuffer The attachment data buffer.
|
|
||||||
* @return {Promise} A promise that resolves with an object when the attachment is encrypted.
|
|
||||||
* The object has a "data" key with an ArrayBuffer of encrypted data and an "info" key
|
|
||||||
* with an object containing the info needed to decrypt the data.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const { Crypto } = require("node-webcrypto-ossl");
|
|
||||||
const crypto = new Crypto();
|
|
||||||
|
|
||||||
function encryptAttachment(plaintextBuffer) {
|
|
||||||
var cryptoKey; // The AES key object.
|
|
||||||
var exportedKey; // The AES key exported as JWK.
|
|
||||||
var ciphertextBuffer; // ArrayBuffer of encrypted data.
|
|
||||||
var sha256Buffer; // ArrayBuffer of digest.
|
|
||||||
var ivArray; // Uint8Array of AES IV
|
|
||||||
// Generate an IV where the first 8 bytes are random and the high 8 bytes
|
|
||||||
// are zero. We set the counter low bits to 0 since it makes it unlikely
|
|
||||||
// that the 64 bit counter will overflow.
|
|
||||||
ivArray = new Uint8Array(16);
|
|
||||||
crypto.getRandomValues(ivArray.subarray(0,8));
|
|
||||||
// Load the encryption key.
|
|
||||||
return crypto.subtle.generateKey(
|
|
||||||
{"name": "AES-CTR", length: 256}, true, ["encrypt", "decrypt"]
|
|
||||||
).then(function(generateKeyResult) {
|
|
||||||
cryptoKey = generateKeyResult;
|
|
||||||
// Export the Key as JWK.
|
|
||||||
return crypto.subtle.exportKey("jwk", cryptoKey);
|
|
||||||
}).then(function(exportKeyResult) {
|
|
||||||
exportedKey = exportKeyResult;
|
|
||||||
// Encrypt the input ArrayBuffer.
|
|
||||||
// Use half of the iv as the counter by setting the "length" to 64.
|
|
||||||
return crypto.subtle.encrypt(
|
|
||||||
{name: "AES-CTR", counter: ivArray, length: 64}, cryptoKey, plaintextBuffer
|
|
||||||
);
|
|
||||||
}).then(function(encryptResult) {
|
|
||||||
ciphertextBuffer = encryptResult;
|
|
||||||
// SHA-256 the encrypted data.
|
|
||||||
return crypto.subtle.digest("SHA-256", ciphertextBuffer);
|
|
||||||
}).then(function (digestResult) {
|
|
||||||
sha256Buffer = digestResult;
|
|
||||||
|
|
||||||
return {
|
|
||||||
data: ciphertextBuffer,
|
|
||||||
info: {
|
|
||||||
v: "v2",
|
|
||||||
key: exportedKey,
|
|
||||||
iv: encodeBase64(ivArray),
|
|
||||||
hashes: {
|
|
||||||
sha256: encodeBase64(new Uint8Array(sha256Buffer)),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decrypt an attachment.
|
|
||||||
* @param {ArrayBuffer} ciphertextBuffer The encrypted attachment data buffer.
|
|
||||||
* @param {Object} info The information needed to decrypt the attachment.
|
|
||||||
* @param {Object} info.key AES-CTR JWK key object.
|
|
||||||
* @param {string} info.iv Base64 encoded 16 byte AES-CTR IV.
|
|
||||||
* @param {string} info.hashes.sha256 Base64 encoded SHA-256 hash of the ciphertext.
|
|
||||||
* @return {Promise} A promise that resolves with an ArrayBuffer when the attachment is decrypted.
|
|
||||||
*/
|
|
||||||
function decryptAttachment(ciphertextBuffer, info) {
|
|
||||||
|
|
||||||
if (info === undefined || info.key === undefined || info.iv === undefined
|
|
||||||
|| info.hashes === undefined || info.hashes.sha256 === undefined) {
|
|
||||||
throw new Error("Invalid info. Missing info.key, info.iv or info.hashes.sha256 key");
|
|
||||||
}
|
|
||||||
|
|
||||||
var cryptoKey; // The AES key object.
|
|
||||||
var ivArray = decodeBase64(info.iv);
|
|
||||||
var expectedSha256base64 = info.hashes.sha256;
|
|
||||||
// Load the AES from the "key" key of the info object.
|
|
||||||
return crypto.subtle.importKey(
|
|
||||||
"jwk", info.key, {"name": "AES-CTR"}, false, ["encrypt", "decrypt"]
|
|
||||||
).then(function (importKeyResult) {
|
|
||||||
cryptoKey = importKeyResult;
|
|
||||||
// Check the sha256 hash
|
|
||||||
return crypto.subtle.digest("SHA-256", ciphertextBuffer);
|
|
||||||
}).then(function (digestResult) {
|
|
||||||
if (encodeBase64(new Uint8Array(digestResult)) != expectedSha256base64) {
|
|
||||||
throw new Error("Mismatched SHA-256 digest");
|
|
||||||
}
|
|
||||||
var counterLength;
|
|
||||||
if (info.v == "v1" || info.v == "v2") {
|
|
||||||
// Version 1 and 2 use a 64 bit counter.
|
|
||||||
counterLength = 64;
|
|
||||||
} else {
|
|
||||||
// Version 0 uses a 128 bit counter.
|
|
||||||
counterLength = 128;
|
|
||||||
}
|
|
||||||
return crypto.subtle.decrypt(
|
|
||||||
{name: "AES-CTR", counter: ivArray, length: counterLength}, cryptoKey, ciphertextBuffer
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encode a typed array of uint8 as base64.
|
|
||||||
* @param {Uint8Array} uint8Array The data to encode.
|
|
||||||
* @return {string} The base64 without padding.
|
|
||||||
*/
|
|
||||||
function encodeBase64(uint8Array) {
|
|
||||||
// Misinterpt the Uint8Array as Latin-1.
|
|
||||||
// window.btoa expects a unicode string with codepoints in the range 0-255.
|
|
||||||
var latin1String = String.fromCharCode.apply(null, uint8Array);
|
|
||||||
// Use the builtin base64 encoder.
|
|
||||||
// var paddedBase64 = window.btoa(latin1String);
|
|
||||||
var paddedBase64 = Buffer.from(latin1String, 'binary').toString('base64')
|
|
||||||
// Calculate the unpadded length.
|
|
||||||
var inputLength = uint8Array.length;
|
|
||||||
var outputLength = 4 * Math.floor((inputLength + 2) / 3) + (inputLength + 2) % 3 - 2;
|
|
||||||
// Return the unpadded base64.
|
|
||||||
return paddedBase64.slice(0, outputLength);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decode a base64 string to a typed array of uint8.
|
|
||||||
* This will decode unpadded base64, but will also accept base64 with padding.
|
|
||||||
* @param {string} base64 The unpadded base64 to decode.
|
|
||||||
* @return {Uint8Array} The decoded data.
|
|
||||||
*/
|
|
||||||
function decodeBase64(base64) {
|
|
||||||
// Pad the base64 up to the next multiple of 4.
|
|
||||||
var paddedBase64 = base64 + "===".slice(0, (4 - base64.length % 4) % 4);
|
|
||||||
// Decode the base64 as a misinterpreted Latin-1 string.
|
|
||||||
// window.atob returns a unicode string with codepoints in the range 0-255.
|
|
||||||
// var latin1String = window.atob(paddedBase64);
|
|
||||||
var latin1String = Buffer.from(paddedBase64, 'base64').toString('binary')
|
|
||||||
// Encode the string as a Uint8Array as Latin-1.
|
|
||||||
var uint8Array = new Uint8Array(latin1String.length);
|
|
||||||
for (var i = 0; i < latin1String.length; i++) {
|
|
||||||
uint8Array[i] = latin1String.charCodeAt(i);
|
|
||||||
}
|
|
||||||
return uint8Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
exports.encryptAttachment = encryptAttachment;
|
|
||||||
exports.decryptAttachment = decryptAttachment;
|
|
||||||
}
|
|
||||||
catch (e) {
|
|
||||||
// Ignore unknown variable "exports" errors when this is loaded directly into a browser
|
|
||||||
// This means that we can test it without having to use browserify.
|
|
||||||
// The intention is that the library is used using browserify.
|
|
||||||
}
|
|
44
src/index.js
44
src/index.js
@ -1,9 +1,39 @@
|
|||||||
import config from '../config.json';
|
require('dotenv').config()
|
||||||
import OcrccBot from './bot';
|
|
||||||
|
|
||||||
const bot = new OcrccBot(config);
|
const ENCRYPTION_CONFIG = { algorithm: "m.megolm.v1.aes-sha2" };
|
||||||
try {
|
const KICK_REASON = "A facilitator has already joined this chat.";
|
||||||
bot.start();
|
const BOT_ERROR_MESSAGE =
|
||||||
} catch(err) {
|
"Something went wrong on our end, please restart the chat and try again.";
|
||||||
console.log("Unable to start bot", err)
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
import OcrccBot from './bot'
|
||||||
|
|
||||||
|
const bot = new OcrccBot(botConfig);
|
||||||
|
bot.start();
|
||||||
|
50
src/setup.js
50
src/setup.js
@ -1,50 +0,0 @@
|
|||||||
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 === 'platform') {
|
|
||||||
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();
|
|
100
yarn.lock
100
yarn.lock
@ -1257,23 +1257,6 @@
|
|||||||
"@types/yargs" "^15.0.0"
|
"@types/yargs" "^15.0.0"
|
||||||
chalk "^3.0.0"
|
chalk "^3.0.0"
|
||||||
|
|
||||||
"@peculiar/asn1-schema@^2.0.1":
|
|
||||||
version "2.0.8"
|
|
||||||
resolved "https://registry.yarnpkg.com/@peculiar/asn1-schema/-/asn1-schema-2.0.8.tgz#bafb74388590f6ec3d53d1b2a4fdbe66d44224a4"
|
|
||||||
integrity sha512-D8ZqT61DdzuXfrILNvtdf7MUcTY2o9WHwmF0WgTKPEGNY5SDxNAjBY3enuwV9SXcSuCAwWac9c9v0vsswB1NIw==
|
|
||||||
dependencies:
|
|
||||||
"@types/asn1js" "^0.0.1"
|
|
||||||
asn1js "^2.0.26"
|
|
||||||
pvtsutils "^1.0.10"
|
|
||||||
tslib "^1.11.1"
|
|
||||||
|
|
||||||
"@peculiar/json-schema@^1.1.10":
|
|
||||||
version "1.1.12"
|
|
||||||
resolved "https://registry.yarnpkg.com/@peculiar/json-schema/-/json-schema-1.1.12.tgz#fe61e85259e3b5ba5ad566cb62ca75b3d3cd5339"
|
|
||||||
integrity sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==
|
|
||||||
dependencies:
|
|
||||||
tslib "^2.0.0"
|
|
||||||
|
|
||||||
"@sinonjs/commons@^1.7.0":
|
"@sinonjs/commons@^1.7.0":
|
||||||
version "1.7.1"
|
version "1.7.1"
|
||||||
resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.7.1.tgz#da5fd19a5f71177a53778073978873964f49acf1"
|
resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.7.1.tgz#da5fd19a5f71177a53778073978873964f49acf1"
|
||||||
@ -1281,13 +1264,6 @@
|
|||||||
dependencies:
|
dependencies:
|
||||||
type-detect "4.0.8"
|
type-detect "4.0.8"
|
||||||
|
|
||||||
"@types/asn1js@^0.0.1":
|
|
||||||
version "0.0.1"
|
|
||||||
resolved "https://registry.yarnpkg.com/@types/asn1js/-/asn1js-0.0.1.tgz#ef8b9f9708cb1632a1c3a9cd27717caabe793bc2"
|
|
||||||
integrity sha1-74uflwjLFjKhw6nNJ3F8qr55O8I=
|
|
||||||
dependencies:
|
|
||||||
"@types/pvutils" "*"
|
|
||||||
|
|
||||||
"@types/babel__core@^7.1.0":
|
"@types/babel__core@^7.1.0":
|
||||||
version "7.1.6"
|
version "7.1.6"
|
||||||
resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.6.tgz#16ff42a5ae203c9af1c6e190ed1f30f83207b610"
|
resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.6.tgz#16ff42a5ae203c9af1c6e190ed1f30f83207b610"
|
||||||
@ -1346,11 +1322,6 @@
|
|||||||
"@types/istanbul-lib-coverage" "*"
|
"@types/istanbul-lib-coverage" "*"
|
||||||
"@types/istanbul-lib-report" "*"
|
"@types/istanbul-lib-report" "*"
|
||||||
|
|
||||||
"@types/pvutils@*":
|
|
||||||
version "0.0.2"
|
|
||||||
resolved "https://registry.yarnpkg.com/@types/pvutils/-/pvutils-0.0.2.tgz#e21684962cfa58ac920fd576d90556032dc86009"
|
|
||||||
integrity sha512-CgQAm7pjyeF3Gnv78ty4RBVIfluB+Td+2DR8iPaU0prF18pkzptHHP+DoKPfpsJYknKsVZyVsJEu5AuGgAqQ5w==
|
|
||||||
|
|
||||||
"@types/stack-utils@^1.0.1":
|
"@types/stack-utils@^1.0.1":
|
||||||
version "1.0.1"
|
version "1.0.1"
|
||||||
resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-1.0.1.tgz#0a851d3bd96498fa25c33ab7278ed3bd65f06c3e"
|
resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-1.0.1.tgz#0a851d3bd96498fa25c33ab7278ed3bd65f06c3e"
|
||||||
@ -1515,13 +1486,6 @@ asn1@~0.2.3:
|
|||||||
dependencies:
|
dependencies:
|
||||||
safer-buffer "~2.1.0"
|
safer-buffer "~2.1.0"
|
||||||
|
|
||||||
asn1js@^2.0.26:
|
|
||||||
version "2.0.26"
|
|
||||||
resolved "https://registry.yarnpkg.com/asn1js/-/asn1js-2.0.26.tgz#0a6d435000f556a96c6012969d9704d981b71251"
|
|
||||||
integrity sha512-yG89F0j9B4B0MKIcFyWWxnpZPLaNTjCj4tkE3fjbAoo0qmpGw0PYYqSbX/4ebnd9Icn8ZgK4K1fvDyEtW1JYtQ==
|
|
||||||
dependencies:
|
|
||||||
pvutils latest
|
|
||||||
|
|
||||||
assert-plus@1.0.0, assert-plus@^1.0.0:
|
assert-plus@1.0.0, assert-plus@^1.0.0:
|
||||||
version "1.0.0"
|
version "1.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525"
|
resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525"
|
||||||
@ -3798,10 +3762,10 @@ map-visit@^1.0.0:
|
|||||||
dependencies:
|
dependencies:
|
||||||
object-visit "^1.0.0"
|
object-visit "^1.0.0"
|
||||||
|
|
||||||
matrix-js-sdk@^6.2.1:
|
matrix-js-sdk@^5.0.1:
|
||||||
version "6.2.1"
|
version "5.1.0"
|
||||||
resolved "https://registry.yarnpkg.com/matrix-js-sdk/-/matrix-js-sdk-6.2.1.tgz#d5f76491a650c0a36fcdd078cff59f2da96edd7b"
|
resolved "https://registry.yarnpkg.com/matrix-js-sdk/-/matrix-js-sdk-5.1.0.tgz#9b3b02af227ecc2d0cc35fb7312c92b8a6754293"
|
||||||
integrity sha512-X12Y2SMg8MOJwE5P3VMsMV/mnQHOmyJkF+FZRida124w4B4tBJouaNxteYyYaH34w+wyaKGxuqEBXecfSpfvbw==
|
integrity sha512-IGRq5iACiKp3iIxAghwtdBPrbdgORowc0i8YuIMkZZMpRJDXnNaudt2BFwyQdukV7gvzz7F0sfxBUerySfOnKA==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.8.3"
|
"@babel/runtime" "^7.8.3"
|
||||||
another-json "^0.2.0"
|
another-json "^0.2.0"
|
||||||
@ -3899,11 +3863,6 @@ mkdirp@^0.5.1:
|
|||||||
dependencies:
|
dependencies:
|
||||||
minimist "0.0.8"
|
minimist "0.0.8"
|
||||||
|
|
||||||
mkdirp@^1.0.4:
|
|
||||||
version "1.0.4"
|
|
||||||
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e"
|
|
||||||
integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==
|
|
||||||
|
|
||||||
ms@2.0.0:
|
ms@2.0.0:
|
||||||
version "2.0.0"
|
version "2.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
|
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
|
||||||
@ -3914,7 +3873,7 @@ ms@^2.1.1:
|
|||||||
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
|
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
|
||||||
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
|
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
|
||||||
|
|
||||||
nan@^2.12.1, nan@^2.14.1:
|
nan@^2.12.1:
|
||||||
version "2.14.1"
|
version "2.14.1"
|
||||||
resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.1.tgz#d7be34dfa3105b91494c3147089315eff8874b01"
|
resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.1.tgz#d7be34dfa3105b91494c3147089315eff8874b01"
|
||||||
integrity sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw==
|
integrity sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw==
|
||||||
@ -3954,11 +3913,6 @@ 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"
|
||||||
@ -3999,17 +3953,6 @@ node-releases@^1.1.53:
|
|||||||
resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-1.1.53.tgz#2d821bfa499ed7c5dffc5e2f28c88e78a08ee3f4"
|
resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-1.1.53.tgz#2d821bfa499ed7c5dffc5e2f28c88e78a08ee3f4"
|
||||||
integrity sha512-wp8zyQVwef2hpZ/dJH7SfSrIPD6YoJz6BDQDpGEkcA0s3LpAQoxBIYmfIq6QAhC1DhwsyCgTaTTcONwX8qzCuQ==
|
integrity sha512-wp8zyQVwef2hpZ/dJH7SfSrIPD6YoJz6BDQDpGEkcA0s3LpAQoxBIYmfIq6QAhC1DhwsyCgTaTTcONwX8qzCuQ==
|
||||||
|
|
||||||
node-webcrypto-ossl@^2.1.0:
|
|
||||||
version "2.1.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/node-webcrypto-ossl/-/node-webcrypto-ossl-2.1.0.tgz#cee0e22fa9d9325a19f260539d0854ba143595db"
|
|
||||||
integrity sha512-diC2LLQKKo41XxrgdT2MmH4mxWNoeCwjS0+uSLfui3rCtxai8cdLLs0TKT0z9Mq8LZ4eMAkuU4FFmEOHk6CbsQ==
|
|
||||||
dependencies:
|
|
||||||
mkdirp "^1.0.4"
|
|
||||||
nan "^2.14.1"
|
|
||||||
pvtsutils "^1.0.10"
|
|
||||||
tslib "^1.11.2"
|
|
||||||
webcrypto-core "^1.1.0"
|
|
||||||
|
|
||||||
nodemon@^2.0.2:
|
nodemon@^2.0.2:
|
||||||
version "2.0.2"
|
version "2.0.2"
|
||||||
resolved "https://registry.yarnpkg.com/nodemon/-/nodemon-2.0.2.tgz#9c7efeaaf9b8259295a97e5d4585ba8f0cbe50b0"
|
resolved "https://registry.yarnpkg.com/nodemon/-/nodemon-2.0.2.tgz#9c7efeaaf9b8259295a97e5d4585ba8f0cbe50b0"
|
||||||
@ -4411,18 +4354,6 @@ punycode@^2.1.0, punycode@^2.1.1:
|
|||||||
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
|
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
|
||||||
integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==
|
integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==
|
||||||
|
|
||||||
pvtsutils@^1.0.10:
|
|
||||||
version "1.0.10"
|
|
||||||
resolved "https://registry.yarnpkg.com/pvtsutils/-/pvtsutils-1.0.10.tgz#157d0fcb853f570d32e0f8788179f3057eacdf38"
|
|
||||||
integrity sha512-8ZKQcxnZKTn+fpDh7wL4yKax5fdl3UJzT8Jv49djZpB/dzPxacyN1Sez90b6YLdOmvIr9vaySJ5gw4aUA1EdSw==
|
|
||||||
dependencies:
|
|
||||||
tslib "^1.10.0"
|
|
||||||
|
|
||||||
pvutils@latest:
|
|
||||||
version "1.0.17"
|
|
||||||
resolved "https://registry.yarnpkg.com/pvutils/-/pvutils-1.0.17.tgz#ade3c74dfe7178944fe44806626bd2e249d996bf"
|
|
||||||
integrity sha512-wLHYUQxWaXVQvKnwIDWFVKDJku9XDCvyhhxoq8dc5MFdIlRenyPI9eSfEtcvgHgD7FlvCyGAlWgOzRnZD99GZQ==
|
|
||||||
|
|
||||||
qs@^6.5.2:
|
qs@^6.5.2:
|
||||||
version "6.9.1"
|
version "6.9.1"
|
||||||
resolved "https://registry.yarnpkg.com/qs/-/qs-6.9.1.tgz#20082c65cb78223635ab1a9eaca8875a29bf8ec9"
|
resolved "https://registry.yarnpkg.com/qs/-/qs-6.9.1.tgz#20082c65cb78223635ab1a9eaca8875a29bf8ec9"
|
||||||
@ -5230,16 +5161,6 @@ triple-beam@^1.2.0, triple-beam@^1.3.0:
|
|||||||
resolved "https://registry.yarnpkg.com/triple-beam/-/triple-beam-1.3.0.tgz#a595214c7298db8339eeeee083e4d10bd8cb8dd9"
|
resolved "https://registry.yarnpkg.com/triple-beam/-/triple-beam-1.3.0.tgz#a595214c7298db8339eeeee083e4d10bd8cb8dd9"
|
||||||
integrity sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==
|
integrity sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==
|
||||||
|
|
||||||
tslib@^1.10.0, tslib@^1.11.1, tslib@^1.11.2:
|
|
||||||
version "1.13.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043"
|
|
||||||
integrity sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q==
|
|
||||||
|
|
||||||
tslib@^2.0.0:
|
|
||||||
version "2.0.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.0.0.tgz#18d13fc2dce04051e20f074cc8387fd8089ce4f3"
|
|
||||||
integrity sha512-lTqkx847PI7xEDYJntxZH89L2/aXInsyF2luSafe/+0fHOMjlBNXdH6th7f70qxLDhul7KZK0zC8V5ZIyHl0/g==
|
|
||||||
|
|
||||||
tunnel-agent@^0.6.0:
|
tunnel-agent@^0.6.0:
|
||||||
version "0.6.0"
|
version "0.6.0"
|
||||||
resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd"
|
resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd"
|
||||||
@ -5471,17 +5392,6 @@ walker@^1.0.7, walker@~1.0.5:
|
|||||||
dependencies:
|
dependencies:
|
||||||
makeerror "1.0.x"
|
makeerror "1.0.x"
|
||||||
|
|
||||||
webcrypto-core@^1.1.0:
|
|
||||||
version "1.1.2"
|
|
||||||
resolved "https://registry.yarnpkg.com/webcrypto-core/-/webcrypto-core-1.1.2.tgz#c522a9e5596688f2b6bb19e2d336f68efa8bdd57"
|
|
||||||
integrity sha512-LxM/dTcXr/ZnwwKLox0tGEOIqvP7KIJ4Hk/fFPX20tr1EgqTmpEFZinmu4FzoGVbs6e4jI1priQKCDrOBD3L6w==
|
|
||||||
dependencies:
|
|
||||||
"@peculiar/asn1-schema" "^2.0.1"
|
|
||||||
"@peculiar/json-schema" "^1.1.10"
|
|
||||||
asn1js "^2.0.26"
|
|
||||||
pvtsutils "^1.0.10"
|
|
||||||
tslib "^1.11.2"
|
|
||||||
|
|
||||||
webidl-conversions@^4.0.2:
|
webidl-conversions@^4.0.2:
|
||||||
version "4.0.2"
|
version "4.0.2"
|
||||||
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad"
|
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad"
|
||||||
|
Loading…
Reference in New Issue
Block a user