Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Copyright 2015 IBM Corp. All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- 'use strict';
- var express = require('express'); // app server
- var bodyParser = require('body-parser'); // parser for post requests
- var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
- var fs = require('fs');
- var http = require('http');
- var https = require('https');
- var privateKey = fs.readFileSync('./newkey.pem', 'utf8');
- var certificate = fs.readFileSync('./newcert.pem', 'utf8');
- var credentials = {key: privateKey, cert: certificate};
- var cors = require('cors')
- var request = require('request');
- var cookieParser = require('cookie-parser');
- var helmet = require('helmet')
- var randomstring = require('randomstring');
- var crypto = require('crypto');
- var app = express();
- // Bootstrap application settings
- app.use(helmet({
- frameguard: false
- }));
- app.use(express.static('./public')); // load UI from public folder
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: true }));
- app.use(cors());
- app.use(cookieParser());
- app.use(function (req, res, next) {
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
- res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
- next();
- });
- var httpServer = http.createServer(app);
- var httpsServer = https.createServer(credentials, app);
- httpServer.listen(8080);
- httpsServer.listen(443);
- // Create the service wrapper
- var conversation = new Conversation({
- // If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
- // After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
- // username: '<username>',
- // password: '<password>',
- // url: 'https://gateway.watsonplatform.net/conversation/api',
- version_date: Conversation.VERSION_DATE_2017_04_21
- });
- function checkToken(req, res, next){
- if(req.path === '/AuthBdesk' || req.path === '/verificar-token'){
- next();
- } else {
- var extraData = req.cookies.extraData;
- var token = req.cookies.tokenbdesk;
- var sha_password = crypto.createHash('sha256').update('q7KuDO&8DAuLU09').digest("hex");
- var key = 'chatbot-watson' + sha_password + extraData + 'https://hmggabi.aguiabranca.com.br/AuthBdesk'
- var generated_token = crypto.createHash('sha256').update(key).digest("hex");
- if(token == generated_token){
- next();
- } else {
- res.status(403).end('Forbidden');
- }
- }
- }
- app.use(checkToken);
- app.get('/AuthBdesk', function(req, res){
- var token = req.query.token;
- res.cookie("tokenbdesk", token);
- res.redirect("http://hmggabi.aguiabranca.com.br/iframe-gab.html");
- });
- app.post('/verificar-token', function(req, res){
- var sha_password = crypto.createHash('sha256').update('q7KuDO&8DAuLU09').digest("hex");
- var key = 'chatbot-watson' + sha_password + req.body.extraData + 'https://hmggabi.aguiabranca.com.br/AuthBdesk'
- var generated_token = crypto.createHash('sha256').update(key).digest("hex");
- if(req.body.token == generated_token){
- res.send("success");
- } else {
- res.clearCookie("token-bdesk");
- res.send("error");
- }
- });
- // Endpoint to be call from the client side
- app.post('/api/message', function(req, res) {
- var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
- if (!workspace || workspace === '<workspace-id>') {
- return res.json({
- 'output': {
- 'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple">README</a> documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple/blob/master/training/car_workspace.json">here</a> in order to get a working application.'
- }
- });
- }
- var payload = {
- workspace_id: workspace,
- context: req.body.context || {},
- input: req.body.input || {}
- };
- // Send the input to the conversation service
- conversation.message(payload, function(err, data) {
- if (err) {
- return res.status(err.code || 500).json(err);
- }
- return res.header("Access-Control-Allow-Origin", "*")
- .header("Access-Control-Allow-Headers", "X-Requested-With")
- .json(updateMessage(payload, data));
- });
- });
- app.post('/abrir-chamado', function(req, res){
- var headers = {
- 'Authorization': 'Bearer gAAAACiGdw5NEUH4ir-qZFwJNs9Kc4B2H5d8JEsEVhPEtn4-xSUMDg735c313I8A1ZRAhqkLCigg73ZJL2ofgHhPU7L8bqtOHEYsGuV6IgCL4SQCGHLZEdbnG-tEBAg7NRzrqsZQhUjmugztEO0vKeHci7aOMA8lxAA51Q60gMnKRl3VFAEAAIAAAABOm_ptCKu1pBdhIPWKOEZW750p2leNSM4eCFv-I8l7J7p0uTOnVk0Ifhezl8V1btLYUHnpHwD0m0K1OmSGXIk41Sx1dfaJL0tQDYu4mDFiJU-_Nrw-tbAj6P28Da09eUS2LUrfwnETX5KWOyJECWhXHCFk0liR9wcPVVNwtXyxfm7pfSfTwGo2qb9B1dt1CEM6zdy93c66-XLXFN89Uoub88Va9uErhkwYTeWwkZMgp5WJm6Kw5x6ara053usmmTtXQyLsOC3OYOUR2Jzs1EEnG3539IkTJhdYp4EFv69VZZeChJ79hBn4rMl1t-kBA3CT_cev52Fz3ZmtpkhRENfvy19lUC50n6O9Ow6jMTcYKQ',
- 'Content-Type': 'application/json'
- }
- if (req.body.cpf){
- var participanteOptions = {
- //TODO: Change user name
- url: 'http://hmgsos.aguiabranca.com.br/ASKRest/v1/participantes/793/pesquisar/' + req.body.cpf,
- method: 'GET',
- headers: headers,
- }
- request(participanteOptions, function (error, response, body) {
- if(JSON.parse(body).length > 0){
- var papeis = {
- 'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }',
- "COP": [JSON.parse(body)[0].Id]
- };
- } else {
- var papeis = {
- 'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }'
- };
- }
- var options = {
- url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/abrir',
- method: 'POST',
- headers: headers,
- body: JSON.stringify({
- 'Formulario': 73,
- 'Conjuntos': {
- 'DadosBasicos': {
- 'Assunto': 'Atendimento Gabi',
- 'Descricao': 'O cliente deseja obter ajuda para ' + req.body.tipoChamado,
- 'DescricaoOrigem': 'Chatbot',
- 'Atividade': req.body.atividade
- },
- 'Papeis': papeis
- }
- })
- }
- request(options, function (error, response, body) {
- res.send(body);
- });
- });
- } else {
- var options = {
- url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/abrir',
- method: 'POST',
- headers: headers,
- body: JSON.stringify({
- 'Formulario': 73,
- 'Conjuntos': {
- 'DadosBasicos': {
- 'Assunto': 'Atendimento Gabi',
- 'Descricao': 'O cliente deseja obter ajuda para ' + req.body.tipoChamado,
- 'DescricaoOrigem': 'Chatbot',
- 'Atividade': req.body.atividade
- },
- 'Papeis': {
- 'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }'
- }
- }
- })
- }
- request(options, function (error, response, body) {
- res.send(body);
- });
- }
- });
- app.post('/atualizar-chamado', function(req, res){
- var headers = {
- 'Authorization': 'Bearer gAAAACiGdw5NEUH4ir-qZFwJNs9Kc4B2H5d8JEsEVhPEtn4-xSUMDg735c313I8A1ZRAhqkLCigg73ZJL2ofgHhPU7L8bqtOHEYsGuV6IgCL4SQCGHLZEdbnG-tEBAg7NRzrqsZQhUjmugztEO0vKeHci7aOMA8lxAA51Q60gMnKRl3VFAEAAIAAAABOm_ptCKu1pBdhIPWKOEZW750p2leNSM4eCFv-I8l7J7p0uTOnVk0Ifhezl8V1btLYUHnpHwD0m0K1OmSGXIk41Sx1dfaJL0tQDYu4mDFiJU-_Nrw-tbAj6P28Da09eUS2LUrfwnETX5KWOyJECWhXHCFk0liR9wcPVVNwtXyxfm7pfSfTwGo2qb9B1dt1CEM6zdy93c66-XLXFN89Uoub88Va9uErhkwYTeWwkZMgp5WJm6Kw5x6ara053usmmTtXQyLsOC3OYOUR2Jzs1EEnG3539IkTJhdYp4EFv69VZZeChJ79hBn4rMl1t-kBA3CT_cev52Fz3ZmtpkhRENfvy19lUC50n6O9Ow6jMTcYKQ',
- 'Content-Type': 'application/json'
- }
- var options = {
- url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/' + req.body.chamadoID + '/acoes',
- method: 'POST',
- headers: headers,
- body: JSON.stringify({
- 'Id': 'Restringir Acompanhamento [ACO]',
- 'Descricao': req.body.log
- })
- }
- request(options, function (error, response, body) {
- res.send(body);
- });
- });
- app.post('/fechar-chamado', function(req, res){
- var headers = {
- 'Authorization': 'Bearer gAAAACiGdw5NEUH4ir-qZFwJNs9Kc4B2H5d8JEsEVhPEtn4-xSUMDg735c313I8A1ZRAhqkLCigg73ZJL2ofgHhPU7L8bqtOHEYsGuV6IgCL4SQCGHLZEdbnG-tEBAg7NRzrqsZQhUjmugztEO0vKeHci7aOMA8lxAA51Q60gMnKRl3VFAEAAIAAAABOm_ptCKu1pBdhIPWKOEZW750p2leNSM4eCFv-I8l7J7p0uTOnVk0Ifhezl8V1btLYUHnpHwD0m0K1OmSGXIk41Sx1dfaJL0tQDYu4mDFiJU-_Nrw-tbAj6P28Da09eUS2LUrfwnETX5KWOyJECWhXHCFk0liR9wcPVVNwtXyxfm7pfSfTwGo2qb9B1dt1CEM6zdy93c66-XLXFN89Uoub88Va9uErhkwYTeWwkZMgp5WJm6Kw5x6ara053usmmTtXQyLsOC3OYOUR2Jzs1EEnG3539IkTJhdYp4EFv69VZZeChJ79hBn4rMl1t-kBA3CT_cev52Fz3ZmtpkhRENfvy19lUC50n6O9Ow6jMTcYKQ',
- 'Content-Type': 'application/json'
- }
- var options = {
- url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/' + req.body.chamadoID + '/acoes',
- method: 'POST',
- headers: headers,
- body: JSON.stringify({
- 'Id': 'Concluir Requisição [CONC]',
- 'Descricao': req.body.log
- })
- }
- request(options, function (error, response, body) {
- res.send(body);
- });
- });
- app.post('/ps', function(req, res) {
- const shell = require('node-powershell');
- if(req.body.name && req.body.cpf){
- let ps = new shell({
- executionPolicy: 'Bypass',
- noProfile: true
- });
- ps.addCommand('exec/ExecResetAD.ps1 ' + req.body.name + ' ' + req.body.cpf)
- ps.invoke()
- .then(output => {
- res.json({content: "True"});
- })
- .catch(err => {
- res.json({error: 'Something wrong happened'});
- ps.dispose();
- });
- } else {
- res.json({error: "Parameter 'name' and/or 'cpf' not found."});
- }
- });
- app.post('/sh', function(req, res) {
- var child_process = require('child_process');
- if(req.body.name){
- var bat = require.resolve('./exec/execSisdia.bat');
- var ls = child_process.spawn(bat, [ req.body.name ]);
- ls.on('exit', function (code) {
- console.log('child process exited with code ' + code);
- if(code == 1){
- res.json({error: "User not found"});
- } else {
- res.json({content: 'True'});
- }
- });
- } else {
- res.json({error: "Parameter 'name' not found."});
- }
- });
- /**
- * Updates the response text using the intent confidence
- * @param {Object} input The request to the Conversation service
- * @param {Object} response The response from the Conversation service
- * @return {Object} The response with the updated message
- */
- function updateMessage(input, response) {
- var responseText = null;
- if (!response.output) {
- response.output = {};
- } else {
- return response;
- }
- if (response.intents && response.intents[0]) {
- var intent = response.intents[0];
- // Depending on the confidence of the response the app can return different messages.
- // The confidence will vary depending on how well the system is trained. The service will always try to assign
- // a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
- // user's intent . In these cases it is usually best to return a disambiguation message
- // ('I did not understand your intent, please rephrase your question', etc..)
- if (intent.confidence >= 0.75) {
- responseText = 'I understood your intent was ' + intent.intent;
- } else if (intent.confidence >= 0.5) {
- responseText = 'I think your intent was ' + intent.intent;
- } else {
- responseText = 'I did not understand your intent';
- }
- }
- response.output.text = responseText;
- return response;
- }
- module.exports = app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement