forked from m0ngr31/lexigram-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.ts
497 lines (424 loc) · 15.3 KB
/
actions.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
import * as execSh from 'exec-sh';
import * as execa from 'execa';
import * as fs from 'fs';
import * as readlineSync from 'readline-sync';
import * as fse from 'fs-extra';
import * as Listr from 'listr';
import * as unzip from 'unzip-stream';
import * as promisePipe from 'promisepipe';
import * as _ from 'lodash';
import * as archiver from 'archiver-promise';
import * as path from 'path';
import * as process from 'process';
import axios from 'axios';
import ParseIni from './ParseIni';
import {getIntents, getSlots} from './InteractionModel';
import {ErrorLogger} from './ErrorHandler';
const askPath = `${__dirname}/../node_modules/.bin/ask`;
const jsonOptions = {
spaces: 2
};
export const loginOrSwitch = (args, options, logger) => {
if (options.noBrowser) {
execSh(`${askPath} init --no-browser`, {});
} else {
execSh(`${askPath} init`, {});
}
};
export const downloadConfig = async (args, options, logger) => {
const url = 'https://rawgit.com/m0ngr31/kodi-voice/master/kodi_voice/kodi.config.example';
const fileName = 'kodi.config';
if (fs.existsSync(fileName)) {
const answer = readlineSync.keyInYNStrict('Config file already exists. Would you like to overwrite?');
if (!answer) {
return;
}
}
const request = await axios.request({
url,
responseType: 'arraybuffer'
});
fs.writeFileSync(fileName, request.data);
};
export const initSkill = async (args, options, logger) => {
const dir = args.skill;
const tasks = new Listr([
{
title: `Initialize ${dir} skill`,
task: async () => {
let doInit = false;
if (fs.existsSync(dir)) {
const answer = readlineSync.keyInYNStrict('Skill directory exists. Would you like to overwrite?');
if (answer) {
let skillId = '';
const skillConfig = fse.readJsonSync(`${dir}/.ask/config`);
if (_.hasIn(skillConfig, 'deploy_settings.default.skill_id')) {
skillId = skillConfig.deploy_settings.default.skill_id;
try {
await execa(askPath, ['api', 'delete-skill', '--skill-id', skillId], { cwd: dir, timeout: 60000 });
} catch (e) { }
}
fse.removeSync(dir);
doInit = true;
}
} else {
doInit = true;
}
if (doInit) {
try {
await execa(askPath, ['new', '-n', dir]);
const newSkillConfig = fse.readJsonSync(`${dir}/.ask/config`);
delete newSkillConfig.deploy_settings.default.merge;
fse.writeJsonSync(`${dir}/.ask/config`, newSkillConfig, jsonOptions);
} catch (e) {
ErrorLogger(e);
throw new Error('Could not create skill. Please try again.');
}
}
}
}
]);
tasks.run().catch(err => {});
};
export const updateOrDeploySkill = async (args, options, logger) => {
let getInput = true;
let answer = '';
let uri = '';
let invocationName = args.skill;
let changeApi = false;
if (args.skill === 'kanzi') {
if (options.invocationName && options.invocationName.length) {
invocationName = options.invocationName.toLowerCase();
} else {
const invocationOpts = ['Kanzi', 'Kodi'];
let invocationAnswer = readlineSync.keyInSelect(invocationOpts, 'What would you like your invocation name to be?');
if (invocationAnswer === -1) {
return;
}
invocationName = invocationOpts[invocationAnswer].toLowerCase();
}
}
if (fs.existsSync(args.skill) && fs.existsSync(`${args.skill}/skill.json`)) {
const existingSkillConfig = fse.readJsonSync(`${args.skill}/skill.json`);
if (_.hasIn(existingSkillConfig, 'manifest.apis.custom.endpoint.uri')) {
getInput = false;
changeApi = true;
uri = existingSkillConfig.manifest.apis.custom.endpoint.uri;
}
}
if (options.url && options.url.length) {
getInput = false;
changeApi = true;
uri = options.url;
}
while (getInput) {
answer = readlineSync.question("What's the URL for your skill server? (ex. https://... or arn:...). Press enter to skip. ");
if (answer.length && (answer.substring(0, 8) === 'https://' || answer.substring(0, 4) === 'arn:')) {
getInput = false;
uri = answer;
changeApi = true;
} else if (!answer.length) {
getInput = false;
changeApi = false;
} else {
logger.warn('Invalid URI. Please try again.');
}
}
const tasks = new Listr([
{
title: 'Check config file',
task: ctx => {
ctx.configFile = 'kodi.config';
if (!fs.existsSync(ctx.configFile)) {
throw new Error("Config file not found. Please run 'lexigram init-config' first.");
}
}
},
{
title: 'Validate config file',
task: ctx => {
ctx.config = new ParseIni();
const file = fs.readFileSync(ctx.configFile, 'utf8');
ctx.config.parse(file);
if (!ctx.config.verifyData()) {
throw new Error('Configuration file is not valid. Please update it with the correct information.');
}
}
},
{
title: 'Check skill directory',
task: ctx => {
ctx.dir = args.skill;
if (!fs.existsSync(ctx.dir)) {
throw new Error(`Skill directory not found. Please run 'lexigram init-skill ${ctx.dir}' first.`);
}
}
},
{
title: 'Remove old repo code',
skip: ctx => options.sourceDir && options.sourceDir.length,
task: ctx => {
fse.removeSync(`${ctx.dir}/source/repo`);
fse.ensureDir(`${ctx.dir}/source/repo`);
}
},
{
title: 'Download latest source code',
skip: ctx => options.sourceDir && options.sourceDir.length,
task: async ctx => {
fse.removeSync(`${ctx.dir}-github.zip`);
let releaseUrl;
try {
const url = ctx.dir === 'kanzi' ?
'https://api.github.com/repos/m0ngr31/kanzi/releases/latest' :
'https://api.github.com/repos/m0ngr31/koko/releases/latest';
const request = await axios.request({
url
});
releaseUrl = request.data.zipball_url;
const releaseRequest = await axios.request({
url: releaseUrl,
responseType: 'arraybuffer'
});
fs.writeFileSync(`${ctx.dir}-github.zip`, releaseRequest.data);
} catch (e) {
ErrorLogger('Could not download latest release.');
throw new Error('Could not download latest release. Please try again.');
}
}
},
{
title: 'Extract source code',
skip: ctx => options.sourceDir && options.sourceDir.length,
task: async ctx => {
try {
await promisePipe(
fs.createReadStream(`${ctx.dir}-github.zip`),
unzip.Extract({ path: `${ctx.dir}/source/repo` })
);
} catch (e) {
ErrorLogger('Could not extract source code.');
throw new Error('Could not extract source code. Please try again.');
}
}
},
{
title: 'Extract source code - Part 2',
skip: ctx => options.sourceDir && options.sourceDir.length,
task: async ctx => {
const readDir = fs.readdirSync(`${ctx.dir}/source/repo/`);
const githubFolder = readDir[0];
const readGithubFolder = fs.readdirSync(`${ctx.dir}/source/repo/${githubFolder}/`);
readGithubFolder.forEach(fileOrDir => {
fse.moveSync(`${ctx.dir}/source/repo/${githubFolder}/${fileOrDir}`, `${ctx.dir}/source/repo/${fileOrDir}`);
});
fse.removeSync(`${ctx.dir}/source/repo/${githubFolder}`);
fse.removeSync(`${ctx.dir}-github.zip`);
}
},
{
title: 'Update skill data',
task: ctx => {
const skillJson = args.skill === 'kanzi' ? 'kanzi-skill.json' : 'koko-skill.json';
const skillConfig = fse.readJsonSync(`${__dirname}/../${skillJson}`);
if (changeApi) {
delete skillConfig.manifest.apis;
skillConfig.manifest.apis = {
custom: {
endpoint: {
uri
}
}
};
if (args.skill === 'koko') {
skillConfig.manifest.apis.custom.interfaces = [
{
"type": "AUDIO_PLAYER"
}
]
}
if (uri.substring(0, 8) === 'https://') {
skillConfig.manifest.apis.custom.endpoint.sslCertificateType = 'Wildcard';
}
}
fse.removeSync(`${ctx.dir}/skill.json`);
fse.writeJsonSync(`${ctx.dir}/skill.json`, skillConfig, jsonOptions);
}
},
{
title: 'Update slot values',
task: async (ctx, task) => {
task.output = 'Generating slot data from Kodi.';
const isKanzi = args.skill === 'kanzi';
const origObj :any = {
interactionModel: {
languageModel: {
invocationName,
types: await getSlots(ctx.dir, ctx.config),
intents: []
}
}
};
task.output = 'Creating intent model.';
const englishObj = _.cloneDeep(origObj);
const germanObj = _.cloneDeep(origObj);
const frenchObj = _.cloneDeep(origObj);
const spanishObj = _.cloneDeep(origObj);
const italianObj = _.cloneDeep(origObj);
const fullDir = options.sourceDir && options.sourceDir.length ? options.sourceDir : null;
germanObj.interactionModel.languageModel.intents = getIntents(ctx.dir, 'de', fullDir);
englishObj.interactionModel.languageModel.intents = getIntents(ctx.dir, 'en', fullDir);
italianObj.interactionModel.languageModel.intents = getIntents(ctx.dir, 'it', fullDir);
if (isKanzi) {
frenchObj.interactionModel.languageModel.intents = getIntents(ctx.dir, 'fr', fullDir);
spanishObj.interactionModel.languageModel.intents = getIntents(ctx.dir, 'es', fullDir);
}
fse.removeSync(`${ctx.dir}/models/en-US.json`);
fse.removeSync(`${ctx.dir}/models/en-GB.json`);
fse.removeSync(`${ctx.dir}/models/en-CA.json`);
fse.removeSync(`${ctx.dir}/models/en-IN.json`);
fse.removeSync(`${ctx.dir}/models/en-AU.json`);
fse.removeSync(`${ctx.dir}/models/de-DE.json`);
fse.removeSync(`${ctx.dir}/models/fr-FR.json`);
fse.removeSync(`${ctx.dir}/models/fr-CA.json`);
fse.removeSync(`${ctx.dir}/models/es-ES.json`);
fse.removeSync(`${ctx.dir}/models/es-MX.json`);
fse.removeSync(`${ctx.dir}/models/it-IT.json`);
fse.writeJsonSync(`${ctx.dir}/models/en-US.json`, englishObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/en-GB.json`, englishObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/en-CA.json`, englishObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/en-IN.json`, englishObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/en-AU.json`, englishObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/de-DE.json`, germanObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/it-IT.json`, italianObj, jsonOptions);
if (isKanzi) {
fse.writeJsonSync(`${ctx.dir}/models/fr-FR.json`, frenchObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/fr-CA.json`, frenchObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/es-ES.json`, spanishObj, jsonOptions);
fse.writeJsonSync(`${ctx.dir}/models/es-MX.json`, spanishObj, jsonOptions);
}
}
},
{
title: 'Deploy skill',
task: async (ctx, task) => {
try {
task.output = 'Deploying skill information.';
await execa(askPath, ['deploy', '-t', 'skill'], { cwd: ctx.dir, timeout: 300000 });
task.output = 'Deploying skill slot data and intents.';
await execa(askPath, ['deploy', '-t', 'model'], { cwd: ctx.dir, timeout: 600000 });
} catch (e) {
ErrorLogger(e);
throw new Error('Error deploying. Please try again');
}
}
}
]);
tasks.run().catch(err => {});
};
export const generateZip = (args, options, logger) => {
const tasks = new Listr([
{
title: 'Check config file',
task: ctx => {
ctx.configFile = 'kodi.config';
if (!fs.existsSync(ctx.configFile)) {
throw new Error("Config file not found. Please run 'lexigram init-config' first.");
}
}
},
{
title: 'Validate config file',
task: ctx => {
ctx.config = new ParseIni();
const file = fs.readFileSync(ctx.configFile, 'utf8');
ctx.config.parse(file);
if (!ctx.config.verifyData()) {
throw new Error('Configuration file is not valid. Please update it with the correct information.');
}
}
},
{
title: 'Check skill directory',
task: ctx => {
ctx.dir = args.skill;
if (!fs.existsSync(ctx.dir)) {
throw new Error(`Skill directory not found. Please run 'lexigram init-skill ${ctx.dir}' first.`);
}
}
},
{
title: 'Remove old Lambda function code',
task: ctx => {
fse.removeSync(`${ctx.dir}/source/skill`);
fse.ensureDir(`${ctx.dir}/source/skill`);
}
},
{
title: 'Download latest source code',
task: async ctx => {
fse.removeSync(`${ctx.dir}-release.zip`);
let releaseUrl;
try {
const url = ctx.dir === 'kanzi' ?
'https://api.github.com/repos/m0ngr31/kanzi/releases/latest' :
'https://api.github.com/repos/m0ngr31/koko/releases/latest';
const request = await axios.request({
url
});
releaseUrl = request.data.assets[0].browser_download_url;
const releaseRequest = await axios.request({
url: releaseUrl,
responseType: 'arraybuffer'
});
fs.writeFileSync(`${ctx.dir}-release.zip`, releaseRequest.data);
} catch (e) {
ErrorLogger('Could not download latest release.');
throw new Error('Could not download latest release. Please try again.');
}
}
},
{
title: 'Extract source code',
task: async ctx => {
try {
await promisePipe(
fs.createReadStream(`${ctx.dir}-release.zip`),
unzip.Extract({ path: `${ctx.dir}/source/skill` })
);
fse.removeSync(`${ctx.dir}-release.zip`);
} catch (e) {
ErrorLogger('Could not extract source code.');
throw new Error('Could not extract source code. Please try again.');
}
}
},
{
title: 'Copy config file',
task: ctx => {
try {
fse.copySync(ctx.configFile, `${ctx.dir}/source/skill/${ctx.configFile}`);
} catch (e) {
ErrorLogger('Could not copy config file.');
throw new Error('Could not copy config file. Please try again.');
}
}
},
{
title: 'Create deployment zip file',
task: async ctx => {
fse.removeSync(`${ctx.dir}-lambda-upload.zip`);
const archive = archiver(`${ctx.dir}-lambda-upload.zip`, {
zlib: { level: 9 }
});
archive.directory(`${ctx.dir}/source/skill`, false);
await archive.finalize();
}
}
]);
tasks.run()
.then(() => {
logger.info(`\nFile is ready. Please upload '${args.skill}-lambda-upload.zip' to AWS Lambda.`)
})
.catch(err => {});
};