-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
496 lines (388 loc) · 15.1 KB
/
app.js
File metadata and controls
496 lines (388 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//02/01/2019 conversation close con actions on google
//18/12/2018
//INIZIO ANALISI STOP CONVERSAZIONE DA PLQ, vedi anche file post.js
//02/12/2018 BUG: caratteri accentati incorretti causa errata codifica
//installato modulo utf8
//12/11/2018: aggiornato con gestione HTTPS
//https://panloquacity2dialogflow.herokuapp.com/callAVA?ava=FarmaInfoBot
var express = require("express");
var bodyParser = require("body-parser");
const querystring = require('querystring');
var path = require("path");
const https = require('https'); // da http: a https: modifica del 12/11/2018...
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var parseurl = require('parseurl');
var fs = require("fs");
var utf8=require('utf8');
var {WebhookClient} = require('dialogflow-fulfillment');
var app = express();
let sess='';
var bot='';
/*const WELCOME_INTENT = 'input.welcome';
const AVA_INTENT = 'SendToPanloquacity'; //MandaFuori*/
//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();
})
/*funzioni per gestire DG agente */
/*function CloseConversation (agent) {
agent.add(`qui chiudo la conversazione `);
console.log('qui chiudo la conversazione');
}*/
function welcome (agent) {
agent.add(`Welcome to Express.JS webhook! `);
console.log('sono nel welcome');
}
function fallback (agent) {
agent.add(`I didn't understand from server`);
agent.add(`I'm sorry, can you try again?`);
}
/*http://86.107.98.69:8080/AVA/avatar.jsp?ava=AlpiGiulieDemo
http://86.107.98.69:8080/AVA/avatar.jsp?ava=FarmaInfoBot
http://86.107.98.69:8080/AVA/avatar.jsp?ava=Olivia
*/
function WebhookProcessing(req, res) {
const agent = new WebhookClient({request: req, response: res});
//02/01/2019
//agent.requestSource = agent.ACTIONS_ON_GOOGLE;
console.log('------ ----- la richiesta proviene da '+ agent.requestSource);
//******************************************* */
//recupero la sessionId della conversazione
agent.sessionId=req.body.session.split('/').pop();
//assegno all'agente il parametro di ricerca da invare sotto forma di searchText a Panloquacity
agent.parameters['searchText']=req.body.queryResult.parameters.searchText;
console.info(`agent set ` + agent.sessionId +` parameters ` + agent.parameters.searchText);
//recupero quale agente viene interrogato
bot=req.query.ava;
console.log('Il bot interrogato : '+bot);
let intentMap = new Map();
//modifica del 29/10/2018 commentato i due intent su richiesta R.
//intentMap.set('Default Welcome Intent', welcome);
//intentMap.set('Default Fallback Intent', fallback);
intentMap.set('Welcome', callAVA); //la funzione callAva sostiutisce la funzione welcome
intentMap.set('AnyText', callAVA); // AnyText sostituisce 'qualunquetesto'
intentMap.set('Stop', callAVA); //modifica del 22/11/2018 per gestire la fine della conversazione
//intentMap.set('CloseConversation', callAVA);
agent.handleRequest(intentMap);
}
app.get('/', function(req, res, next) {
if (req.session.views) {
req.session.views++;
res.setHeader('Content-Type', 'text/html')
res.write("sono nella root ");
res.write('<p>views: ' + req.session.views + '</p>')
res.write('<p> id sessione ' + req.session.id +' expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh!')
}
})
app.get('/foo', function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/foo'] + ' times')
})
app.get('/bar', function (req, res, next) {
//if (req.session.pippo)
console.log('Cookies: ' + req.session.cookie.name);
res.send('you viewed this page ' + req.session.views['/bar'] + ' times e ti chiami '+req.session.id);
})
app.get('/writefs', function (req, res, next) {
sess=req.session.id;
/*fs.appendFile('sessions/'+ sess,'0HV+3S+MjoJyXvaYA0PUFySz.undefined', function (err) {
if (err) throw err;
console.log('Saved!');
res.send("salvato file di nome " + sess);
});*/
scriviSessione('sessions/',sess, '0HV+3S+MjoJyXvaYA0PUFySz.undefined');
res.send("salvato file di nome " + sess);
//if (risultato) console.log('ok');
})
app.get('/readfs', function (req, res, next) {
if (sess){
var c=leggiSessione('sessions/', sess);
res.send("letto "+c);
}else{
console.log('manca la sessione');
}
});
//routing e api
// route handler for GET requests
///random/10/100, ma anche /random/foo/bar, quindi verifica che siano numeri...
//app.get("/random/:min/:max", function(req, res) {
/* PER FARE POST SU AVA*/
postData = querystring.stringify({
'searchText': 'ciao',
'user':'',
'pwd':'',
'ava':'FarmaInfoBot'
});
const options = {
//modifica del 12/11/2018 : cambiato porta per supportare HTTPS
hostname: '86.107.98.69',
/*port: 8080,*/
port: 8443,
rejectUnauthorized: false, // aggiunto qui 12/11/2018
path: '/AVA/rest/searchService/search_2?searchText=',
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'Content-Length': Buffer.byteLength(postData),
'Cookie':'' // +avaSession
}
};
app.get("/random/:min/:max", function(req, res) {
var min = parseInt(req.params.min);
var max = parseInt(req.params.max);
/*var min=parseInt(req.query.min);
var max=parseInt(req.query.max);*/
if (isNaN(min) || isNaN(max)) {
res.status(400);
res.json({ error: "Bad request." });
return;
}
var result = Math.round((Math.random() * (max - min)) + min);
res.json({ result: result });
});
//random/1/10
//app.post("/random/:min/:max", function(req, res) {
app.post("/random/", function(req, res) {
//devo adattare il codice per dialogflow
console.log(JSON.stringify(req.body));
/*var min = parseInt(req.params.min);
var max = parseInt(req.params.max);*/
//prova mia:
//querystring funziona, a condizione che da postman vada messo &min=1&max=12
/* UN ATTIMO LO COMMENTO
var min=parseInt(req.query.min);
var max=parseInt(req.query.max);
*/
//da form da postman non funziona
// var min=parseInt(req.body.min); req.body.result.parameters.
// var max=parseInt(req.body.max);
/* adattare il codice per DG!!!!!*/
var min=parseInt(req.body.queryResult.parameters.min);
var max=parseInt(req.body.queryResult.parameters.max);
if (isNaN(min) || isNaN(max)) {
res.status(400);
res.json({ error: "Bad request." });
return;
}
var result = Math.round((Math.random() * (max - min)) + min);
//preparo la risposta per DG
res.setHeader('Content-Type', 'application/json');
// res.json({ result: result });
res.json({
fulfillmentText: "il numero e' " + result,
payload: null
})
});
//funzione callAVA
app.post("/callAVA", function (req,res){
//console.log('Dialogflow Request headers: ' + JSON.stringify(req.headers));
//console.log('DIALOGFLOW Request body: ' + JSON.stringify(req.body));
//
WebhookProcessing(req, res); //usa handleAgent
/*****************OLD ************** */
/*console.log(`\n\n>>>>>>> S E R V E R H I T <<<<<<<`);
//console.log('Dialogflow Request headers: ' + JSON.stringify(req.headers));
console.log('DIALOGFLOW Request body: ' + JSON.stringify(req.body));
//projects/testcallava/agent/sessions/dac5d6c5-c63f-b62d-7472-3f7673dc00e9
let sessionId = req.body.session.split('/').pop();
console.log('valore di sessionID DG '+sessionId);
let strRicerca='';
let out='';
var str= req.body.queryResult.parameters.searchText; //req.body.queryResult.parameters.searchText; //req.body.searchText;
if (str) {
strRicerca=querystring.escape(str);
options.path+=strRicerca+'&user=&pwd=&ava=FarmaInfoBot';
callAVA( strRicerca, sessionId).then((strOutput)=> {
return res.json({ 'fulfillmentText': strOutput});
}).catch((error) => {
return res.json({ 'fulfillmentText': 'errore: ' + error.message});
});
}
*/
});
/**** FUNZIONI A SUPPORTO */
function scriviSessione(path, strSessione, strValore) {
fs.appendFile(path + strSessione,strValore, function (err) {
if (err) {
throw err;
} else {
console.log('DENTRO SCRIVI SESSIONE: SALVATO FILE '+ path + strSessione);
}
});
}
function leggiSessione(path, strSessione){
var contents='';
try {
fs.accessSync(__dirname+ '/sessions/'+ strSessione);
contents = fs.readFileSync(__dirname+'/sessions/'+ strSessione, 'utf8');
console.log('DENTRO LEGGI SESSIIONE ' +contents);
}catch (err) {
if (err.code==='ENOENT')
console.log('DENTRO LEGGI SESSIONE :il file non esiste...')
}
return contents;
}
// 18/12/2018
function getComandi(arComandi)
{
var comandi=arComandi;
if (comandi.length>0){
//prosegui con il parsing
//caso 1: ho solo un comando, ad esempio lo stop->prosegui con il parsing
switch (comandi.length){
case 1:
comandi=arComandi;
break;
case 2:
//caso 2: ho due comandi, stop e img=path image, quindi devo scomporre comandi[1]
var temp=arComandi[1].toString();
//temp=img=https.....
//splitto temp in un array con due elementi divisi da uguale
temp=temp.split("=");
console.log('valore di temp[1]= ' +temp[1]);
arComandi[1]=temp[1];
comandi=arComandi;
//scompongo arComandi[1]
break;
default:
//
console.log('sono in default');
}
return comandi; //ritorno array come mi serve STOP oppure STOP, PATH img
} else {
console.log('non ci sono comandi')
//non ci sono comandi quindi non fare nulla
return undefined;
}
}
// OLD SIGNATURE
//function callAVA(stringaRicerca, sess) {
//NEW SIGNATURE + AGENT
function callAVA(agent) {
return new Promise((resolve, reject) => {
let strRicerca='';
let out='';
let sessionId = agent.sessionId /*.split('/').pop()*/;
console.log('dentro call ava il mio session id '+sessionId);
//modifica del 02/12/2018 per bug utf8
// faccio encoding in utf8-> utf8.encode()
var str= utf8.encode(agent.parameters.searchText); //req.body.queryResult.parameters.searchText; //req.body.searchText;
if (str) {
strRicerca=querystring.escape(str); //02/12/2018: questo rimane, escape della stringa ci vuole cmq!
options.path+=strRicerca+'&user=&pwd=&ava='+bot;
}
let data = '';
let strOutput='';
//var ss=leggiSessione(__dirname +'/sessions/', sess);
var ss=leggiSessione(__dirname +'/sessions/', sessionId);
if (ss===''){
options.headers.Cookie='JSESSIONID=';
console.log('DENTRO CALL AVA: SESSIONE VUOTA');
}else {
options.headers.Cookie='JSESSIONID='+ss;
console.log('DENTRO CALL AVA: HO LA SESSIONE + JSESSIONID');
}
const req = https.request(options, (res) => {
//console.log("DENTRO CALL AVA " + sess);
console.log('________valore di options.cookie INIZIO ' + options.headers.Cookie);
console.log(`STATUS DELLA RISPOSTA: ${res.statusCode}`);
console.log(`HEADERS DELLA RISPOSTA: ${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('=');
// scriviSessione(__dirname+'/sessions/',sess, y[1]);
scriviSessione(__dirname+'/sessions/',sessionId, y[1]);
}
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
data += chunk;
let c=JSON.parse(data);
strOutput=c.output[0].output;
strOutput=strOutput.replace(/(<\/p>|<p>|<b>|<\/b>|<br>|<\/br>|<strong>|<\/strong>|<div>|<\/div>|<ul>|<li>|<\/ul>|<\/li>| |)/gi, '');
//resolve(strOutput); <--- OLD
//18/12/2018 02/01/2019
let comandi=[];
comandi=getComandi(c.output[0].commands);
if (typeof comandi!=='undefined' && comandi.length>=1) {
console.log('ho almeno un comando, quindi prosegui con l\' azione ' + comandi[0]);
if (comandi[0]=="STOP"){
console.log('++++++++++++ stoppo la conversazione')
//03/01/2019
//verifico che posso gestire la chiusura della conversazone
if (agent.requestSource=="ACTIONS_ON_GOOGLE"){
//agent.requestSource = agent.ACTIONS_ON_GOOGLE
let conv = agent.conv();
console.log(' ---- la conversazione PRIMA ----- ' + JSON.stringify(conv));
conv.close(strOutput);
console.log(' ---- la conversazione DOPO CHIUSURA ----- ' + JSON.stringify(conv));
agent.add(conv);
//altrimenti ritorna la strOutput
}else{
agent.add(strOutput);
}
} else { //07/01/2019
console.log('+++++++++ ho solo link immagine')
//02/01/2019
agent.add(strOutput); //ritorno il link immagine
}
if (typeof comandi[1] !== 'undefined' && comandi[0]=="STOP"){
console.log('+++++++++ stoppo la conversazione e mando link immagine')
//02/01/2019
agent.add(strOutput); //NEW
}
} else {
//02/01/2019
agent.add(strOutput); //NEW
console.log('non ci sono comandi, prosegui');
}
/**********fino qua gestione comandi 18/12/2018 */
//agent.add(strOutput); //NEW
resolve(agent);
});
res.on('end', () => {
console.log('No more data in response.');
options.path='/AVA/rest/searchService/search_2?searchText=';
console.log('valore di options.path FINE ' + options.path);
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
strOutput="si è verificato errore " + e.message;
});
// write data to request body
req.write(postData);
req.end();
});
}
/*****FINE CALL AVA */
app.listen(process.env.PORT || 3000, function() {
console.log("App started on port 3000");
});