-
-
Save bchhun/cce2c8b7c683c70f242c7703ddda0f13 to your computer and use it in GitHub Desktop.
DialogFlow webhook talking to remote API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require("express"); | |
var bodyParser = require("body-parser"); | |
const querystring = require('querystring'); | |
var path = require("path"); | |
const https = require('http'); | |
var session = require('express-session'); | |
var FileStore = require('session-file-store')(session); | |
var parseurl = require('parseurl'); | |
var fs = require("fs"); | |
var app = express(); | |
let sess=''; | |
//inizializzo la sessione | |
app.use(session({ | |
store: new FileStore(), | |
secret: 'keyboard cat', | |
resave: false, | |
saveUninitialized: true, | |
cookie: {secure: false, maxAge: 180000,name:'JSESSIONID'} | |
})); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(bodyParser.json()); | |
app.use(express.static(__dirname)); | |
app.use(function (req, res, next) { | |
if (!req.session.views) { | |
req.session.views = {} | |
} | |
// get the url pathname | |
var pathname = parseurl(req).pathname; | |
// count the views | |
req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; | |
req.session.pippo='pippo'; | |
req.session.mysession=''; | |
sess=req.session.id; | |
req.session.myid=sess; | |
next(); | |
}) | |
/* IP address remote web service */ | |
const options = { | |
hostname: '86.XXX.XX.XX', | |
port: 8080, | |
path: '/AVA/rest/searchService/search_2?searchText=', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Cookie':'' // -> I HAVE TO GET THIS VALUE THE FIRST TIME I QUERY THE WEB SERVICE, STORE IT TO SEND IT BACK TO WEB SERVICE UNTIL THE CONVERSATION GOES ON | |
} | |
}; | |
//THIS IS THE WEBHOOK END-POINT | |
app.post("/callAVA", function (req,res){ | |
let strRicerca=''; | |
let out=''; | |
var str= req.body.queryResult.parameters.searchText; | |
// === here's the fix I did !!! the v2 version is a long string separated by /; the sessionId is there at the end === | |
let sessionId = req.body.session.split('/').pop(); | |
if (str) { | |
strRicerca=querystring.escape(str); | |
options.path+=strRicerca+'&user=&pwd=&ava=FarmaInfoBot'; | |
// I INVOKE THE CALLAVA FUNCTION SENDING THE PARAMETERS FROM DG AGENT + ACTUAL SESSION ID GOTTEN FROM EXPRESS | |
// IT DOESN'T WORK!! | |
// the other fix ! take a look at the second parameter. | |
callAVA( strRicerca, sessionId).then((strOutput)=> { | |
return res.json({ 'fulfillmentText': strOutput}); | |
}).catch((error) => { | |
return res.json({ 'fulfillmentText': 'errore: ' + error.message}); | |
}); | |
} | |
}); | |
/**** UTILITY FUNCTIONS TO STORE SESSION */ | |
function writeSession(path, strSessione, strValore) { | |
fs.appendFile(path + strSessione,strValore, function (err) { | |
if (err) { | |
throw err; | |
} else { | |
console.log('SAVED FILE '+ path + strSessione); | |
} | |
}); | |
} | |
function readSession(path, strSessione){ | |
var contents=''; | |
try { | |
fs.accessSync(__dirname+ '/sessions/'+ strSessione); | |
contents = fs.readFileSync(__dirname+'/sessions/'+ strSessione, 'utf8'); | |
console.log('READ SESSION ' +contents); | |
}catch (err) { | |
if (err.code==='ENOENT') | |
console.log('INSIDE READ SESSION :file not exists...'); | |
} | |
return contents; | |
} | |
function callAVA(stringaRicerca, sess) { | |
return new Promise((resolve, reject) => { | |
let data = ''; | |
let strOutput=''; | |
var ss=readSession(__dirname +'/sessions/', sess); //GET THE ACTUAL SESSIONID FROM FILE + COOKIE GOTTEN FROM API | |
if (ss===''){ | |
options.headers.Cookie='JSESSIONID='; | |
console.log('INSIDE CALL AVA: SESSION EMPTY'); | |
}else { //THIS IS THE FIRST TIME I QUERY THE WEB SERVICE SO IT'S OK IT'S EMPTY | |
options.headers.Cookie='JSESSIONID='+ss; | |
console.log('INSIDE CALL AVA: SESSION '+ JSESSIONID); | |
} | |
//DO THE REQUEST TO WEB SERVICE | |
const req = https.request(options, (res) => { | |
//logs | |
console.log('options.cookie AT START ' + options.headers.Cookie); | |
console.log(`STATUS from response: ${res.statusCode}`); | |
console.log(`HEADERS from response: ${JSON.stringify(res.headers)}`); | |
console.log('..............RES HEADER ' + res.headers["set-cookie"] ); | |
if (res.headers["set-cookie"]){ | |
var x = res.headers["set-cookie"].toString(); | |
var arr=x.split(';') | |
var y=arr[0].split('='); | |
writeSession(__dirname+'/sessions/',sess, y[1]); // OK I GOT THE COOKIE FROM WEB SERVICE AND STORE IT | |
} | |
//GETTING THE DATA FROM WEB SERVICE | |
res.setEncoding('utf8'); | |
res.on('data', (chunk) => { | |
console.log(`BODY: ${chunk}`); | |
data += chunk; | |
let c=JSON.parse(data); | |
strOutput=c.output[0].output; | |
//CLEAN HTML TAG | |
strOutput=strOutput.replace(/(<\/p>|<p>|<b>|<\/b>|<br>|<\/br>|<strong>|<\/strong>|<div>|<\/div>|<ul>|<li>|<\/ul>|<\/li>| |)/gi, ''); | |
resolve(strOutput); // THIS IS THE TEXT OUTPUT I NEED TO GET BACK TO THE DG AGENT | |
}); | |
res.on('end', () => { | |
console.log('No more data in response.'); | |
options.path='/AVA/rest/searchService/search_2?searchText='; | |
}); | |
}); | |
req.on('error', (e) => { | |
console.error(`problem with request: ${e.message}`); | |
strOutput=" error " + e.message; | |
}); | |
// write data to request body | |
req.write(postData); | |
req.end(); | |
}); | |
} | |
app.listen(process.env.PORT || 3000, function() { | |
console.log("App started on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment