-
Notifications
You must be signed in to change notification settings - Fork 745
/
conversationManager.ts
645 lines (584 loc) · 24.4 KB
/
conversationManager.ts
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Framework Emulator Github:
// https://github.com/Microsoft/BotFramwork-Emulator
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import * as request from 'request';
import * as http from 'http';
import * as Payment from '../types/paymentTypes';
import { IUser } from '../types/userTypes';
import { IActivity, IConversationUpdateActivity, IMessageActivity, IContactRelationUpdateActivity, IInvokeActivity } from '../types/activityTypes';
import { PaymentEncoder } from '../shared/paymentEncoder';
import { ISpeechTokenInfo } from '../types/speechTypes';
import { uniqueId } from '../shared/utils';
import { dispatch, getSettings, authenticationSettings, addSettingsListener, speechSettings } from './settings';
import { Settings } from '../types/serverSettingsTypes';
import * as HttpStatus from "http-status-codes";
import * as ResponseTypes from '../types/responseTypes';
import { ErrorCodes, IResourceResponse } from '../types/responseTypes';
import { emulator } from './emulator';
import * as log from './log';
import * as utils from '../shared/utils';
import { usersDefault } from '../types/serverSettingsTypes';
import * as moment from 'moment';
/**
* Stores and propagates conversation messages.
*/
export class Conversation {
private accessToken: string;
private accessTokenExpires: number;
private speechToken: ISpeechTokenInfo;
constructor(botId: string, conversationId: string, user: IUser) {
this.botId = botId;
this.conversationId = conversationId;
this.members.push({ id: botId, name: "Bot" });
this.members.push({ id: user.id, name: user.name });
}
// the botId this conversation is with
public botId: string;
// the id for this conversation
public conversationId: string;
// the list of activities in this conversation
public activities: IActivity[] = [];
public members: IUser[] = [];
// flag indicating if the user has been shown the
// "please don't use default Bot State API" warning message
// when they try to write bot state data
public stateApiDeprecationWarningShown: boolean = false;
getCurrentUser() {
const users = getSettings().users;
let currentUser = users.usersById[users.currentUserId];
// TODO: This is a band-aid until state system cleanup
if (!currentUser) {
currentUser = usersDefault.usersById['default-user'];
dispatch({
type: 'Users_SetCurrentUser',
state: {
user: currentUser
}
})
}
return currentUser;
}
private postage(recipientId: string, activity: IActivity) {
const date = moment();
activity.id = activity.id || uniqueId();
activity.channelId = 'emulator';
activity.timestamp = date.toISOString();
activity.localTimestamp = date.format();
activity.recipient = { id: recipientId };
activity.conversation = activity.conversation || { id: this.conversationId };
}
/**
* Sends the activity to the conversation's bot.
*/
postActivityToBot(activity: IActivity, recordInConversation: boolean, cb?) {
// Do not make a shallow copy here before modifying
this.postage(this.botId, activity);
activity.from = activity.from || this.getCurrentUser();
if (!activity.recipient.name) {
activity.recipient.name = "Bot";
}
const settings = getSettings();
const bot = settings.botById(this.botId);
if (bot) {
activity.serviceUrl = emulator.framework.getServiceUrl(bot.botUrl);
let options: request.OptionsWithUrl = {
url: bot.botUrl,
method: "POST",
json: activity,
agent: emulator.proxyAgent,
strictSSL: false
};
let responseCallback = (err, resp: http.IncomingMessage, body) => {
let messageActivity: IMessageActivity = activity;
let text = messageActivity.text || '';
if (text && text.length > 50)
text = text.substring(0, 50);
if (err) {
log.error(
'->',
log.makeInspectorLink("POST", activity),
err.message);
} else if (resp) {
if (!/^2\d\d$/.test(`${resp.statusCode}`)) {
log.error(
'->',
log.makeInspectorLink("POST", activity),
log.makeInspectorLink(`${resp.statusCode}`, body, `(${resp.statusMessage})`),
`[${activity.type}]`,
text);
if(Number(resp.statusCode) == 401 || Number(resp.statusCode) == 402) {
log.error("Error: The bot's MSA appId or password is incorrect.");
log.error(log.botCredsConfigurationLink('Edit your bot\'s MSA info'));
}
cb(err, resp ? resp.statusCode : undefined);
} else {
log.info(
'->',
log.makeInspectorLink("POST", activity),
log.makeInspectorLink(`${resp.statusCode}`, body, `(${resp.statusMessage})`),
`[${activity.type}]`,
text);
if (recordInConversation) {
this.activities.push(Object.assign({}, activity));
}
if(activity.type === 'invoke') {
cb(null, resp.statusCode, activity.id, body);
} else {
cb(null, resp.statusCode, activity.id);
}
}
}
}
if (!utils.isLocalhostUrl(bot.botUrl) && utils.isLocalhostUrl(emulator.framework.getServiceUrl(bot.botUrl))) {
log.error('Error: The bot is remote, but the callback URL is localhost. Without tunneling software you will not receive replies.');
log.error(log.makeLinkMessage('Connecting to bots hosted remotely', 'https://aka.ms/cnjvpo'));
log.error(log.ngrokConfigurationLink('Edit ngrok settings'));
}
if (bot.msaAppId && bot.msaPassword) {
this.authenticatedRequest(options, responseCallback);
} else {
request(options, responseCallback);
}
} else {
cb("bot not found");
}
}
sendConversationUpdate(membersAdded: IUser[], membersRemoved: IUser[]) {
const activity: IConversationUpdateActivity = {
type: 'conversationUpdate',
membersAdded,
membersRemoved
}
this.postActivityToBot(activity, false, () => {});
}
/**
* Queues activity for delivery to user.
*/
public postActivityToUser(activity: IActivity): IResourceResponse {
const settings = getSettings();
// Make a shallow copy before modifying & queuing
let visitor = new PaymentEncoder();
activity = Object.assign({}, activity);
visitor.traverseActivity(activity);
this.postage(settings.users.currentUserId, activity);
if (!activity.from.name) {
activity.from.name = "Bot";
}
this.activities.push(activity);
return ResponseTypes.createResourceResponse(activity.id);
}
// updateActivity with replacement
public updateActivity(updatedActivity: IActivity): IResourceResponse {
// if we found the activity to reply to
let oldActivity = this.activities.find((val) => val.id == updatedActivity.id);
if (oldActivity) {
Object.assign(oldActivity, updatedActivity);
return ResponseTypes.createResourceResponse(updatedActivity.id);
}
throw ResponseTypes.createAPIException(HttpStatus.NOT_FOUND, ErrorCodes.BadArgument, "not a known activity id");
}
public deleteActivity(id: string) {
// if we found the activity to reply to
let index = this.activities.findIndex((val) => val.id == id);
if (index >= 0) {
this.activities.splice(index, 1);
return;
}
throw ResponseTypes.createAPIException(HttpStatus.NOT_FOUND, ErrorCodes.BadArgument, "The activity id was not found");
}
// add member
public addMember(id: string, name: string): IUser {
name = name || `user-${uniqueId(4)}`;
id = id || uniqueId();
let user = {name, id};
this.members.push(user);
this.sendConversationUpdate([user], undefined);
return user;
}
public removeMember(id: string) {
let index = this.members.findIndex((val) => val.id == id);
if (index >= 0) {
this.members.splice(index, 1);
}
this.sendConversationUpdate(undefined, [{id, name: undefined}]);
}
public sendContactAdded() {
const activity: IContactRelationUpdateActivity = {
type: 'contactRelationUpdate',
action: 'add'
}
this.postActivityToBot(activity, false, () => {});
}
public sendContactRemoved() {
const activity: IContactRelationUpdateActivity = {
type: 'contactRelationUpdate',
action: 'remove'
}
this.postActivityToBot(activity, false, () => {});
}
public sendTyping() {
const activity: IActivity = {
type: 'typing'
}
this.postActivityToBot(activity, false, () => {});
}
public sendPing() {
const activity: IActivity = {
type: 'ping'
}
this.postActivityToBot(activity, false, () => {});
}
public sendDeleteUserData() {
const activity: IActivity = {
type: 'deleteUserData'
}
this.postActivityToBot(activity, false, () => {});
}
public sendUpdateShippingAddressOperation(
checkoutSession: Payment.ICheckoutConversationSession,
request: Payment.IPaymentRequest,
shippingAddress: Payment.IPaymentAddress,
shippingOptionId: string,
cb: (errCode, body) => void) {
this.sendUpdateShippingOperation(
checkoutSession,
Payment.PaymentOperations.UpdateShippingAddressOperationName,
request,
shippingAddress,
shippingOptionId,
cb
);
}
public sendUpdateShippingOptionOperation(
checkoutSession: Payment.ICheckoutConversationSession,
request: Payment.IPaymentRequest,
shippingAddress: Payment.IPaymentAddress,
shippingOptionId: string,
cb: (errCode, body) => void) {
this.sendUpdateShippingOperation(
checkoutSession,
Payment.PaymentOperations.UpdateShippingOptionOperationName,
request,
shippingAddress,
shippingOptionId,
cb
);
}
private sendUpdateShippingOperation(
checkoutSession: Payment.ICheckoutConversationSession,
operation: string,
request: Payment.IPaymentRequest,
shippingAddress: Payment.IPaymentAddress,
shippingOptionId: string,
cb: (errCode, body) => void) {
const updateValue: Payment.IPaymentRequestUpdate = {
id: request.id,
shippingAddress: shippingAddress,
shippingOption: shippingOptionId,
details: request.details
};
let serviceUrl;
const settings = getSettings();
const bot = settings.botById(this.botId);
serviceUrl = emulator.framework.getServiceUrl(bot.botUrl);
const activity: IInvokeActivity = {
type: 'invoke',
name: operation,
from: { id: checkoutSession.checkoutFromId },
conversation: {id: checkoutSession.checkoutConversationId },
relatesTo: {
activityId: checkoutSession.paymentActivityId,
bot: { id: this.botId },
channelId: 'emulator',
conversation: { id: this.conversationId },
serviceUrl: serviceUrl,
user: this.getCurrentUser()
},
value: updateValue
};
this.postActivityToBot(activity, false, (err, statusCode, activityId, responseBody) => {
cb(statusCode, responseBody);
});
}
public sendPaymentCompleteOperation(
checkoutSession: Payment.ICheckoutConversationSession,
request: Payment.IPaymentRequest,
shippingAddress: Payment.IPaymentAddress,
shippingOptionId: string,
payerEmail: string,
payerPhone: string,
cb: (errCode, body) => void) {
let paymentTokenHeader = {
format: 2,
merchantId: request.methodData[0].data.merchantId,
paymentRequestId: request.id,
amount: request.details.total.amount,
expiry: '1/1/2020',
timestamp: '4/27/2017',
};
let paymentTokenHeaderStr = JSON.stringify(paymentTokenHeader);
let pthBytes = new Buffer(paymentTokenHeaderStr).toString('base64');
let paymentTokenSource = 'tok_18yWDMKVgMv7trmwyE21VqO';
let ptsBytes = new Buffer(paymentTokenSource).toString('base64');
let ptsigBytes = new Buffer('Emulator').toString('base64');
const updateValue: Payment.IPaymentRequestComplete = {
id: request.id,
paymentRequest: request,
paymentResponse: {
details: {
paymentToken: pthBytes + '.' + ptsBytes + '.' + ptsigBytes
},
methodName: request.methodData[0].supportedMethods[0],
payerEmail: payerEmail,
payerPhone: payerPhone,
shippingAddress: shippingAddress,
shippingOption: shippingOptionId
}
};
let serviceUrl;
const settings = getSettings();
const bot = settings.botById(this.botId);
serviceUrl = emulator.framework.getServiceUrl(bot.botUrl);
const activity: IInvokeActivity = {
type: 'invoke',
name: Payment.PaymentOperations.PaymentCompleteOperationName,
from: { id: checkoutSession.checkoutFromId },
conversation: {id: checkoutSession.checkoutConversationId },
relatesTo: {
activityId: checkoutSession.paymentActivityId,
bot: { id: this.botId },
channelId: 'emulator',
conversation: { id: this.conversationId },
serviceUrl: serviceUrl,
user: this.getCurrentUser()
},
value: updateValue
};
this.postActivityToBot(activity, false, (err, statusCode, activityId, responseBody) => {
cb(statusCode, responseBody);
});
}
public getSpeechToken(duration: number, cb: (tokenInfo: ISpeechTokenInfo) => void, refresh: boolean = false) {
if (this.speechToken && !refresh) {
cb(this.speechToken);
} else {
// fetch the speech token
const settings = getSettings();
const bot = settings.botById(this.botId);
if (bot.msaAppId && bot.msaPassword) {
let options: request.OptionsWithUrl = {
url: speechSettings.tokenEndpoint + '?goodForInMinutes=' + duration,
method: 'GET',
agent: emulator.proxyAgent,
strictSSL: false
};
let responseCallback = (err, resp: http.IncomingMessage, body) => {
if (body) {
let speechToken: ISpeechTokenInfo = JSON.parse(body) as ISpeechTokenInfo;
if (speechToken.access_Token) {
this.speechToken = speechToken;
}
cb(speechToken);
} else if (err) {
cb({access_Token: undefined, error: err, error_Description: undefined});
} else if (resp.statusCode === 401) {
cb({access_Token: undefined, error: 'Unauthorized', error_Description: 'This bot is not authorized to use the Cognitive Services Speech API.'});
} else {
cb({access_Token: undefined, error: 'Unable to retrieve speech token', error_Description: 'A speech token could not be retrieved for this bot. Response code: ' + resp.statusCode});
}
}
this.authenticatedRequest(options, responseCallback);
} else {
cb({access_Token: undefined, error: 'Unauthorized', error_Description: 'To use speech, the bot must be registered and using a valid MS AppId and Password.'});
}
}
}
/**
* Returns activities since the watermark.
*/
getActivitiesSince(watermark: number): IActivity[] {
return this.activities.slice(watermark);
}
private authenticatedRequest(options: request.OptionsWithUrl, callback: (error: any, response: http.IncomingMessage, body: any) => void, refresh = false): void {
if (refresh) {
this.accessToken = null;
}
this.addAccessToken(options, (err) => {
if (!err) {
request(options, (err, response, body) => {
if (!err) {
switch (response.statusCode) {
case HttpStatus.UNAUTHORIZED:
case HttpStatus.FORBIDDEN:
if (!refresh) {
this.authenticatedRequest(options, callback, true);
} else {
callback(null, response, body);
}
break;
default:
if (response.statusCode < 400) {
callback(null, response, body);
} else {
let txt = "Request to '" + options.url + "' failed: [" + response.statusCode + "] " + response.statusMessage;
callback(new Error(txt), response, null);
}
break;
}
} else {
callback(err, null, null);
}
});
} else {
callback(err, null, null);
}
});
}
public getAccessToken(cb: (err: Error, accessToken: string) => void): void {
if (!this.accessToken || new Date().getTime() >= this.accessTokenExpires) {
const bot = getSettings().botById(this.botId);
// Refresh access token
let opt: request.OptionsWithUrl = {
method: 'POST',
url: authenticationSettings.tokenEndpoint,
form: {
grant_type: 'client_credentials',
client_id: bot.msaAppId,
client_secret: bot.msaPassword,
scope: bot.msaAppId + '/.default',
},
agent: emulator.proxyAgent,
strictSSL: false
};
if (getSettings().framework.use10Tokens) {
// flag to request a version 1.0 token
opt.form.atver = 1;
}
request(opt, (err, response, body) => {
if (!err) {
if (body && response.statusCode < 300) {
// Subtract 5 minutes from expires_in so they'll we'll get a
// new token before it expires.
let oauthResponse = JSON.parse(body);
this.accessToken = oauthResponse.access_token;
this.accessTokenExpires = new Date().getTime() + ((oauthResponse.expires_in - 300) * 1000);
cb(null, this.accessToken);
} else {
cb(new Error('Refresh access token failed with status code: ' + response.statusCode), null);
}
} else {
cb(err, null);
}
});
} else {
cb(null, this.accessToken);
}
}
private addAccessToken(options: request.Options, cb: (err: Error) => void): void {
const bot = getSettings().botById(this.botId);
if (bot.msaAppId && bot.msaPassword) {
this.getAccessToken((err, token) => {
if (!err && token) {
options.headers = {
'Authorization': 'Bearer ' + token
};
cb(null);
} else {
cb(err);
}
});
} else {
cb(null);
}
}
}
/**
* A set of conversations with a bot.
*/
class ConversationSet {
botId: string;
conversations: Conversation[] = [];
constructor(botId: string) {
this.botId = botId;
}
newConversation(user: IUser, conversationId?: string): Conversation {
const conversation = new Conversation(this.botId, conversationId || uniqueId(), user);
this.conversations.push(conversation);
return conversation;
}
conversationById(conversationId: string): Conversation {
return this.conversations.find(value => value.conversationId === conversationId);
}
}
/**
* Container for conversations.
*/
export class ConversationManager {
conversationSets: ConversationSet[] = [];
constructor() {
addSettingsListener((settings: Settings) => {
this.configure(settings);
});
this.configure(getSettings());
}
/**
* Applies configuration changes.
*/
private configure(settings: Settings) {
// Remove conversations that reference nonexistent bots.
const deadBotIds = this.conversationSets.filter(set => !settings.bots.find(bot => bot.botId === set.botId)).map(conversation => conversation.botId);
this.conversationSets = this.conversationSets.filter(set => !deadBotIds.find(botId => set.botId === botId));
}
/**
* Creates a new conversation.
*/
public newConversation(botId: string, user: IUser, conversationId?: string): Conversation {
let conversationSet = this.conversationSets.find(value => value.botId === botId);
if (!conversationSet) {
conversationSet = new ConversationSet(botId);
this.conversationSets.push(conversationSet);
}
let conversation = conversationSet.newConversation(user, conversationId);
return conversation;
}
/**
* Gets the existing conversation, or returns undefined.
*/
public conversationById(botId: string, conversationId: string): Conversation {
const set = this.conversationSets.find(set => set.botId === botId);
if (set) {
return set.conversationById(conversationId);
} else {
return null;
}
}
}