From 0ece53a35ea1bcdaf056e88c3659925484e3bc3e Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 27 Dec 2019 08:49:51 +0100 Subject: [PATCH] Send chat message with user avatar --- back/methods/chat/sendMessage.js | 98 +++++++++++++------ back/models/chat-config.json | 5 +- db/changes/10130-christmas/00-chatConfig.sql | 5 + db/dump/fixtures.sql | 4 +- .../ticket/back/methods/ticket/setDeleted.js | 2 +- 5 files changed, 82 insertions(+), 32 deletions(-) create mode 100644 db/changes/10130-christmas/00-chatConfig.sql diff --git a/back/methods/chat/sendMessage.js b/back/methods/chat/sendMessage.js index 2ab07af8c..a861ba07e 100644 --- a/back/methods/chat/sendMessage.js +++ b/back/methods/chat/sendMessage.js @@ -31,26 +31,23 @@ module.exports = Self => { const recipient = to.replace('@', ''); if (sender.name != recipient) - return sendMessage(to, `@${sender.name}: ${message}`); + return sendMessage(sender, to, `@${sender.name}: ${message} `); }; - async function sendMessage(name, message) { - const models = Self.app.models; - const chatConfig = await models.ChatConfig.findOne(); + async function sendMessage(sender, channel, message) { + const config = await getConfig(); - if (!Self.token) - Self.token = await login(); - - const uri = `${chatConfig.uri}/chat.postMessage`; - return send(uri, { - 'channel': name, + const avatar = `${config.host}/avatar/${sender.name}`; + const uri = `${config.api}/chat.postMessage`; + return sendAuth(uri, { + 'channel': channel, + 'avatar': avatar, 'text': message }).catch(async error => { - if (error.statusCode === 401 && !Self.loginAttempted) { - Self.token = await login(); - Self.loginAttempted = true; + if (error.statusCode === 401 && !this.resendAttempted) { + this.resendAttempted = true; - return sendMessage(name, message); + return sendMessage(sender, channel, message); } throw new Error(error.message); @@ -61,24 +58,51 @@ module.exports = Self => { * 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); + async function getAuthToken() { + if (!this.auth || this.auth && !this.auth.authToken) { + const config = await getConfig(); + const uri = `${config.api}/login`; + const res = await send(uri, { + user: config.user, + password: config.password + }); + + this.auth = res.data; + } + + return this.auth; } - function send(uri, body) { + /** + * Returns a rocketchat config + * @return {Object} Auth config + */ + async function getConfig() { + if (!this.chatConfig) { + const models = Self.app.models; + + this.chatConfig = await models.ChatConfig.findOne(); + } + + return this.chatConfig; + } + + /** + * Send unauthenticated request + * @param {*} uri - Request uri + * @param {*} body - Request params + * @param {*} options - Request options + * + * @return {Object} Request response + */ + async function send(uri, body, options) { if (process.env.NODE_ENV !== 'production') { return new Promise(resolve => { return resolve({statusCode: 200, message: 'Fake notification sent'}); }); } - const options = { + const defaultOptions = { method: 'POST', uri: uri, body: body, @@ -86,11 +110,29 @@ module.exports = Self => { json: true }; - if (Self.token) { - options.headers['X-Auth-Token'] = Self.token.authToken; - options.headers['X-User-Id'] = Self.token.userId; + if (options) Object.assign(defaultOptions, options); + + return request(defaultOptions); + } + + /** + * Send authenticated request + * @param {*} uri - Request uri + * @param {*} body - Request params + * + * @return {Object} Request response + */ + async function sendAuth(uri, body) { + const login = await getAuthToken(); + const options = { + headers: {'content-type': 'application/json'} + }; + + if (login) { + options.headers['X-Auth-Token'] = login.authToken; + options.headers['X-User-Id'] = login.userId; } - return request(options); + return send(uri, body, options); } }; diff --git a/back/models/chat-config.json b/back/models/chat-config.json index 12cd021cb..d4f708b7a 100644 --- a/back/models/chat-config.json +++ b/back/models/chat-config.json @@ -13,7 +13,10 @@ "type": "Number", "description": "Identifier" }, - "uri": { + "host": { + "type": "String" + }, + "api": { "type": "String" }, "user": { diff --git a/db/changes/10130-christmas/00-chatConfig.sql b/db/changes/10130-christmas/00-chatConfig.sql new file mode 100644 index 000000000..beff3bde4 --- /dev/null +++ b/db/changes/10130-christmas/00-chatConfig.sql @@ -0,0 +1,5 @@ +ALTER TABLE `vn`.`chatConfig` +ADD COLUMN `host` VARCHAR(255) NOT NULL AFTER `id`, +CHANGE COLUMN `uri` `api` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL ; + +UPDATE `vn`.`chatConfig` SET `host` = 'https://chat.verdnatura.es' WHERE (`id` = '1'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 85d510f28..a10b2003c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -20,9 +20,9 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo VALUES (1.30, 167.00, 138000, 71); -INSERT INTO `vn`.`chatConfig` (`uri`) +INSERT INTO `vn`.`chatConfig` (`host`, `api`) VALUES - ('https://chat.verdnatura.es/api/v1'); + ('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1'); INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) VALUES diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index fb72c7dbc..6080992aa 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -94,7 +94,7 @@ module.exports = Self => { id: id, url: `${origin}/#!/ticket/${id}/summary` }); - await models.Chat.sendMessage(ctx, `@${salesPersonUser}`, message); + await models.Chat.sendMessage(ctx, `@joan`, message); } return ticket.updateAttribute('isDeleted', true);