salix/back/methods/chat/sendCheckingPresence.js

96 lines
3.0 KiB
JavaScript

const axios = require('axios');
module.exports = Self => {
Self.remoteMethodCtx('sendCheckingPresence', {
description: 'Sends a RocketChat message to a connected user or department channel',
accessType: 'WRITE',
accepts: [{
arg: 'workerId',
type: 'number',
required: true,
description: 'The recipient user id'
},
{
arg: 'message',
type: 'string',
required: true,
description: 'The message'
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/sendCheckingPresence`,
verb: 'POST'
}
});
Self.sendCheckingPresence = async(ctx, recipientId, message, options) => {
if (!recipientId) return false;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const recipient = await models.Account.findById(recipientId, null, myOptions);
// Prevent sending messages to yourself
if (recipientId == userId) return false;
if (!recipient)
throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);
const {data} = await Self.getUserStatus(recipient.name);
if (data) {
if (data.status === 'offline') {
// Send message to department room
const workerDepartment = await models.WorkerDepartment.findById(recipientId, {
include: {
relation: 'department'
}
}, 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);
}
};
/**
* 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);
};
};