salix/back/methods/chat/sendQueued.js

79 lines
2.1 KiB
JavaScript
Raw Normal View History

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