formatting

This commit is contained in:
Sharon Kennedy 2020-03-23 00:28:00 -04:00
parent 42866ecfc7
commit c01de33895

View File

@ -12,7 +12,8 @@ import logger from "./logger";
const ENCRYPTION_CONFIG = { algorithm: "m.megolm.v1.aes-sha2" }; const ENCRYPTION_CONFIG = { algorithm: "m.megolm.v1.aes-sha2" };
const KICK_REASON = "A facilitator has already joined this chat."; 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 BOT_ERROR_MESSAGE =
"Something went wrong on our end, please restart the chat and try again.";
const MAX_RETRIES = 3; const MAX_RETRIES = 3;
class OcrccBot { class OcrccBot {
@ -38,9 +39,9 @@ class OcrccBot {
msgtype: "m.text", msgtype: "m.text",
body: msgText, body: msgText,
showToUser: showToUser showToUser: showToUser
} };
this.sendMessage(roomId, content) this.sendMessage(roomId, content);
} }
sendMessage(roomId, content) { sendMessage(roomId, content) {
@ -132,12 +133,16 @@ class OcrccBot {
this.client this.client
.getGroupUsers(process.env.FACILITATOR_GROUP_ID) .getGroupUsers(process.env.FACILITATOR_GROUP_ID)
.then(res => { .then(res => {
const members = res.chunk const members = res.chunk;
let onlineMembersCount = 0; let onlineMembersCount = 0;
members.forEach(member => { members.forEach(member => {
const memberId = member.user_id const memberId = member.user_id;
const user = this.client.getUser(memberId); const user = this.client.getUser(memberId);
if (user && user.presence === "online" && memberId !== process.env.BOT_USERID) { if (
user &&
user.presence === "online" &&
memberId !== process.env.BOT_USERID
) {
chatOffline = false; chatOffline = false;
this.inviteUserToRoom(this.client, roomId, memberId); this.inviteUserToRoom(this.client, roomId, memberId);
} }
@ -161,7 +166,7 @@ class OcrccBot {
.then(groupUsers => { .then(groupUsers => {
this.client.getJoinedRoomMembers(roomId).then(roomMembers => { this.client.getJoinedRoomMembers(roomId).then(roomMembers => {
const membersIds = Object.keys(roomMembers["joined"]); const membersIds = Object.keys(roomMembers["joined"]);
const facilitators = groupUsers.chunk const facilitators = groupUsers.chunk;
const facilitatorsIds = facilitators.map(f => f.user_id); const facilitatorsIds = facilitators.map(f => f.user_id);
facilitatorsIds.forEach(f => { facilitatorsIds.forEach(f => {
if (!membersIds.includes(f)) { if (!membersIds.includes(f)) {
@ -196,13 +201,13 @@ class OcrccBot {
} }
// 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 (process.env.CAPTURE_TRANSCRIPTS) { if (process.env.CAPTURE_TRANSCRIPTS) {
return this.writeToTranscript(event) return this.writeToTranscript(event);
} }
} }
@ -229,22 +234,33 @@ class OcrccBot {
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 command = content.body.substring("!bot".length).trim() const command = content.body.substring("!bot".length).trim();
switch (command) { switch (command) {
case 'transcript': case "transcript":
this.sendTranscript(senderId, roomId) this.sendTranscript(senderId, roomId);
break; break;
case 'transcript please': case "transcript please":
this.sendTranscript(senderId, roomId) this.sendTranscript(senderId, roomId);
break; break;
case 'hi': case "hi":
const responses = ['Hi!', 'Hello', 'Hey :)', 'Hi there', 'Bleep bloop'] const responses = [
const message = responses[Math.floor(Math.random() * responses.length)] "Hi!",
this.sendTextMessage(roomId, message, senderId) "Hello",
"Hey :)",
"Hi there",
"Bleep bloop"
];
const message =
responses[Math.floor(Math.random() * responses.length)];
this.sendTextMessage(roomId, message, senderId);
break; break;
default: default:
this.sendTextMessage(roomId, `Sorry, I don't know that command. I'm not a very smart bot.`, senderId) this.sendTextMessage(
roomId,
`Sorry, I don't know that command. I'm not a very smart bot.`,
senderId
);
break; break;
} }
} catch (err) { } catch (err) {
@ -255,16 +271,22 @@ class OcrccBot {
sendTranscript(senderId, roomId) { sendTranscript(senderId, roomId) {
const transcriptFile = this.activeChatrooms[roomId].transcriptFile; const transcriptFile = this.activeChatrooms[roomId].transcriptFile;
if (!transcriptFile) { if (!transcriptFile) {
this.sendTextMessage(roomId, 'There is no transcript for this chat.', senderId) this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
senderId
);
} }
const filename = path.basename(transcriptFile) || 'Transcript'; const filename = path.basename(transcriptFile) || "Transcript";
const stream = fs.createReadStream(transcriptFile); const stream = fs.createReadStream(transcriptFile);
this.client.uploadContent({ this.client
.uploadContent({
stream: stream, stream: stream,
name: filename name: filename
}).then((contentUrl) => { })
.then(contentUrl => {
const content = { const content = {
msgtype: "m.file", msgtype: "m.file",
body: filename, body: filename,
@ -273,11 +295,15 @@ class OcrccBot {
}; };
this.sendMessage(roomId, content); this.sendMessage(roomId, content);
}).catch(err => {
logger.log("error", `ERROR UPLOADING CONTENT: ${err}`)
this.sendTextMessage(roomId, 'There was an error uploading the transcript.', senderId)
}) })
.catch(err => {
logger.log("error", `ERROR UPLOADING CONTENT: ${err}`);
this.sendTextMessage(
roomId,
"There was an error uploading the transcript.",
senderId
);
});
} }
deleteOldDevices() { deleteOldDevices() {
@ -286,9 +312,7 @@ class OcrccBot {
const allDeviceIds = data.devices.map(d => d.device_id); const allDeviceIds = data.devices.map(d => d.device_id);
const oldDevices = allDeviceIds.filter(id => id !== currentDeviceId); const oldDevices = allDeviceIds.filter(id => id !== currentDeviceId);
logger.log("info", `DELETING OLD DEVICES: ${oldDevices}`); logger.log("info", `DELETING OLD DEVICES: ${oldDevices}`);
this.client this.client.deleteMultipleDevices(oldDevices).catch(err => {
.deleteMultipleDevices(oldDevices)
.catch(err => {
const auth = { const auth = {
session: err.data.session, session: err.data.session,
type: "m.login.password", type: "m.login.password",
@ -301,16 +325,16 @@ class OcrccBot {
.then(() => logger.log("info", "DELETED OLD DEVICES")) .then(() => logger.log("info", "DELETED OLD DEVICES"))
.catch(err => { .catch(err => {
if (err.errcode === "M_LIMIT_EXCEEDED") { if (err.errcode === "M_LIMIT_EXCEEDED") {
const delay = err.retry_after_ms || 2000 const delay = err.retry_after_ms || 2000;
logger.log("info", `RETRYING DELETE OLD DEVICES: ${oldDevices}`); logger.log("info", `RETRYING DELETE OLD DEVICES: ${oldDevices}`);
setTimeout(() => { setTimeout(() => {
this.client.deleteMultipleDevices(oldDevices) this.client.deleteMultipleDevices(oldDevices);
}, delay) }, delay);
} else { } else {
logger.log( logger.log(
"error", "error",
`ERROR DELETING OLD DEVICES: ${JSON.stringify(err.data)}` `ERROR DELETING OLD DEVICES: ${JSON.stringify(err.data)}`
) );
} }
}); });
}); });
@ -349,6 +373,20 @@ class OcrccBot {
this.activeChatrooms[member.roomId] = { this.activeChatrooms[member.roomId] = {
facilitator: member.userId facilitator: member.userId
}; };
const event = {
getType: () => {
return "m.room.power_levels";
},
getContent: () => {
return {
users: {
[process.env.BOT_USERID]: 100,
[member.userId]: 50
}
};
}
};
this.client.setPowerLevel(member.roomId, member.userId, 50, event);
this.sendTextMessage( this.sendTextMessage(
member.roomId, member.roomId,
`${member.name} has joined the chat.` `${member.name} has joined the chat.`
@ -365,10 +403,7 @@ class OcrccBot {
month: "short", month: "short",
day: "numeric" day: "numeric"
}; };
const chatDate = currentDate.toLocaleDateString( const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
"en-GB",
dateOpts
);
const chatTime = currentDate.toLocaleTimeString("en-GB", { const chatTime = currentDate.toLocaleTimeString("en-GB", {
timeZone: "America/New_York" timeZone: "America/New_York"
}); });
@ -399,7 +434,7 @@ class OcrccBot {
return logger.log("error", `ERROR DECRYPTING EVENT: ${err}`); return logger.log("error", `ERROR DECRYPTING EVENT: ${err}`);
} }
if (event.getType() === "m.room.message") { if (event.getType() === "m.room.message") {
this.handleMessageEvent(event) this.handleMessageEvent(event);
} }
}); });
// unencrypted messages // unencrypted messages
@ -411,7 +446,7 @@ class OcrccBot {
if (event.isEncrypted()) { if (event.isEncrypted()) {
return; return;
} }
this.handleMessageEvent(event) this.handleMessageEvent(event);
} }
}); });
} }
@ -429,7 +464,7 @@ class OcrccBot {
.then(data => { .then(data => {
const accessToken = data.access_token; const accessToken = data.access_token;
const deviceId = data.device_id; const deviceId = data.device_id;
logger.log('info', `LOGIN DATA ==> ${JSON.stringify(data)}`) logger.log("info", `LOGIN DATA ==> ${JSON.stringify(data)}`);
// create new client with full options // create new client with full options
@ -447,7 +482,7 @@ class OcrccBot {
logger.log("error", `ERROR WITH LOGIN: ${err}`); logger.log("error", `ERROR WITH LOGIN: ${err}`);
}) })
.then(() => { .then(() => {
this.deleteOldDevices() this.deleteOldDevices();
}) })
.then(() => this.client.initCrypto()) .then(() => this.client.initCrypto())
.catch(err => logger.log("error", `ERROR STARTING CRYPTO: ${err}`)) .catch(err => logger.log("error", `ERROR STARTING CRYPTO: ${err}`))
@ -457,8 +492,8 @@ class OcrccBot {
}) })
) )
.then(() => { .then(() => {
this.setMembershipListeners() this.setMembershipListeners();
this.setMessageListeners() this.setMessageListeners();
}) })
.then(() => this.client.startClient({ initialSyncLimit: 0 })) .then(() => this.client.startClient({ initialSyncLimit: 0 }))
.catch(err => { .catch(err => {
@ -469,4 +504,3 @@ class OcrccBot {
} }
export default OcrccBot; export default OcrccBot;