const request = require('request-promise-native'); module.exports = Self => { Self.remoteMethodCtx('sendMessage', { description: 'Send a RocketChat message', accessType: 'WRITE', accepts: [{ arg: 'to', type: 'String', required: true, description: 'user (@) or channel (#) to send the message' }, { arg: 'message', type: 'String', required: true, description: 'The message' }], returns: { type: 'Object', root: true }, http: { path: `/sendMessage`, verb: 'POST' } }); Self.sendMessage = async(ctx, to, message) => { const models = Self.app.models; const accessToken = ctx.req.accessToken; const sender = await models.Account.findById(accessToken.userId); const recipient = to.replace('@', ''); if (sender.name != recipient) return sendMessage(to, `@${sender.name}: ${message}`); }; async function sendMessage(name, message) { const models = Self.app.models; const chatConfig = await models.ChatConfig.findOne(); if (!Self.token) Self.token = await login(); const uri = `${chatConfig.uri}/chat.postMessage`; return send(uri, { 'channel': name, 'text': message }).catch(async error => { if (error.statusCode === 401 && !Self.loginAttempted) { Self.token = await login(); Self.loginAttempted = true; return sendMessage(name, message); } throw new Error(error.message); }); } /** * Returns a rocketchat token * @return {Object} userId and authToken */ async function login() { const models = Self.app.models; const chatConfig = await models.ChatConfig.findOne(); const uri = `${chatConfig.uri}/login`; return send(uri, { user: chatConfig.user, password: chatConfig.password }).then(res => res.data); } function send(uri, body) { if (process.env.NODE_ENV !== 'production') { return new Promise(resolve => { return resolve({statusCode: 200, message: 'Fake notification sent'}); }); } const options = { method: 'POST', uri: uri, body: body, headers: {'content-type': 'application/json'}, json: true }; if (Self.token) { options.headers['X-Auth-Token'] = Self.token.authToken; options.headers['X-User-Id'] = Self.token.userId; } return request(options); } };