Advertisement
Guest User

app.js

a guest
Aug 20th, 2017
112
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('./newkey.pem', 'utf8');
  26. var certificate = fs.readFileSync('./newcert.pem', 'utf8');
  27. var credentials = {key: privateKey, cert: certificate};
  28. var cors = require('cors')
  29.  
  30. var app = express();
  31.  
  32.  
  33. // Bootstrap application settings
  34. app.use(express.static('./public')); // load UI from public folder
  35. app.use(bodyParser.json());
  36. app.use(bodyParser.urlencoded({ extended: true }));
  37. app.use(cors());
  38. app.use(function (req, res, next) {
  39.     res.setHeader('Access-Control-Allow-Origin', '*');
  40.     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  41.     res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  42.     next();
  43. });
  44.  
  45. var httpServer = http.createServer(app);
  46. var httpsServer = https.createServer(credentials, app);
  47.  
  48. httpServer.listen(8080);
  49. httpsServer.listen(443);
  50. // Create the service wrapper
  51. var conversation = new Conversation({
  52.   // If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
  53.   // After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
  54.   // username: '<username>',
  55.   // password: '<password>',
  56.   // url: 'https://gateway.watsonplatform.net/conversation/api',
  57.   version_date: Conversation.VERSION_DATE_2017_04_21
  58. });
  59.  
  60. // Endpoint to be call from the client side
  61. app.post('/api/message', function(req, res) {
  62.   var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
  63.   if (!workspace || workspace === '<workspace-id>') {
  64.     return res.json({
  65.       'output': {
  66.         '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.'
  67.       }
  68.     });
  69.   }
  70.   var payload = {
  71.     workspace_id: workspace,
  72.     context: req.body.context || {},
  73.     input: req.body.input || {}
  74.   };
  75.  
  76.   // Send the input to the conversation service
  77.   conversation.message(payload, function(err, data) {
  78.     if (err) {
  79.       return res.status(err.code || 500).json(err);
  80.     }
  81.     return res.header("Access-Control-Allow-Origin", "*")
  82.             .header("Access-Control-Allow-Headers", "X-Requested-With")
  83.             .json(updateMessage(payload, data));
  84.   });
  85. });
  86.  
  87. app.post('/ps', function(req, res) {
  88.     const shell = require('node-powershell');
  89.  
  90.     if(req.body.name && req.body.cpf){
  91.         let ps = new shell({
  92.             executionPolicy: 'Bypass',
  93.             noProfile: true
  94.         });
  95.  
  96.         ps.addCommand('exec/helloworld.ps1 ' + req.body.name + ' ' + req.body.cpf)
  97.         ps.invoke()
  98.             .then(output => {
  99.                 res.send(output);
  100.             })
  101.             .catch(err => {
  102.                 res.send(err);
  103.                 ps.dispose();
  104.             });
  105.     } else {
  106.         res.send("Parameter 'name' and/or 'cpf' not found.");
  107.     }
  108. });
  109.  
  110. app.post('/sh', function(req, res) {
  111.     const shell = require('child_process');
  112.     if(req.body.name){
  113.         shell.exec('sh exec/helloworld.sh ' + req.body.name, {silent: true}, function(code, stdout, stderr) {
  114.             res.send(stdout);
  115.         });
  116.     } else {
  117.         res.send("Parameter 'name' not found.");
  118.     }
  119. });
  120.  
  121. /**
  122.  * Updates the response text using the intent confidence
  123.  * @param  {Object} input The request to the Conversation service
  124.  * @param  {Object} response The response from the Conversation service
  125.  * @return {Object}          The response with the updated message
  126.  */
  127. function updateMessage(input, response) {
  128.   var responseText = null;
  129.   if (!response.output) {
  130.     response.output = {};
  131.   } else {
  132.     return response;
  133.   }
  134.   if (response.intents && response.intents[0]) {
  135.     var intent = response.intents[0];
  136.     // Depending on the confidence of the response the app can return different messages.
  137.     // The confidence will vary depending on how well the system is trained. The service will always try to assign
  138.     // a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
  139.     // user's intent . In these cases it is usually best to return a disambiguation message
  140.     // ('I did not understand your intent, please rephrase your question', etc..)
  141.     if (intent.confidence >= 0.75) {
  142.       responseText = 'I understood your intent was ' + intent.intent;
  143.     } else if (intent.confidence >= 0.5) {
  144.       responseText = 'I think your intent was ' + intent.intent;
  145.     } else {
  146.       responseText = 'I did not understand your intent';
  147.     }
  148.   }
  149.   response.output.text = responseText;
  150.   return response;
  151. }
  152.  
  153. module.exports = app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement