-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
339 lines (274 loc) · 9.76 KB
/
app.js
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
var builder = require('botbuilder');
var restify = require('restify');
var connector = new builder.ChatConnector({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function(){
console.log('%s listening to %s ',server.name,server.url);
})
server.post('/api/messages',connector.listen());
var inMemoryStorage = new builder.MemoryBotStorage();
var helpOptions={
"ColorCode":{
Contact:"[email protected]"
},
"GreatSoft":{
Contact:"[email protected]"
},
"Emails":{
Contact:"[email protected]"
},
};
var bot = new builder.UniversalBot(connector, [
(session) => {
builder.Prompts.choice(session,
'Hi am here to help.Choose what is troubling you',
helpOptions,
{ listStyle: builder.ListStyle.button });
},
(session, result) => {
if (result.response) {
switch (result.response.entity) {
case 'GreatSoft':
session.beginDialog('greatsoftDialog');
break;
case 'Emails':
session.send(`Initializing chat with ${helpOptions[result.response.entity].Contact}`);
session.reset();
break;
case 'ColorCode':
session.beginDialog('colorcodeDialog',helpOptions[result.response.entity].Contact);
break;
default:
extractTags(result.response);
}
} else {
extractTags(result);
//session.send(`I am sorry but I didn't understand that. I need you to select one of the options below`);
}
},
(session, result) => {
if (result.resume) {
session.send('You identity was not verified and your password cannot be reset');
session.reset();
}
}
]);
const ChangePasswordOption = 'Change Password';
const ResetPasswordOption = 'Reset Password';
bot.dialog('greatsoftDialog', [
(session) => {
builder.Prompts.choice(session,
'What would you like to get help on',
[ChangePasswordOption, ResetPasswordOption],
{ listStyle: builder.ListStyle.button });
},
(session, result) => {
if (result.response) {
switch (result.response.entity) {
case ChangePasswordOption:
session.send('This functionality is not yet implemented! Try resetting your password.');
session.reset();
break;
case ResetPasswordOption:
session.beginDialog('resetPassword:/');
break;
}
} else {
session.send(`I am sorry but I didn't understand that. I need you to select one of the options below`);
}
},
(session, result) => {
if (result.resume) {
session.send('You identity was not verified and your password cannot be reset');
session.reset();
}
}
])
.triggerAction({
matches:/^GreatSoft$/i,
confirmPrompt:'This will interrupt your conversation,are you sure?'
});
bot.dialog('colorcodeDialog', [
function(session,args){
session.dialogData.senderrorto=args;
builder.Prompts.text(session,'Please enter the error code recieved or briefly describe your issue?');
},
function(session,results){
session.dialogData.error=results.response;
openOutlook(session.dialogData.senderrorto,session.dialogData.error);
var msg=`Thank you for reporting.Issue sent to ${session.dialogData.senderrorto} for action`;
session.endDialog(msg);
}
]);
bot.dialog('helpDialog', [
function(session,args){
session.dialogData.senderrorto=args;
builder.Prompts.text(session,'I am here to chat your way out of your technical issues');
session.reset();
}
])
.triggerAction({
matches:/^help$/i,
confirmPrompt:'This will interrupt your conversation,are you sure?'
});
bot.dialog('outlookRead', [
function(session){
builder.Prompts.attachment(session,'Attach outlook object');
},
function(session,results){
//read email object
var url=results.response[0].contentUrl;
var http = require('http');
var fs=require('fs');
//
var emailbody='';
http.get(url, function(res) {
var data = [];
res.on('data', function(chunk) {
data.push(chunk);
// var file = fs.createWriteStream("file.msg");
}).on('end', function() {
//at this point data is an array of Buffers
//so Buffer.concat() can make us a new Buffer
//of all of them together
var buffer = Buffer.concat(data);
emailbody=readBuffer(buffer);
//file.close();
//summarize email
summarization(emailbody.replace(/\r?\n|\r/g, " ").trim());
});
});
function summarization(trimmed_emailbody){
//summarization by algorithmia
var result='';
var Algorithmia=require('algorithmia');
Algorithmia.client("simkW3Zwdt2gz7anbSf62wu7KzS1")
//.algo("nlp/Summarizer/0.1.7")
.algo("SummarAI/Summarizer/0.1.3")
.pipe(trimmed_emailbody)
.then(function(response) {
//console.log('TRACK'+trimmed_emailbody);
var keywords=response.result.auto_gen_ranked_keywords;
//get sentiment
sentimentAnalysis(emailbody,keywords,response.result.summarized_data);
});
return result;
}
function sentimentAnalysis(emailbody,keywords,summary){
//sentiment analysis ALGORITHIMIA
var input = {
"document": emailbody
};
var result='';
var Algorithmia=require('algorithmia');
Algorithmia.client("simkW3Zwdt2gz7anbSf62wu7KzS1")
.algo("nlp/SentimentAnalysis/1.0.4")
.pipe(input)
.then(function(response) {
console.log('Email Sentiment score->: '+response.result[0].sentiment);
result=response.result[0].sentiment;
//respond to chat
builder.Prompts.text(session,'Here is an overview of the email');
builder.Prompts.text(session,'Summary: '+summary);
builder.Prompts.text(session,'Keywords: '+keywords);
builder.Prompts.text(session,'Sentiment Score: '+result);
});
return result;
}
}
])
.triggerAction({
matches:/^outlook$/i,
confirmPrompt:'This will interrupt your conversation,are you sure?'
});
function readBuffer(buffer){
function formatEmail(data) {
return data.name ? data.name + " [" + data.email + "]" : data.email;
}
function parseHeaders(headers) {
var parsedHeaders = {};
if (!headers) {
return parsedHeaders;
}
var headerRegEx = /(.*)\: (.*)/g;
while (m = headerRegEx.exec(headers)) {
// todo: Pay attention! Header can be presented many times (e.g. Received). Handle it, if needed!
parsedHeaders[m[1]] = m[2];
}
return parsedHeaders;
}
function getMsgDate(rawHeaders) {
// Example for the Date header
var headers = parseHeaders(rawHeaders);
if (!headers['Date']){
return '-';
}
return new Date(headers['Date']);
}
const MSGReader= require ('./mail_reader/msg.reader.js');
//require '../msg.reader.js'
var msgReader = new MSGReader(buffer);
var fileData = msgReader.getFileData();
console.log('fileData'+fileData);
if (!fileData.error) {
console.log('name: '+fileData.senderName );
console.log(' email: '+ fileData.senderEmail);
console.log(' sent to: '+ fileData.recipients);
// $('.msg-example .msg-to').html(jQuery.map(fileData.recipients, function (recipient, i) {
// return formatEmail(recipient);
// }).join('<br/>'));
console.log('Email Date= '+getMsgDate(fileData.headers));
console.log('Email Subject= '+fileData.subject);
console.log('Email Body'+fileData.body);
console.log('attachments'+Object.keys(fileData.attachments));
// $('.msg-example .msg-attachment').html(jQuery.map(fileData.attachments, function (attachment, i) {
// return attachment.fileName + ' [' + attachment.contentLength + 'bytes]' +
// (attachment.pidContentId ? '; ID = ' + attachment.pidContentId : '');
// }).join('<br/>'));
// $('.msg-info').show();
// Use msgReader.getAttachment to access attachment content ...
// msgReader.getAttachment(0) or msgReader.getAttachment(fileData.attachments[0])
} else {
console.log('Parsed message has an error');
}
return fileData.body;
}
function openOutlook(sendto,error){
var childProcess = require('child_process');
childProcess.spawn(
"powershell.exe",
['$mail = (New-Object -comObject Outlook.Application).CreateItem(0);$mail.Subject = "Color Code Error";$mail.Body="I have error '+error+' on Color Code.Kindly Assist";$mail.To ="'+sendto+'"; $mail.Send();']
);
}
//Sub-Dialogs
bot.library(require('./dialogs/reset-password'));
//Validators
bot.library(require('./validators'));
server.post('/api/messages', connector.listen());
//outlook read metadata handlers
function formatEmail(data) {
return data.name ? data.name + " [" + data.email + "]" : data.email;
}
function parseHeaders(headers) {
var parsedHeaders = {};
if (!headers) {
return parsedHeaders;
}
var headerRegEx = /(.*)\: (.*)/g;
while (m = headerRegEx.exec(headers)) {
// todo: Pay attention! Header can be presented many times (e.g. Received). Handle it, if needed!
parsedHeaders[m[1]] = m[2];
}
return parsedHeaders;
}
function getMsgDate(rawHeaders) {
// Example for the Date header
var headers = parseHeaders(rawHeaders);
if (!headers['Date']){
return '-';
}
return new Date(headers['Date']);
}