feat: add queue to send rocket messages
gitea/salix/pipeline/head This commit is unstable Details

This commit is contained in:
Vicent Llopis 2022-06-03 12:22:07 +02:00
parent f6028316f4
commit 3eac002fb4
4 changed files with 124 additions and 101 deletions

View File

@ -1,4 +1,3 @@
const axios = require('axios');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('send', { Self.remoteMethodCtx('send', {
description: 'Send a RocketChat message', description: 'Send a RocketChat message',
@ -31,39 +30,19 @@ module.exports = Self => {
const recipient = to.replace('@', ''); const recipient = to.replace('@', '');
if (sender.name != recipient) { if (sender.name != recipient) {
await sendMessage(sender, to, message); await models.Chat.create({
senderFk: sender.id,
recipient: to,
dated: new Date(),
checkUserStatus: 0,
message: message,
status: 0,
attempts: 0
});
return true; return true;
} }
return false;
}; };
async function sendMessage(sender, channel, message) { return false;
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({
statusCode: 200,
message: 'Fake notification sent'
});
});
}
const login = await Self.getServiceAuth();
const avatar = `${login.host}/avatar/${sender.name}`;
const options = {
headers: {
'X-Auth-Token': login.auth.token,
'X-User-Id': login.auth.userId
},
};
return axios.post(`${login.api}/chat.postMessage`, {
'channel': channel,
'avatar': avatar,
'alias': sender.nickname,
'text': message
}, options);
}
}; };

View File

@ -1,5 +1,3 @@
const axios = require('axios');
module.exports = Self => { module.exports = Self => {
Self.remoteMethodCtx('sendCheckingPresence', { Self.remoteMethodCtx('sendCheckingPresence', {
description: 'Sends a RocketChat message to a connected user or department channel', description: 'Sends a RocketChat message to a connected user or department channel',
@ -36,6 +34,7 @@ module.exports = Self => {
const models = Self.app.models; const models = Self.app.models;
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const sender = await models.Account.findById(userId);
const recipient = await models.Account.findById(recipientId, null, myOptions); const recipient = await models.Account.findById(recipientId, null, myOptions);
// Prevent sending messages to yourself // Prevent sending messages to yourself
@ -44,54 +43,14 @@ module.exports = Self => {
if (!recipient) if (!recipient)
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`); throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
const {data} = await Self.getUserStatus(recipient.name); return models.Chat.create({
if (data) { senderFk: sender.id,
if (data.status === 'offline' || data.status === 'busy') { recipient: `@${recipient.name}`,
// Send message to department room dated: new Date(),
const workerDepartment = await models.WorkerDepartment.findById(recipientId, { checkUserStatus: 1,
include: { message: message,
relation: 'department' status: 0,
} attempts: 0
}, myOptions); });
const department = workerDepartment && workerDepartment.department();
const channelName = department && department.chatName;
if (channelName)
return Self.send(ctx, `#${channelName}`, `@${recipient.name}${message}`);
else
return Self.send(ctx, `@${recipient.name}`, message);
} else
return Self.send(ctx, `@${recipient.name}`, message);
}
};
/**
* Returns the current user status on Rocketchat
*
* @param {string} username - The recipient user name
* @return {Promise} - The request promise
*/
Self.getUserStatus = async function getUserStatus(username) {
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({
data: {
status: 'online'
}
});
});
}
const login = await Self.getServiceAuth();
const options = {
params: {username},
headers: {
'X-Auth-Token': login.auth.token,
'X-User-Id': login.auth.userId
},
};
return axios.get(`${login.api}/users.getStatus`, options);
}; };
}; };

View File

