/
protocolHandler.ts
346 lines (313 loc) · 11.7 KB
/
protocolHandler.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
//
// 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 Path from 'path';
import { FrameworkSettings, newNotification, SharedConstants } from '@bfemulator/app-shared';
import got from 'got';
import { IEndpointService } from 'botframework-config/lib/schema';
import {
applyBotConfigOverrides,
BotConfigOverrides,
BotConfigWithPath,
CommandServiceImpl,
CommandServiceInstance,
StartConversationParams,
} from '@bfemulator/sdk-shared';
import { Protocol } from './constants';
import { Emulator } from './emulator';
import { getSettings } from './state/store';
import { sendNotificationToClient } from './utils/sendNotificationToClient';
import { TelemetryService } from './telemetry';
enum ProtocolDomains {
livechat,
transcript,
bot,
inspector,
}
export enum ProtocolLiveChatActions {
open,
}
export enum ProtocolTranscriptActions {
open,
}
export enum ProtocolBotActions {
open,
}
export interface Protocol {
// the 'controller'
domain?: string;
// the 'action' or 'route' within the controller
action?: string;
// any extra info passed in
args?: string;
// object reprsentation of args
parsedArgs?: { [key: string]: string } | any;
}
export interface ProtocolHandler {
parseProtocolUrl: (url: string) => Protocol;
dispatchProtocolAction: (protocol: Protocol) => void;
performLiveChatAction: (protocol: Protocol) => void;
performTranscriptAction: (protocol: Protocol) => void;
performBotAction: (protocol: Protocol) => void;
}
class ProtocolHandlerImpl implements ProtocolHandler {
@CommandServiceInstance()
private commandService: CommandServiceImpl;
/** Extracts useful information out of a protocol URL */
public parseProtocolUrl(url: string): Protocol {
const parsedUrl = new URL(url);
if (!Protocol.startsWith(parsedUrl.protocol)) {
throw new Error(`Invalid protocol url. Must start with '${Protocol}'`);
}
// grab what's left after the protocol prefix (protocol automatically places '/' before query string params)
const domainAndAction = (parsedUrl.hostname || '').toLowerCase().split('.');
const [domain = '', action = ''] = domainAndAction;
const parsedArgs = {};
parsedUrl.searchParams.forEach((value: string, key: string) => (parsedArgs[key] = value));
return {
domain,
action,
args: (parsedUrl.search || '').replace(/(\?)/, ''),
parsedArgs,
};
}
/** Uses information from a protocol URL and carries out the corresponding action */
public dispatchProtocolAction(protocol: Protocol): void {
switch (ProtocolDomains[protocol.domain]) {
case ProtocolDomains.bot:
this.performBotAction(protocol);
break;
case ProtocolDomains.livechat:
this.performLiveChatAction(protocol);
break;
case ProtocolDomains.transcript:
this.performTranscriptAction(protocol);
break;
case ProtocolDomains.inspector:
this.performInspectorAction(protocol);
break;
default:
break;
}
}
/** Reads in a protocol URL and then performs the corresponding action if valid */
public parseProtocolUrlAndDispatch(url: string): void {
this.dispatchProtocolAction(this.parseProtocolUrl(url));
}
public performLiveChatAction(protocol: Protocol): void {
const {
botUrl: endpoint,
msaAppId: appId,
msaAppPassword: appPassword,
cloud: channelService,
} = protocol.parsedArgs;
this.commandService.remoteCall(SharedConstants.Commands.UI.OpenBotViaUrl, {
endpoint,
appId,
appPassword,
mode: 'livechat',
channelService,
} as StartConversationParams);
}
public performTranscriptAction(protocol: Protocol): void {
this.openTranscript(protocol);
}
public performBotAction(protocol: Protocol): void {
this.openBot(protocol);
}
public performInspectorAction(protocol: Protocol): void {
const {
botUrl: endpoint,
msaAppId: appId,
msaAppPassword: appPassword,
cloud: channelService,
} = protocol.parsedArgs;
this.commandService.remoteCall(SharedConstants.Commands.UI.OpenBotViaUrl, {
endpoint,
appId,
appPassword,
mode: 'debug',
channelService,
} as StartConversationParams);
}
/** Downloads a transcript from a URL provided in the protocol string,
* parses out the list of activities, and has the client side open it
*/
public openTranscript(protocol: Protocol): void {
const { url } = protocol.parsedArgs;
const options = { url };
return got(options)
.then(res => {
if (/^2\d\d$/.test(res.statusCode)) {
if (res.body) {
try {
// parse the activities from the downloaded transcript
const transcriptString = res.body;
const conversationActivities = JSON.parse(transcriptString);
if (!Array.isArray(conversationActivities)) {
throw new Error('Invalid transcript file contents; should be an array of conversation activities.');
}
const { name, ext } = Path.parse(url);
const fileName = `${name}${ext}`;
// open a transcript on the client side and pass in some
// extra info to differentiate it from a transcript on disk
this.commandService.remoteCall(SharedConstants.Commands.Emulator.OpenTranscript, 'deepLinkedTranscript', {
activities: conversationActivities,
inMemory: true,
fileName,
});
} catch (e) {
throw new Error(`Error occured while reading downloaded transcript: ${e}`);
}
}
} else {
if (res.statusCode === 401) {
// auth failed
const stat = res.body || res.statusText || '';
throw new Error(`Authorization error while trying to download transcript: ${stat}`);
}
if (res.statusCode === 404) {
// transcript link is broken / doesn't exist anymore
throw new Error(`Transcript file not found at: ${url}`);
}
}
})
.catch(err => {
const errMsg = `Error downloading and parsing transcript file: ${err}`;
const notification = newNotification(errMsg);
sendNotificationToClient(notification, this.commandService);
});
}
/** Opens the bot project associated with the .bot file at the specified path */
public async openBot(protocol: Protocol): Promise<void> {
const { path, secret }: { path: string; secret: string } = protocol.parsedArgs;
const endpointOverrides: Partial<IEndpointService> = parseEndpointOverrides(protocol.parsedArgs);
const overrides: BotConfigOverrides = endpointOverrides ? { endpoint: endpointOverrides } : null;
let bot: BotConfigWithPath;
try {
bot = (await this.commandService.call(SharedConstants.Commands.Bot.Open, path, secret)) as BotConfigWithPath;
if (!bot) {
throw new Error(
`Error occurred while trying to open bot at ${path} inside of protocol handler: Bot is invalid.`
);
}
} catch (e) {
throw new Error(`Error occurred while trying to open bot at ${path} inside of protocol handler: ${e}`);
}
// apply any overrides
if (overrides) {
bot = applyBotConfigOverrides(bot, overrides);
}
const appSettings: FrameworkSettings = getSettings().framework;
if (appSettings.ngrokPath) {
const ngrok = Emulator.getInstance().ngrok;
let ngrokSpawnStatus = ngrok.getSpawnStatus();
// if ngrok hasn't spawned yet, we need to start it up
if (!ngrokSpawnStatus.triedToSpawn) {
await ngrok.recycle();
}
ngrokSpawnStatus = ngrok.getSpawnStatus();
if (ngrokSpawnStatus.triedToSpawn && ngrokSpawnStatus.err) {
throw new Error(`Error while trying to spawn ngrok instance: ${ngrokSpawnStatus.err || ''}`);
}
if (ngrok.running) {
try {
await this.commandService.call(SharedConstants.Commands.Bot.SetActive, bot);
await this.commandService.remoteCall(SharedConstants.Commands.Bot.Load, bot);
} catch (e) {
throw new Error(`(ngrok running) Error occurred while trying to deep link to bot project at ${path}: ${e}`);
}
} else {
// if ngrok hasn't connected yet, wait for it to connect and load the bot
ngrok.ngrokEmitter.once(
'connect',
async (...args: any[]): Promise<void> => {
try {
await this.commandService.call(SharedConstants.Commands.Bot.SetActive, bot);
await this.commandService.remoteCall(SharedConstants.Commands.Bot.Load, bot);
} catch (e) {
throw new Error(
`(ngrok running but not connected) Error occurred while ` +
`trying to deep link to bot project at ${path}: ${e}`
);
}
}
);
}
} else {
try {
await this.commandService.call(SharedConstants.Commands.Bot.SetActive, bot);
await this.commandService.remoteCall(SharedConstants.Commands.Bot.Load, bot);
} catch (e) {
throw new Error(
`(ngrok not configured) Error occurred while trying to deep link to bot project at ${path}: ${e}`
);
}
}
const numOfServices = bot.services && bot.services.length;
TelemetryService.trackEvent('bot_open', {
method: 'protocol',
numOfServices,
source: 'path',
});
}
}
export const ProtocolHandler = new ProtocolHandlerImpl();
/**
* Takes the list of parsed protocol URI query params and constructs an endpoint service
* override object if there are appropriate parameters
* @param parsedArgs Parsed protocol URI query parameters
*/
export function parseEndpointOverrides(parsedArgs: { [key: string]: string }): Partial<IEndpointService> {
if (!parsedArgs || !Object.keys(parsedArgs).length) {
return null;
}
const endpointOverrides: Partial<IEndpointService> = {};
const { appId = null, appPassword = null, endpoint = null, id = null } = parsedArgs;
if (appId) {
endpointOverrides.appId = appId;
}
if (appPassword) {
endpointOverrides.appPassword = appPassword;
}
if (endpoint) {
endpointOverrides.endpoint = endpoint;
}
if (id) {
endpointOverrides.id = id;
}
// if no overrides were parsed, then return null
if (!Object.keys(endpointOverrides).length) {
return null;
}
return endpointOverrides;
}