Advertisement
Guest User

JS

a guest
Sep 15th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Copyright 2015 IBM Corp. All Rights Reserved.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *      http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16.  
  17. 'use strict';
  18.  
  19. var express = require('express'); // app server
  20. var bodyParser = require('body-parser'); // parser for post requests
  21. var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
  22. var fs = require('fs');
  23. var http = require('http');
  24. var https = require('https');
  25. var privateKey  = fs.readFileSync('./gabi.aguiabranca.com.br-key.pem', 'utf8');
  26. var certificate = fs.readFileSync('./gabi.aguiabranca.com.br-crt.pem', 'utf8');
  27. var credentials = {key: privateKey, cert: certificate};
  28. var cors = require('cors')
  29. var request = require('request');
  30. var helmet = require('helmet')
  31.  
  32. var app = express();
  33.  
  34.  
  35. // Bootstrap application settings
  36. app.use(helmet({
  37.   frameguard: false
  38. }));
  39. app.use(express.static('./public')); // load UI from public folder
  40. app.use(bodyParser.json());
  41. app.use(bodyParser.urlencoded({ extended: true }));
  42. app.use(cors());
  43. app.use(function (req, res, next) {
  44.     res.setHeader('Access-Control-Allow-Origin', '*');
  45.     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  46.     res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  47.     next();
  48. });
  49.  
  50. var httpServer = http.createServer(app);
  51. var httpsServer = https.createServer(credentials, app);
  52.  
  53. httpServer.listen(8080);
  54. httpsServer.listen(443);
  55. // Create the service wrapper
  56. var conversation = new Conversation({
  57.     // If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
  58.     // After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
  59.     // username: '<username>',
  60.     // password: '<password>',
  61.     // url: 'https://gateway.watsonplatform.net/conversation/api',
  62.     version_date: Conversation.VERSION_DATE_2017_04_21
  63. });
  64.  
  65. // Endpoint to be call from the client side
  66. app.post('/api/message', function(req, res) {
  67.     var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
  68.     if (!workspace || workspace === '<workspace-id>') {
  69.         return res.json({
  70.             'output': {
  71.                 '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.'
  72.             }
  73.         });
  74.     }
  75.     var payload = {
  76.         workspace_id: workspace,
  77.         context: req.body.context || {},
  78.         input: req.body.input || {}
  79.     };
  80.  
  81.     // Send the input to the conversation service
  82.     conversation.message(payload, function(err, data) {
  83.         if (err) {
  84.             return res.status(err.code || 500).json(err);
  85.         }
  86.         return res.header("Access-Control-Allow-Origin", "*")
  87.             .header("Access-Control-Allow-Headers", "X-Requested-With")
  88.             .json(updateMessage(payload, data));
  89.     });
  90. });
  91.  
  92. app.post('/abrir-chamado', function(req, res){
  93.    
  94.     var headers = {
  95.         'Authorization': 'Bearer gAAAAKbpfV-oyV63J_b32vUyjaMVN7sEABdqCgwBQEnYuKsQGHJVPLpbEemCKe0I-g75mo_GHcHJRX1pPCXxIN9gQpVOvoQW6k0zz2hXrYMBIV6pQjfI39RXh2fipL8vWzUiBM1x7CHXohKN9c9DTBx-T5gIvcEFgLolQ5sZE8uErnfCFAEAAIAAAAB8H7R0KEbI7SGk5VOX0idDKDZdzfJ4uAvSZJJHF2SrGGilbaMlOihfX4H7dzR_0JV1PiAqDYMaqa7PuTBI9el251_A6NDzTNJumKYbxMjsZVo6i3nTcOGKap8UQmPHRks9R2a1tqiytQaxd1qvFdUhXgSa-xsBKiYZKZfT6N_teyjkxg2a6etlOAvy0IPGH8K2PYh-aXVTL3GCG6KfNcNIQYwGDuWM3wM7zIhsOSrQj8F3sEZxNxh6HhiKeTB0NjeM42NvY5otlsRyrClabtHP6hweUS1vl2ZVhbJSG9TcJRiIOPHjYAgEL3bmMP4s2JQEPQT0qBMzVMbe6NqIJZWSPaIuoAkAyTtXTe9WxnRTkg',
  96.         'Content-Type': 'application/json'
  97.     }
  98.        
  99.     if (req.body.cpf){
  100.         var participanteOptions = {
  101.             //TODO: Change user name
  102.             url: 'http://hmgsos.aguiabranca.com.br/ASKRest/v1/participantes/793/pesquisar/' + req.body.cpf,
  103.             method: 'GET',
  104.             headers: headers,
  105.         }
  106.         request(participanteOptions, function (error, response, body) {
  107.             if(JSON.parse(body).length > 0){
  108.                 var papeis = {
  109.                     'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }',
  110.                     "COP": [JSON.parse(body)[0].Id]
  111.                 };
  112.             } else {
  113.                 var papeis = {
  114.                     'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }'
  115.                 };
  116.             }
  117.             var options = {
  118.                 url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/abrir',
  119.                 method: 'POST',
  120.                 headers: headers,
  121.                 body: JSON.stringify({
  122.                     'Formulario': 73,
  123.                     'Conjuntos': {
  124.                         'DadosBasicos': {
  125.                             'Assunto': 'Atendimento Gabi',
  126.                             'Descricao': 'O cliente deseja obter ajuda para ' + req.body.tipoChamado,
  127.                             'DescricaoOrigem': 'Chatbot',
  128.                             'Atividade': req.body.atividade
  129.                         },
  130.                         'Papeis': papeis
  131.                     }
  132.                 })
  133.             }  
  134.             request(options, function (error, response, body) {
  135.                 res.send(body);
  136.             });
  137.         });
  138.     } else {
  139.         var options = {
  140.             url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/abrir',
  141.             method: 'POST',
  142.             headers: headers,
  143.             body: JSON.stringify({
  144.                 'Formulario': 73,
  145.                 'Conjuntos': {
  146.                     'DadosBasicos': {
  147.                         'Assunto': 'Atendimento Gabi',
  148.                         'Descricao': 'O cliente deseja obter ajuda para ' + req.body.tipoChamado,
  149.                         'DescricaoOrigem': 'Chatbot',
  150.                         'Atividade': req.body.atividade
  151.                     },
  152.                     'Papeis': {
  153.                         'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }'
  154.                     }
  155.                 }
  156.             })
  157.         }  
  158.         request(options, function (error, response, body) {
  159.             res.send(body);
  160.         });
  161.     }
  162. });
  163.  
  164. app.post('/atualizar-chamado', function(req, res){
  165.    
  166.     var headers = {
  167.         'Authorization': 'Bearer gAAAAKbpfV-oyV63J_b32vUyjaMVN7sEABdqCgwBQEnYuKsQGHJVPLpbEemCKe0I-g75mo_GHcHJRX1pPCXxIN9gQpVOvoQW6k0zz2hXrYMBIV6pQjfI39RXh2fipL8vWzUiBM1x7CHXohKN9c9DTBx-T5gIvcEFgLolQ5sZE8uErnfCFAEAAIAAAAB8H7R0KEbI7SGk5VOX0idDKDZdzfJ4uAvSZJJHF2SrGGilbaMlOihfX4H7dzR_0JV1PiAqDYMaqa7PuTBI9el251_A6NDzTNJumKYbxMjsZVo6i3nTcOGKap8UQmPHRks9R2a1tqiytQaxd1qvFdUhXgSa-xsBKiYZKZfT6N_teyjkxg2a6etlOAvy0IPGH8K2PYh-aXVTL3GCG6KfNcNIQYwGDuWM3wM7zIhsOSrQj8F3sEZxNxh6HhiKeTB0NjeM42NvY5otlsRyrClabtHP6hweUS1vl2ZVhbJSG9TcJRiIOPHjYAgEL3bmMP4s2JQEPQT0qBMzVMbe6NqIJZWSPaIuoAkAyTtXTe9WxnRTkg',
  168.         'Content-Type': 'application/json'
  169.     }
  170.     var options = {
  171.         url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/' + req.body.chamadoID  + '/acoes',
  172.         method: 'POST',
  173.         headers: headers,
  174.         body: JSON.stringify({
  175.                             'Id': 'Restringir Acompanhamento [ACO]',
  176.                             'Descricao': req.body.log
  177.                         })
  178.     }
  179.     request(options, function (error, response, body) {
  180.         res.send(body);
  181.     });
  182. });
  183.  
  184. app.post('/fechar-chamado', function(req, res){
  185.    
  186.     var headers = {
  187.         'Authorization': 'Bearer gAAAAKbpfV-oyV63J_b32vUyjaMVN7sEABdqCgwBQEnYuKsQGHJVPLpbEemCKe0I-g75mo_GHcHJRX1pPCXxIN9gQpVOvoQW6k0zz2hXrYMBIV6pQjfI39RXh2fipL8vWzUiBM1x7CHXohKN9c9DTBx-T5gIvcEFgLolQ5sZE8uErnfCFAEAAIAAAAB8H7R0KEbI7SGk5VOX0idDKDZdzfJ4uAvSZJJHF2SrGGilbaMlOihfX4H7dzR_0JV1PiAqDYMaqa7PuTBI9el251_A6NDzTNJumKYbxMjsZVo6i3nTcOGKap8UQmPHRks9R2a1tqiytQaxd1qvFdUhXgSa-xsBKiYZKZfT6N_teyjkxg2a6etlOAvy0IPGH8K2PYh-aXVTL3GCG6KfNcNIQYwGDuWM3wM7zIhsOSrQj8F3sEZxNxh6HhiKeTB0NjeM42NvY5otlsRyrClabtHP6hweUS1vl2ZVhbJSG9TcJRiIOPHjYAgEL3bmMP4s2JQEPQT0qBMzVMbe6NqIJZWSPaIuoAkAyTtXTe9WxnRTkg',
  188.         'Content-Type': 'application/json'
  189.     }
  190.     var options = {
  191.         url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/' + req.body.chamadoID + '/acoes',
  192.         method: 'POST',
  193.         headers: headers,
  194.         body: JSON.stringify({
  195.                             'Id': 'Concluir Requisição [CONC]',
  196.                             'Descricao': req.body.log
  197.                         })
  198.     }
  199.     request(options, function (error, response, body) {
  200.         res.send(body);
  201.     });
  202. });
  203.  
  204. app.post('/ps', function(req, res) {
  205.     const shell = require('node-powershell');
  206.  
  207.     if(req.body.name && req.body.cpf){
  208.         let ps = new shell({
  209.             executionPolicy: 'Bypass',
  210.             noProfile: true
  211.         });
  212.  
  213.         ps.addCommand('exec/ExecResetAD.ps1 ' + req.body.name + ' ' + req.body.cpf)
  214.         ps.invoke()
  215.             .then(output => {
  216.                 res.json({content: "True"});
  217.             })
  218.             .catch(err => {
  219.                 res.json({error: 'Something wrong happened'});
  220.                 ps.dispose();
  221.             });
  222.     } else {
  223.         res.json({error: "Parameter 'name' and/or 'cpf' not found."});
  224.     }
  225. });
  226.  
  227. app.post('/sh', function(req, res) {
  228.     var child_process = require('child_process');
  229.    
  230.     if(req.body.name){
  231.         var bat = require.resolve('./exec/execSisdia.bat');
  232.         var ls = child_process.spawn(bat, [ req.body.name ]);
  233.  
  234.         ls.on('exit', function (code) {
  235.             console.log('child process exited with code ' + code);
  236.             if(code == 1){
  237.                 res.json({error: "User not found"});
  238.             } else {
  239.                 res.json({content: 'True'});
  240.             }
  241.         });
  242.     } else {
  243.         res.json({error: "Parameter 'name' not found."});
  244.     }
  245. });
  246.  
  247. /**
  248.  * Updates the response text using the intent confidence
  249.  * @param  {Object} input The request to the Conversation service
  250.  * @param  {Object} response The response from the Conversation service
  251.  * @return {Object}          The response with the updated message
  252.  */
  253. function updateMessage(input, response) {
  254.     var responseText = null;
  255.     if (!response.output) {
  256.         response.output = {};
  257.     } else {
  258.         return response;
  259.     }
  260.     if (response.intents && response.intents[0]) {
  261.         var intent = response.intents[0];
  262.         // Depending on the confidence of the response the app can return different messages.
  263.         // The confidence will vary depending on how well the system is trained. The service will always try to assign
  264.         // a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
  265.         // user's intent . In these cases it is usually best to return a disambiguation message
  266.         // ('I did not understand your intent, please rephrase your question', etc..)
  267.         if (intent.confidence >= 0.75) {
  268.             responseText = 'I understood your intent was ' + intent.intent;
  269.         } else if (intent.confidence >= 0.5) {
  270.             responseText = 'I think your intent was ' + intent.intent;
  271.         } else {
  272.             responseText = 'I did not understand your intent';
  273.         }
  274.     }
  275.     response.output.text = responseText;
  276.     return response;
  277. }
  278.  
  279. module.exports = app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement