rewuite to use async

This commit is contained in:
Sharon Kennedy 2020-04-22 01:35:34 -04:00
parent fefda571d6
commit 242d32639a
6 changed files with 786 additions and 660 deletions

View File

@ -1,8 +0,0 @@
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"dynamic-import-node"
]
}

View File

@ -21,9 +21,20 @@
},
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.8.4",
"@babel/node": "^7.8.4",
"@babel/preset-env": "^7.8.4",
"@babel/core": "7.7.7",
"@babel/node": "^7.8.7",
"@babel/plugin-proposal-class-properties": "7.7.4",
"@babel/plugin-proposal-decorators": "7.7.4",
"@babel/plugin-proposal-export-namespace-from": "7.7.4",
"@babel/plugin-proposal-function-sent": "7.7.4",
"@babel/plugin-proposal-json-strings": "7.7.4",
"@babel/plugin-proposal-numeric-separator": "7.7.4",
"@babel/plugin-proposal-object-rest-spread": "^7.9.5",
"@babel/plugin-proposal-throw-expressions": "7.7.4",
"@babel/plugin-syntax-dynamic-import": "7.7.4",
"@babel/plugin-syntax-import-meta": "7.7.4",
"@babel/plugin-transform-runtime": "^7.9.0",
"@babel/preset-env": "^7.9.0",
"babel-jest": "^25.1.0",
"babel-plugin-dynamic-import-node": "^2.3.0",
"jest": "^25.1.0",
@ -32,6 +43,38 @@
"wait-for-expect": "^3.0.2"
},
"jest": {
"testPathIgnorePatterns": ["dist"]
"testPathIgnorePatterns": [
"dist"
]
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "12"
}
}
]
],
"plugins": [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-import-meta",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-json-strings",
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-proposal-function-sent",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-throw-expressions",
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-transform-runtime"
]
}
}

View File

