salix/back/methods/chat/sendQueued.js

79 lines
2.1 KiB
JavaScript

const axios = require('axios');
module.exports = Self => {
Self.remoteMethodCtx('sendQueued', {
description: 'Send a RocketChat message',
accessType: 'WRITE',
accepts: [],
returns: {
type: 'object',
root: true
},
http: {
path: `/sendQueued`,
verb: 'POST'
}
});
Self.sendQueued = async ctx => {
const models = Self.app.models;
const sentStatus = 1;
const chats = await models.Chat.find({
where: {
status: {neq: sentStatus}
}
});
for (let chat of chats) {
if (chat.checkUserStatus)
await sendCheckingPresence(ctx, chat);
else
await sendMessage(chat);
}
};
async function sendCheckingPresence(ctx, chat) {
const models = Self.app.models;
const recipient = await models.Account.findOne({
where: {
name: chat.recipient
}
});
await models.Chat.sendCheckingPresence(ctx, recipient.id, chat.message);
}
async function sendMessage(chat) {
if (process.env.NODE_ENV !== 'production') {
return new Promise(resolve => {
return resolve({
statusCode: 200,
message: 'Fake notification sent'
});
});
}
const sender = await models.Account.findOne({
where: {
name: chat.senderFk
}
});
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': `@${chat.recipient}`,
'avatar': avatar,
'alias': sender.nickname,
'text': chat.message
}, options);
}
};