-
Notifications
You must be signed in to change notification settings - Fork 16
/
cli.js
executable file
·542 lines (455 loc) · 15.5 KB
/
cli.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
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
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const readline = require('readline');
// const conf = require('conf');
const chalk = require('chalk');
const envPaths = require('env-paths');
const flatten = require('lodash/flatten');
const find = require('lodash/find');
const Fuse = require('fuse.js');
const getStream = require('get-stream');
const globby = require('globby');
const got = require('got');
const inquirer = require('inquirer');
const isStream = require('is-stream');
const isUrl = require('is-url-superb');
const Jimp = require('jimp');
const logSymbols = require('log-symbols');
const meow = require('meow');
const mkdirp = require('mkdirp');
const ora = require('ora');
const ProgressBar = require('progress');
const puppeteer = require('puppeteer');
const some = require('lodash/some');
const typeis = require('type-is');
const uniq = require('lodash/uniq');
const frameData = require('./data/frames.json');
const paths = envPaths('deviceframe');
const frameCacheDir = path.join(paths.cache, 'frames');
const webCacheDir = path.join(paths.cache, 'web');
readline.emitKeypressEvents(process.stdin);
/* ------ */
// Help text
const cli = meow(
`
Usage
# Pass in any number of image files (globs allows), image urls, or website urls:
$ dframe <image>
$ dframe <url
$ dframe <ul> <image> <url> <image url> <image>
Options
--delay Delay webpage capturing in seconds
--output, -o Output directory (default: current working directory)
--debug, -d Log debug info
--devices List all available devices
--frame Supply a frame to use. Fuzzy matches. Use multiple --frame switches for multiple frames or use commas. See below for examples.
Examples
$ dframe cat.png
$ dframe cat.png dog.png horse.jpg
$ dframe *.png cat-*.jpeg
$ dframe https://github.com/c0bra/deviceframe --delay 2
$ dframe cat.png https://github.com/c0bra/deviceframe *.bmp https://i.imgur.com/aw2bc01.jpg
$ dframe cat.png --frame "iPhone 7"
$ dframe cat.png --frame "iPhone 6" --frame "iPhone 7"
$ dframe cat.png --frame "iphone 6","iphone 7"
`,
{
flags: {
help: {
alias: 'h',
},
delay: {
default: 0,
},
devices: {
default: false,
},
output: {
type: 'string',
alias: 'o',
default: '.',
},
debug: {
type: 'boolean',
alias: 'd',
default: false,
},
},
}
);
const framesRepo = cli.pkg.devDependencies['deviceframe-frames'];
const framesVersion = framesRepo.match(/#(.+)$/)[1];
// const framesUrl = 'https://gitcdn.xyz/repo/c0bra/deviceframe-frames/1.0.0/';
const framesUrl = `https://cdn.rawgit.com/c0bra/deviceframe-frames/${framesVersion}/`;
// Log out list of devices
if (cli.flags.devices) {
console.log(
uniq(frameData.map(x => x.device)).sort().join('\n')
);
process.exit(0);
}
// Parse frames args
if (cli.flags.frame && typeof cli.flags.frame === 'string') {
cli.flags.frame = [].concat(cli.flags.frame.split(/,/).map(f => f.trim()));
}
// console.log('frames', cli.flags.frame); process.exit(0);
// Find matching frames
let frames = null;
if (cli.flags.frame) {
const fuse = new Fuse(frameData, {
shouldSort: true,
tokenize: true,
matchAllTokens: true,
threshold: 0,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: ['name'],
});
const results = [];
cli.flags.frame.forEach(f => {
// See if we can match exactly
const exact = find(frameData, { name: f });
if (exact) {
results.push(exact);
} else {
const res = fuse.search(f);
if (res) results.push(res[0]);
}
});
frames = uniq(results);
if (!frames) error('Could not find any matching frames');
}
/*
1. Init (read in cache dir and conf)
2. Process image paths, urls and confirm w/ user
3. Prompt user for frames
4. Process each image through each frame, writing each out
*/
Promise.resolve()
.then(init)
.then(confirmInputs)
.then(([files, urls]) => {
return chooseFrames()
.then(frames => [files, urls, frames]);
})
.then(([files, urls, frames]) => {
return downloadFrames(frames)
.then(frames => [files, urls, frames])
.catch(err => error(err));
})
.then(([files, urls, frames]) => frameImages(files, urls, frames))
.catch(err => error(err));
/* ------------------------------------------------------------------------- */
function init() {
debug('Init...');
// Add shadow suffix on to frame name
frameData.forEach(frame => {
if (frame.shadow) frame.name = `${frame.name} [shadow]`;
});
mkdirp(frameCacheDir, err => {
if (err) console.error(chalk.red(err));
// NOTE: not used
// const files = fs.readdirSync(frameCacheDir);
// return files;
});
mkdirp(webCacheDir, err => {
if (err) console.error(chalk.red(err));
});
}
function confirmInputs() {
const urls = cli.input.filter(f => isUrl(f));
// Find image files to frame from input
return globImageFiles(cli.input.filter(f => !isUrl(f)))
.then(files => {
if (files.length === 0 && urls.length === 0) error('No image files or urls specified', true);
return [files, urls];
});
}
function chooseFrames() {
if (frames) return Promise.resolve(frames);
debug('Choosing frames');
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'));
return new Promise(resolve => {
const ui = new inquirer.ui.BottomBar();
let frames = [];
let prompt = null;
function prompter() {
prompt = inquirer.prompt({
type: 'autocomplete',
name: 'frames',
message: 'Add the frames you want to use (ESC to complete)',
source: (answers, input) => {
input = input || '';
input = input.toLowerCase();
return Promise.resolve(
frameData.map(f => f.name.toLowerCase()).filter(name => name.indexOf(input) !== -1)
);
},
});
prompt.then(answers => {
const foundFrames = frameData.filter(frame => some(answers, a => a === frame.name.toLowerCase()));
frames = uniq(frames.concat(foundFrames));
ui.log.write(chalk.magenta(`\nFrames: [${frames.map(f => chalk.bold(f.name)).join(', ')}]\n`));
prompter();
});
}
prompter();
// Resolve promise on ESC key
process.stdin.on('keypress', (ch, key) => {
if (key && key.name === 'escape') {
prompt.ui.close();
console.log('\n');
resolve(frames);
}
});
});
}
function frameImages(files, urls, frames) {
let promises = files.map(file => {
return frames.map(frame => {
return frameIt(file, frame);
});
});
promises = promises.concat(
urls.map(url => {
return frames.map(frame => frameIt(url, frame));
})
);
return promises;
}
// function setup() {
// inquirer.prompt([{
// name: 'download',
// type: 'confirm',
// message: `Looks like we're running for the first time. deviceframe needs to download the frameset images. This is about 185MB. Sound good?`,
// default: true,
// }]).then(answers => {
// if (answers.download) downloadFrames();
// });
// }
function globImageFiles(inputs) {
if (!inputs || inputs.length === 0) return Promise.resolve([]);
const ps = inputs.map(file => {
return globby(file);
});
return Promise.all(ps).then(results => flatten(results));
}
function downloadFrames(frames) {
debug('Downloading frames');
// console.log('frames', frames);
const promises = [];
for (const frame of frames) {
const frameCachePath = path.join(frameCacheDir, frame.relPath);
if (fs.existsSync(frameCachePath) && fs.statSync(frameCachePath).size > 0) {
debug(`Frame found at ${frameCachePath}`);
frame.path = frameCachePath;
promises.push(frame);
} else {
if (fs.existsSync(frameCachePath)) fs.unlink(frameCachePath);
frame.url = framesUrl + frame.relPath; // encodeURIComponent(frame.relPath);
promises.push(downloadFrame(frame));
}
}
return Promise.all(promises).then(results => flatten(results));
}
function downloadFrame(frame) {
debug(`Downloading frame ${frame.url}`);
const bar = new ProgressBar(`Downloading frame ${chalk.green(frame.name)} [:bar] :rate/bps :percent :etas`, {
complete: '=',
incomplete: ' ',
width: 20,
total: 100,
});
bar.tick();
frame.path = path.join(frameCacheDir, frame.relPath);
const downloadDir = path.parse(frame.path).dir;
mkdirp.sync(downloadDir);
return new Promise((resolve, reject) => {
got.stream(frame.url, {
headers: {
'user-agent': `deviceframe/${cli.pkg.version} (${cli.pkg.repo})`,
},
})
.on('end', () => {
bar.tick(100);
resolve(frame);
})
.on('downloadProgress', progress => {
console.log('progress.percent', progress.percent);
bar.tick(progress.percent * 100);
})
.on('error', error => {
if (fs.existsSync(frame.path)) fs.unlink(frame.path);
console.log(require('util').inspect(error, { depth: null }));
reject(error);
})
.pipe(fs.createWriteStream(frame.path));
});
}
function frameIt(img, frameConf) {
debug('Framing images');
// TODO: use filenamify here?
// Get the writeable file name for the image
let imgName = '';
if (typeof img === 'string') {
const p = path.parse(img);
imgName = `${p.name}-${frameConf.name}.png`;
} else {
imgName = `Frame-${frameConf.name}.png`;
}
const imgPath = path.join(cli.flags.output, imgName);
if (isStream(img)) {
img = getStream.buffer(img);
} else if (isUrl(img)) {
// Check if url is for an image or for a webpage
const urlCachePath = path.join(webCacheDir, imgName);
debug(`Checking url cache: ${urlCachePath}`);
// NOTE: for urls we need to cache them
const imgUrl = img;
debug(`Checking for image: ${imgUrl}`);
img = got(img, { encoding: null })
.then(response => {
if (typeis(response, ['image/*'])) return response.body;
// Scale image size for device pixel density
const pixelRatio = frameConf.pixelRatio;
const w = Math.floor(frameConf.frame.width / 1);
const h = Math.floor(frameConf.frame.height / 1);
const dim = [w, h].join('x');
const spinner = ora(`ing ${imgUrl} at ${dim}`).start();
// TODO: need to dynamically choose device user-agent from a list, or store them with the frames
const delay = 1000 || cli.flags.delay * 1000;
const bufPromise = new Promise((resolve, reject) => {
puppeteer.launch().then(browser => {
browser.newPage()
.then(page => {
page.goto(imgUrl);
const shot = () => {
page.setViewport({
width: w,
height: h,
deviceScaleFactor: pixelRatio,
});
page.screenshot().then(buffer => {
spinner.succeed();
browser.close();
resolve(buffer);
}).catch(err => {
spinner.fail();
browser.close();
reject(err);
});
};
const onload = () => {
setTimeout(shot, delay);
};
page.on('load', onload);
})
.catch(err => {
spinner.fail();
reject(err);
});
});
});
return Promise.all([bufPromise, w, h]);
})
.then(([buf, w, h]) => new Promise((resolve, reject) => {
Jimp.read(buf)
.then(lenna => {
lenna.resize(w, Jimp.AUTO)
.crop(0, 0, w, h)
.getBuffer(Jimp.MIME_PNG, (err, result) => {
if (err) return reject(err);
resolve(result);
});
});
}))
.catch(err => error(err));
}
// Read in image and frame
return Promise.resolve(img)
.then(imgData => {
const framePath = path.join(frameCacheDir, frameConf.relPath);
debug(`Reading in frame from ${framePath}`);
return Promise.all([
Jimp.read(framePath),
Jimp.read(imgData),
]);
})
// Resize largest image to fit the other
.then(([frame, jimg]) => {
debug('Resizing frame/image');
const frameImageWidth = frame.bitmap.width;
const frameImageHeight = frame.bitmap.height;
const compLeftRatio = frameConf.frame.left / frameImageWidth;
const compTopRatio = frameConf.frame.top / frameImageHeight;
let compLeft = frameConf.frame.left;
let compTop = frameConf.frame.top;
const frameMax = Math.max(frameConf.frame.height, frameConf.frame.width);
const jimgMax = Math.max(jimg.bitmap.height, jimg.bitmap.width);
// Frame is bigger, size it down to source image
if (frameMax > jimgMax) {
// Resize frame so shortest dimension matches source image. Source image overflow will be clipped
let rH = frame.bitmap.height;
let rW = frame.bitmap.width;
if (frameConf.frame.height > frameConf.frame.width) {
const ratio = jimg.bitmap.width / frameConf.frame.width;
rW = Math.ceil(rW * ratio);
rH = Jimp.AUTO;
} else {
const ratio = jimg.bitmap.height / frameConf.frame.height;
rH = Math.ceil(rH * ratio);
rW = Jimp.AUTO;
}
frame.resize(rW, rH);
// We resized the frame so there's a new compositing location on it
compLeft = Math.ceil(frame.bitmap.width * compLeftRatio);
compTop = Math.ceil(frame.bitmap.height * compTopRatio);
// Resize source image to fit new frame size
const newFrameWidth = frameConf.frame.width * (frame.bitmap.width / frameImageWidth);
const newFrameHeight = frameConf.frame.height * (frame.bitmap.height / frameImageHeight);
jimg.cover(newFrameWidth, newFrameHeight);
} else {
// Source image is bigger, size it down to frame
// Resize frame so shortest dimension matches
let rH = jimg.bitmap.height;
let rW = jimg.bitmap.width;
if (rH > rW) {
rW = frameConf.frame.width;
rH = Jimp.AUTO;
} else {
rH = frameConf.frame.height;
rW = Jimp.AUTO;
}
jimg.cover(frameConf.frame.width, frameConf.frame.height);
}
return [frame, jimg, { left: compLeft, top: compTop }, frameConf];
})
.then(([frame, jimg, compPos, frameConf]) => {
debug(`Compositing... ${frameConf.frame.left} ${frameConf.frame.top}`);
// Create a canvas the same as the frame size for the screenshot to be placed on at the frame top/left coordinates
const canvas = new Jimp(frame.bitmap.width, frame.bitmap.height);
jimg = canvas.composite(jimg, compPos.left, compPos.top);
return jimg.composite(frame, 0, 0);
})
.then(composite => {
debug('Saving...');
composite.write(imgPath);
console.log(chalk.bold('> ') + chalk.green('Wrote: ') + imgPath);
})
.catch(err => error(err));
}
// function cacheSettings(settings) {
// // TODO: write settings to ~/.deviceframe/settings.json
// }
function error(msg, usage) {
if (usage) console.log(cli.help);
console.error('\n' + logSymbols.error + ' ' + chalk.red(msg));
process.exit(1);
}
function debug(...args) {
if (cli.flags.debug) console.log(chalk.green(...args));
}