@ -10,22 +10,18 @@ import * as matrix from "matrix-js-sdk";
import logger from "./logger";
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;
class OcrccBot {
constructor() {
constructor(botConfig) {
this.config = botConfig
this.awaitingFacilitator = {};
this.client = matrix.createClient(process.env.MATRIX_SERVER_URL);
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
this.joinedRooms = [];
this.activeChatrooms = {};
}
createLocalStorage() {
const storageLoc = `matrix-chatbot-${process.env.BOT_USERNAME}`;
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
@ -44,150 +40,102 @@ class OcrccBot {
this.sendMessage(roomId, content);
}
sendMessage(roomId, content) {
async sendMessage(roomId, content) {
logger.log("info", `SENDING MESSAGE: ${content.body}`)
return this.client.sendMessage(roomId, content).catch(err => {
switch (err["name"]) {
case "UnknownDeviceError":
Object.keys(err.devices).forEach(userId => {
Object.keys(err.devices[userId]).map(deviceId => {
this.client.setDeviceVerified(userId, deviceId, true);
Object.keys(err.devices[userId]).map(async deviceId => {
await this.client.setDeviceVerified(userId, deviceId, true);
});
});
return this.sendMessage(roomId, content);
break;
default:
logger.log("error", `ERROR SENDING MESSAGE: ${err}`);
this.handleBotCrash(roomId, err);
break;
}
});
}
inviteUserToRoom(client, roomId, member, retries = 0) {
logger.log("info", "INVITING MEMBER: " + member);
if (retries > MAX_RETRIES) {
this.handleBotCrash(roomId, "Rate limit exceeded for bot account");
return logger.log(
"error",
`RATE LIMIT EXCEEDED AND RETRY LIMIT EXCEEDED`
);
inviteUserToRoom(roomId, member) {
try {
this.client.invite(roomId, member)
} catch(err) {
this.handleBotCrash(roomId, err);
}
return client.invite(roomId, member).catch(err => {
switch (err["name"]) {
case "M_LIMIT_EXCEEDED":
logger.log("info", "Rate limit exceeded, retrying.");
const retryCount = retries + 1;
const delay = retryCount * 2 * 1000;
return setTimeout(
this.inviteUserToRoom,
delay,
client,
roomId,
member,
retryCount
);
break;
default:
logger.log("error", `ERROR INVITING MEMBER: ${err}`);
this.handleBotCrash(roomId, err);
break;
}
});
}
kickUserFromRoom(client, roomId, member, retries = 0) {
logger.log("info", "KICKING OUT MEMBER: " + member);
if (retries > MAX_RETRIES) {
this.handleBotCrash(roomId, "Rate limit exceeded for bot account.");
return logger.log(
"error",
`RATE LIMIT EXCEEDED AND RETRY LIMIT EXCEEDED`
);
kickUserFromRoom(roomId, member) {
try {
this.client.kick(roomId, member, this.config.KICK_REASON)
} catch(err) {
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
}
return client.kick(roomId, member, KICK_REASON).catch(err => {
switch (err["name"]) {
case "M_LIMIT_EXCEEDED":
logger.log("info", "Rate limit exceeded, retrying.");
const retryCount = retries + 1;
const delay = retryCount * 2 * 1000;
return setTimeout(
this.kickUserFromRoom,
delay,
client,
roomId,
member,
retryCount
);
break;
default:
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
break;
}
});
}
inviteFacilitators(roomId) {
async inviteFacilitators(roomId) {
this.awaitingFacilitator[roomId] = true;
let chatOffline = true;
this.client
.getGroupUsers(process.env.FACILITATOR_GROUP_ID)
.then(res => {
const members = res.chunk;
let onlineMembersCount = 0;
members.forEach(member => {
const memberId = member.user_id;
const user = this.client.getUser(memberId);
if (
user &&
user.presence === "online" &&
memberId !== process.env.BOT_USERID
) {
chatOffline = false;
this.inviteUserToRoom(this.client, roomId, memberId);
}
});
})
.then(() => {
if (chatOffline) {
this.sendTextMessage(roomId, process.env.CHAT_OFFLINE_MESSAGE);
try {
const data = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
const members = data.chunk
members.forEach(member => {
const memberId = member.user_id;
const user = this.client.getUser(memberId);
if (
user &&
user.presence === "online" &&
memberId !== this.config.BOT_USERID
) {
chatOffline = false;
this.inviteUserToRoom(roomId, memberId);
}
})
.catch(err => {
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR GETTING FACILITATORS: ${err}`);
});
if (chatOffline) {
logger.log('info', "CHAT OFFLINE!")
this.sendTextMessage(roomId, this.config.CHAT_OFFLINE_MESSAGE);
}
} catch(err) {
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR GETTING FACILITATORS: ${err}`);
}
}
uninviteFacilitators(roomId) {
async uninviteFacilitators(roomId) {
this.awaitingFacilitator[roomId] = false;
this.client
.getGroupUsers(process.env.FACILITATOR_GROUP_ID)
.then(groupUsers => {
this.client.getJoinedRoomMembers(roomId).then(roomMembers => {
const membersIds = Object.keys(roomMembers["joined"]);
const facilitators = groupUsers.chunk;
const facilitatorsIds = facilitators.map(f => f.user_id);
facilitatorsIds.forEach(f => {
if (!membersIds.includes(f)) {
this.kickUserFromRoom(this.client, roomId, f);
}
});
});
})
.catch(err => {
this.handleBotCrash(roomId, err);
logger.log("error", err);
try {
const groupUsers = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
const roomMembers = await this.client.getJoinedRoomMembers(roomId)
const membersIds = Object.keys(roomMembers["joined"]);
const facilitatorsIds = groupUsers.chunk.map(f => f.user_id);
facilitatorsIds.forEach(f => {
if (!membersIds.includes(f)) {
this.kickUserFromRoom(roomId, f);
}
});
} catch(err) {
this.handleBotCrash(roomId, err);
logger.log("ERROR UNINVITING FACILITATORS", err);
}
}
handleBotCrash(roomId, error) {
if (roomId) {
this.sendTextMessage(roomId, BOT_ERROR_MESSAGE);
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
}
this.sendTextMessage(
process.env.FACILITATOR_ROOM_ID,
this.config.FACILITATOR_ROOM_ID,
`The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`
);
}
@ -206,7 +154,7 @@ class OcrccBot {
}
// write to transcript
if (process.env.CAPTURE_TRANSCRIPTS) {
if (this.config.CAPTURE_TRANSCRIPTS) {
return this.writeToTranscript(event);
}
}
@ -268,109 +216,112 @@ class OcrccBot {
}
}
sendTranscript(senderId, roomId) {
const transcriptFile = this.activeChatrooms[roomId]
? this.activeChatrooms[roomId].transcriptFile
: false;
if (!transcriptFile) {
this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
senderId
);
}
async sendTranscript(senderId, roomId) {
try {
const transcriptFile = this.activeChatrooms[roomId]
? this.activeChatrooms[roomId].transcriptFile
: false;
if (!transcriptFile) {
this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
senderId
);
}
const filename = path.basename(transcriptFile) || "Transcript";
const stream = fs.createReadStream(transcriptFile);
const filename = path.basename(transcriptFile) || "Transcript";
const stream = fs.createReadStream(transcriptFile);
this.client
.uploadContent({
const contentUrl = await this.client.uploadContent({
stream: stream,
name: filename
})
.then(contentUrl => {
const content = {
msgtype: "m.file",
body: filename,
url: JSON.parse(contentUrl).content_uri,
showToUser: senderId
};
this.sendMessage(roomId, content);
})
.catch(err => {
logger.log("error", `ERROR UPLOADING CONTENT: ${err}`);
this.sendTextMessage(
roomId,
"There was an error uploading the transcript.",
senderId
);
});
const content = {
msgtype: "m.file",
body: filename,
url: JSON.parse(contentUrl).content_uri,
showToUser: senderId
};
this.sendMessage(roomId, content);
} catch(err) {
logger.log("error", `ERROR UPLOADING CONTENT: ${err}`);
this.sendTextMessage(
roomId,
"There was an error uploading the transcript.",
senderId
);
}
}
deleteOldDevices() {
return this.client.getDevices().then(data => {
const currentDeviceId = this.client.getDeviceId();
const allDeviceIds = data.devices.map(d => d.device_id);
const oldDevices = allDeviceIds.filter(id => id !== currentDeviceId);
logger.log("info", `DELETING OLD DEVICES: ${oldDevices}`);
this.client.deleteMultipleDevices(oldDevices).catch(err => {
const auth = {
session: err.data.session,
type: "m.login.password",
user: process.env.BOT_USERID,
identifier: { type: "m.id.user", user: process.env.BOT_USERID },
password: process.env.BOT_PASSWORD
};
this.client
.deleteMultipleDevices(oldDevices, auth)
.then(() => logger.log("info", "DELETED OLD DEVICES"))
.catch(err => {
if (err.errcode === "M_LIMIT_EXCEEDED") {
const delay = err.retry_after_ms || 2000;
logger.log("info", `RETRYING DELETE OLD DEVICES: ${oldDevices}`);
setTimeout(() => {
this.client.deleteMultipleDevices(oldDevices);
}, delay);
} else {
logger.log(
"error",
`ERROR DELETING OLD DEVICES: ${JSON.stringify(err.data)}`
);
}
});
});
});
async deleteOldDevices() {
const currentDeviceId = this.client.getDeviceId();
const deviceData = await this.client.getDevices()
const allDeviceIds = deviceData.devices.map(d => d.device_id)
const oldDevices = allDeviceIds.filter(id => id !== currentDeviceId);
try {
await this.client.deleteMultipleDevices(oldDevices)
} catch(err) {
logger.log("info", "RETRYING DELETE OLD DEVICES WITH AUTH")
const auth = {
session: err.data.session,
type: "m.login.password",
user: this.config.BOT_USERID,
identifier: { type: "m.id.user", user: this.config.BOT_USERID },
password: this.config.BOT_PASSWORD
};
await this.client.deleteMultipleDevices(oldDevices, auth)
logger.log("info", "DELETED OLD DEVICES")
}
}
setMembershipListeners() {
async leaveOldRooms() {
const roomData = await this.client.getJoinedRooms()
const joinedRoomsIds = roomData["joined_rooms"]
this.joinedRooms = joinedRoomsIds
logger.log("info", `LEAVING ROOMS ${joinedRoomsIds}`)
joinedRoomsIds.forEach(async(roomId) => {
if (roomId === this.config.FACILITATOR_ROOM_ID) return;
try {
await this.client.leave(roomId)
} catch(err) {
logger.log("error", `ERROR LEAVING ROOM => ${err}`)
}
})
}
async setMembershipListeners() {
// Automatically accept all room invitations
return this.client.on("RoomMember.membership", (event, member) => {
this.client.on("RoomMember.membership", async (event, member) => {
if (
member.membership === "invite" &&
member.userId === process.env.BOT_USERID &&
member.userId === this.config.BOT_USERID &&
!this.joinedRooms.includes(member.roomId)
) {
logger.log("info", "Auto-joining room " + member.roomId);
this.client
.joinRoom(member.roomId)
.then(room => {
this.sendTextMessage(
process.env.FACILITATOR_ROOM_ID,
`A support seeker requested a chat (Room ID: ${member.roomId})`
);
})
.then(() => this.inviteFacilitators(member.roomId))
.catch(err => {
logger.log("error", err);
});
try {
logger.log("info", "Auto-joining room " + member.roomId);
const room = await this.client.joinRoom(member.roomId)
this.sendTextMessage(
this.config.FACILITATOR_ROOM_ID,
`A support seeker requested a chat (Room ID: ${member.roomId})`
);
this.inviteFacilitators(member.roomId)
} catch(err) {
logger.log("error", err);
}
}
// When a facilitator joins a support session, make them a moderator
// revoke the other invitations
if (
member.membership === "join" &&
member.userId !== process.env.BOT_USERID &&
member.userId !== this.config.BOT_USERID &&
this.awaitingFacilitator[member.roomId]
) {
this.activeChatrooms[member.roomId] = {
@ -383,7 +334,7 @@ class OcrccBot {
getContent: () => {
return {
users: {
[process.env.BOT_USERID]: 100,
[this.config.BOT_USERID]: 100,
[member.userId]: 50
}
};
@ -395,11 +346,11 @@ class OcrccBot {
`${member.name} has joined the chat.`
);
this.sendTextMessage(
process.env.FACILITATOR_ROOM_ID,
this.config.FACILITATOR_ROOM_ID,
`${member.name} joined the chat (Room ID: ${member.roomId})`
);
this.uninviteFacilitators(member.roomId);
if (process.env.CAPTURE_TRANSCRIPTS) {
if (this.config.CAPTURE_TRANSCRIPTS) {
const currentDate = new Date();
const dateOpts = {
year: "numeric",
@ -418,7 +369,7 @@ class OcrccBot {
if (
member.membership === "leave" &&
member.userId !== process.env.BOT_USERID &&
member.userId !== this.config.BOT_USERID &&
this.activeChatrooms[member.roomId] &&
member.userId === this.activeChatrooms[member.roomId].facilitator
) {
@ -426,6 +377,14 @@ class OcrccBot {
member.roomId,
`${member.name} has left the chat.`
);
const room = this.client.getRoom(member.roomId)
const memberCount = room.getJoinedMemberCount()
if (memberCount === 1) {
logger.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
this.client.leave(event.roomId)
}
}
});
}
@ -448,54 +407,38 @@ class OcrccBot {
});
}
start() {
async start() {
const localStorage = this.createLocalStorage();
this.client
.login("m.login.password", {
user: process.env.BOT_USERNAME,
password: process.env.BOT_PASSWORD,
initial_device_display_name: process.env.BOT_DISPLAY_NAME
})
.then(data => {
const accessToken = data.access_token;
const deviceId = data.device_id;
logger.log("info", `LOGIN DATA ==> ${JSON.stringify(data)}`);
try {
const auth = {
user: this.config.BOT_USERNAME,
password: this.config.BOT_PASSWORD,
initial_device_display_name: this.config.BOT_DISPLAY_NAME
}
const account = await this.client.login("m.login.password", auth)
logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
// create new client with full options
let opts = {
baseUrl: this.config.MATRIX_SERVER_URL,
accessToken: account.access_token,
userId: this.config.BOT_USERID,
deviceId: account.device_id,
sessionStore: new matrix.WebStorageSessionStore(localStorage)
};
let opts = {
baseUrl: process.env.MATRIX_SERVER_URL,
accessToken: accessToken,
userId: process.env.BOT_USERID,
deviceId: deviceId,
sessionStore: new matrix.WebStorageSessionStore(localStorage)
};
this.client = matrix.createClient(opts);
await this.deleteOldDevices()
await this.leaveOldRooms();
await this.client.initCrypto()
this.client = matrix.createClient(opts);
})
.catch(err => {
logger.log("error", `ERROR WITH LOGIN: ${err}`);
})
.then(() => {
this.deleteOldDevices();
})
.then(() => this.client.initCrypto())
.catch(err => logger.log("error", `ERROR STARTING CRYPTO: ${err}`))
.then(() =>
this.client.getJoinedRooms().then(data => {
this.joinedRooms = data["joined_rooms"];
})
)
.then(() => {
this.setMembershipListeners();
this.setMessageListeners();
})
.then(() => this.client.startClient({ initialSyncLimit: 0 }))
.catch(err => {
this.handleBotCrash(undefined, err);
logger.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
});
this.setMembershipListeners();
this.setMessageListeners();
this.client.startClient({ initialSyncLimit: 0 })
} catch(err) {
this.handleBotCrash(undefined, err);
logger.log("error", `ERROR INITIALIZING CLIENT: ${err}`);
}
}
}

View File

@ -1,6 +1,39 @@
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_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();
const bot = new OcrccBot(botConfig);
bot.start();

View File

@ -1,5 +0,0 @@
@help-bot:rhok.space [17:39:36]: Facilitator Demo Account has joined the chat.
@ocrcc-facilitator-demo:rhok.space [17:39:48]: heyooo
@help-bot:rhok.space [17:41:13]: Bleep bloop
@help-bot:rhok.space [17:41:21]: 20 Mar 2020 - 17:39:35 - !HyOQxerRxiwlUBolJA:rhok.space.txt
@95326bf0-cd5e-45d7-be64-cb413d37d929:rhok.space [17:42:01]: hi

912
yarn.lock

File diff suppressed because it is too large Load Diff