forked from formio/formio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.js
468 lines (420 loc) · 11.9 KB
/
install.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
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
'use strict';
const prompt = require('prompt');
const async = require('async');
const fs = require('fs-extra');
const _ = require('lodash');
const nunjucks = require('nunjucks');
nunjucks.configure([], {watch: false});
const util = require('./src/util/util');
const debug = require('debug')('formio:error');
const path = require('path');
module.exports = function(formio, items, done) {
// The project that was created.
let project = {};
// The directory for the client application.
const directories = {
client: path.join(__dirname, 'client'),
app: path.join(__dirname, 'app')
};
// The application they wish to install.
let application = '';
let templateFile = '';
/**
* Download a zip file.
*
* @param url
* @param zipFile
* @param dir
* @param done
* @returns {*}
*/
const download = function(url, zipFile, dir, done) {
// Check to see if the client already exists.
if (fs.existsSync(zipFile)) {
util.log(`${directories[dir]} file already exists, skipping download.`);
return done();
}
const request = require('request');
const ProgressBar = require('progress');
util.log(`Downloading ${dir}${'...'.green}`);
// Download the project.
let downloadError = null;
let tries = 0;
let bar = null;
(function downloadProject() {
request.get(url)
.on('response', function(res) {
if (
!res.headers.hasOwnProperty('content-disposition') ||
!parseInt(res.headers['content-length'], 10)
) {
if (tries++ > 3) {
return done('Unable to download project. Please try again.');
}
setTimeout(downloadProject, 200);
return;
}
// Setup the progress bar.
bar = new ProgressBar(' downloading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
width: 50,
total: parseInt(res.headers['content-length'], 10)
});
res.pipe(fs.createWriteStream(zipFile, {
flags: 'w'
}));
res.on('data', function(chunk) {
if (bar) {
bar.tick(chunk.length);
}
});
res.on('error', function(err) {
downloadError = err;
});
res.on('end', function() {
setTimeout(function() {
done(downloadError);
}, 100);
});
});
})();
};
/**
* Extract a download to a folder.
*
* @param zipFile
* @param fromDir
* @param dir
* @param done
* @returns {*}
*/
const extract = function(zipFile, fromDir, dir, done) {
// See if we need to extract.
if (fs.existsSync(directories[dir])) {
util.log(`${directories[dir]} already exists, skipping extraction.`);
return done();
}
// Unzip the contents.
const AdmZip = require('adm-zip');
util.log('Extracting contents...'.green);
const zip = new AdmZip(zipFile);
zip.extractAllTo('', true);
fs.move(fromDir, directories[dir], function(err) {
if (err) {
return done(err);
}
// Delete the zip file.
fs.remove(zipFile);
// Get the package json file.
let info = {};
try {
info = JSON.parse(fs.readFileSync(path.join(directories[dir], 'package.json')));
}
catch (err) {
debug(err);
return done(err);
}
// Set local variable to directory path.
let directoryPath = directories[dir];
// Change the document root if we need to.
if (info.formio && info.formio.docRoot) {
directoryPath = path.join(directories[dir], info.formio.docRoot);
}
if (!fs.existsSync(path.join(directoryPath, 'config.template.js'))) {
return done('Missing config.template.js file');
}
// Change the project configuration.
const config = fs.readFileSync(path.join(directoryPath, 'config.template.js'));
const newConfig = nunjucks.renderString(config.toString(), {
domain: formio.config.domain ? formio.config.domain : 'https://form.io'
});
fs.writeFileSync(path.join(directoryPath, 'config.js'), newConfig);
done();
});
};
// All the steps in the installation.
const steps = {
/**
* Step to perform the are you sure step.
*
* @param done
*/
areYouSure: function(done) {
prompt.get([
{
name: 'install',
description: 'Are you sure you wish to install? (y/N)',
required: true
}
], function(err, results) {
if (err) {
return done(err);
}
if (results.install.toLowerCase() !== 'y') {
return done('Installation canceled.');
}
done();
});
},
// Allow them to select the application.
whatApp: function(done) {
const repos = [
'None',
'https://github.com/formio/formio-app-humanresources',
'https://github.com/formio/formio-app-servicetracker',
'https://github.com/formio/formio-app-todo',
'https://github.com/formio/formio-app-salesquote',
'https://github.com/formio/formio-app-basic'
];
let message = '\nWhich Github application would you like to install?\n'.green;
_.each(repos, function(repo, index) {
message += ` ${index + 1}.) ${repo}\n`;
});
message += '\nOr, you can provide a custom Github repository...\n'.green;
util.log(message);
prompt.get([
{
name: 'app',
description: 'GitHub repository or selection?',
default: '1',
required: true
}
], function(err, results) {
if (err) {
return done(err);
}
if (results.app.indexOf('https://github.com/') !== -1) {
application = results.app;
}
else {
const selection = parseInt(results.app, 10);
if (_.isNumber(selection)) {
if ((selection > 1) && (selection <= repos.length)) {
application = repos[selection - 1];
}
}
}
// Replace github.com url.
application = application.replace('https://github.com/', '');
done();
});
},
/**
* Download the application.
*
* @param done
* @returns {*}
*/
downloadApp: function(done) {
if (!application) {
return done();
}
// Download the app.
download(
`https://nodeload.github.com/${application}/zip/master`,
'app.zip',
'app',
done
);
},
/**
* Extract the application to the app folder.
*
* @param done
* @returns {*}
*/
extractApp: function(done) {
if (!application) {
return done();
}
const parts = application.split('/');
const appDir = `${parts[1]}-master`;
extract('app.zip', appDir, 'app', done);
},
/**
* Download the Form.io admin client.
*
* @param done
* @returns {*}
*/
downloadClient: function(done) {
if (!items.download) {
return done();
}
// Download the client.
download(
'https://nodeload.github.com/formio/formio-app-formio/zip/master',
'client.zip',
'client',
done
);
},
/**
* Extract the client.
*
* @param done
* @returns {*}
*/
extractClient: function(done) {
if (!items.extract) {
return done();
}
extract('client.zip', 'formio-app-formio-master', 'client', done);
},
/**
* Select the template to use.
*
* @param done
* @return {*}
*/
whatTemplate: function(done) {
if (application) {
templateFile = 'app';
return done();
}
let message = '\nWhich project template would you like to install?\n'.green;
message += '\n Please provide the local file path of the project.json file.'.yellow;
message += '\n Or, just press '.yellow + 'ENTER'.green + ' to use the default template.\n'.yellow;
util.log(message);
prompt.get([
{
name: 'templateFile',
description: 'Local file path or just press Enter for default.',
default: 'client',
required: true
}
], function(err, results) {
if (err) {
return done(err);
}
templateFile = results.templateFile ? results.templateFile : 'client';
done();
});
},
/**
* Import the template.
* @param done
*/
importTemplate: function(done) {
if (!items.import) {
return done();
}
// Determine if this is a custom project.
const customProject = (['app', 'client'].indexOf(templateFile) === -1);
let directoryPath = '';
if (!customProject) {
directoryPath = directories[templateFile];
// Get the package json file.
let info = {};
try {
info = JSON.parse(fs.readFileSync(path.join(directoryPath, 'package.json')));
}
catch (err) {
debug(err);
return done(err);
}
// Change the document root if we need to.
if (info.formio && info.formio.docRoot) {
directoryPath = path.join(directoryPath, info.formio.docRoot);
}
}
const projectJson = customProject ? templateFile : path.join(directoryPath, 'project.json');
if (!fs.existsSync(projectJson)) {
util.log(projectJson);
return done('Missing project.json file'.red);
}
let template = {};
try {
template = JSON.parse(fs.readFileSync(projectJson));
}
catch (err) {
debug(err);
return done(err);
}
// Get the form.io service.
util.log('Importing template...'.green);
const importer = require('./src/templates/import')({formio: formio});
importer.template(template, function(err, template) {
if (err) {
return done(err);
}
project = template;
done(null, template);
});
},
/**
* Create the root user object.
*
* @param done
*/
createRootUser: function(done) {
if (!items.user) {
return done();
}
util.log('Creating root user account...'.green);
prompt.get([
{
name: 'email',
description: 'Enter your email address for the root account.',
pattern: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
message: 'Must be a valid email',
required: true
},
{
name: 'password',
description: 'Enter your password for the root account.',
require: true,
hidden: true
}
], function(err, result) {
if (err) {
return done(err);
}
util.log('Encrypting password');
formio.encrypt(result.password, function(err, hash) {
if (err) {
return done(err);
}
// Create the root user submission.
util.log('Creating root user account');
formio.resources.submission.model.create({
form: project.resources.admin._id,
data: {
email: result.email,
password: hash
},
roles: [
project.roles.administrator._id
]
}, function(err, item) {
if (err) {
return done(err);
}
done();
});
});
});
}
};
util.log('Installing...');
prompt.start();
async.series([
steps.areYouSure,
steps.whatApp,
steps.downloadApp,
steps.extractApp,
steps.downloadClient,
steps.extractClient,
steps.whatTemplate,
steps.importTemplate,
steps.createRootUser
], function(err, result) {
if (err) {
util.log(err);
return done(err);
}
util.log('Install successful!'.green);
done();
});
};