@ -16,33 +16,75 @@ module.exports = Self => {
Self.sendQueued = async ctx => { Self.sendQueued = async ctx => {
const models = Self.app.models; const models = Self.app.models;
const maxAttempts = 3;
const sentStatus = 1; const sentStatus = 1;
const errorStatus = 2;
const chats = await models.Chat.find({ const chats = await models.Chat.find({
where: { where: {
status: {neq: sentStatus} status: {neq: sentStatus},
attempts: {lt: maxAttempts}
} }
}); });
for (let chat of chats) { for (let chat of chats) {
if (chat.checkUserStatus) if (chat.checkUserStatus) {
await sendCheckingPresence(ctx, chat); try {
else await sendCheckingUserStatus(chat);
await sendMessage(chat); await updateChat(chat, sentStatus);
} catch (error) {
await updateChat(chat, errorStatus);
}
} else {
try {
await sendMessage(chat.senderFk, chat.recipient, chat.message);
await updateChat(chat, sentStatus);
} catch (error) {
await updateChat(chat, errorStatus);
}
}
} }
}; };
async function sendCheckingPresence(ctx, chat) { async function sendCheckingUserStatus(chat) {
const models = Self.app.models; const models = Self.app.models;
const recipientName = chat.recipient.slice(1);
const recipient = await models.Account.findOne({ const recipient = await models.Account.findOne({
where: { where: {
name: chat.recipient name: recipientName
} }
}); });
await models.Chat.sendCheckingPresence(ctx, recipient.id, chat.message);
}
async function sendMessage(chat) { const {data} = await getUserStatus(recipient.name);
if (data) {
if (data.status === 'offline' || data.status === 'busy') {
// Send message to department room
const workerDepartment = await models.WorkerDepartment.findById(recipient.id, {
include: {
relation: 'department'
}
});
const department = workerDepartment && workerDepartment.department();
const channelName = department && department.chatName;
if (channelName)
return sendMessage(chat.senderFk, `#${channelName}`, `@${recipient.name}${message}`);
else
return sendMessage(chat.senderFk, `@${recipient.name}`, chat.message);
} else
return sendMessage(chat.senderFk, `@${recipient.name}`, chat.message);
}
}
/**
* Update status and attempts of a chat
*
* @param {object} senderFk - The sender id
* @param {string} recipient - The user (@) or channel (#) to send the message
* @param {string} message - The message to send
* @return {Promise} - The request promise
*/
async function sendMessage(senderFk, recipient, message) {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => { return new Promise(resolve => {
return resolve({ return resolve({
@ -52,11 +94,8 @@ module.exports = Self => {
}); });
} }
const sender = await models.Account.findOne({ const models = Self.app.models;
where: { const sender = await models.Account.findById(senderFk);
name: chat.senderFk
}
});
const login = await Self.getServiceAuth(); const login = await Self.getServiceAuth();
const avatar = `${login.host}/avatar/${sender.name}`; const avatar = `${login.host}/avatar/${sender.name}`;
@ -69,10 +108,54 @@ module.exports = Self => {
}; };
return axios.post(`${login.api}/chat.postMessage`, { return axios.post(`${login.api}/chat.postMessage`, {
'channel': `@${chat.recipient}`, 'channel': recipient,
'avatar': avatar, 'avatar': avatar,
'alias': sender.nickname, 'alias': sender.nickname,
'text': chat.message 'text': message
}, options); }, options);
} }
/**
* Update status and attempts of a chat
*
* @param {object} chat - The chat
* @param {string} status - The new status
* @return {Promise} - The request promise
*/
async function updateChat(chat, status) {
return chat.updateAttributes({
status: status,
attempts: ++chat.attempts
});
}
/**
* Returns the current user status on Rocketchat
*
* @param {string} username - The recipient user name
* @return {Promise} - The request promise
*/
async function getUserStatus(username) {
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({
data: {
status: 'online'
}
});
});
}
const login = await Self.getServiceAuth();
const options = {
params: {username},
headers: {
'X-Auth-Token': login.auth.token,
'X-User-Id': login.auth.userId
},
};
return axios.get(`${login.api}/users.getStatus`, options);
}
}; };

View File

@ -2562,7 +2562,9 @@ INSERT INTO `vn`.`supplierAgencyTerm` (`agencyFk`, `supplierFk`, `minimumPackage
INSERT INTO `vn`.`chat` (`senderFk`, `recipient`, `dated`, `checkUserStatus`, `message`, `status`, `attempts`) INSERT INTO `vn`.`chat` (`senderFk`, `recipient`, `dated`, `checkUserStatus`, `message`, `status`, `attempts`)
VALUES VALUES
(1101, 'PetterParker', '2022-06-02', 1, 'First test message', 0, 0); (1101, '@PetterParker', CURDATE(), 1, 'First test message', 0, 0),
(1101, '@PetterParker', CURDATE(), 0, 'Second test message', 0, 0);
INSERT INTO `vn`.`mobileAppVersionControl` (`appName`, `version`, `isVersionCritical`) INSERT INTO `vn`.`mobileAppVersionControl` (`appName`, `version`, `isVersionCritical`)
VALUES VALUES