forked from astefanutti/decktape
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecktape.js
410 lines (372 loc) · 13.9 KB
/
decktape.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
const fs = require('fs'),
hummus = require('hummus'),
os = require('os'),
parser = require('./libs/nomnom'),
puppeteer = require('puppeteer');
const plugins = loadAvailablePlugins('./plugins/');
parser.script('decktape')
.options({
url: {
position : 1,
required : true,
help : 'URL of the slides deck'
},
filename: {
position : 2,
required : true,
help : 'Filename of the output PDF file'
},
size: {
abbr : 's',
metavar : '<size>',
type : 'string',
callback : parseSize,
transform : parseSize,
help : 'Size of the slides deck viewport: <width>x<height> (ex. 1280x720)'
},
pause: {
abbr : 'p',
metavar : '<ms>',
default : 1000,
help : 'Duration in milliseconds before each slide is exported'
},
loadPause: {
full : "load-pause",
metavar : '<ms>',
default : 0,
help : 'Duration in milliseconds between the page has loaded and starting to export slides'
},
screenshots: {
default : false,
flag : true,
help : 'Capture each slide as an image'
},
screenshotDirectory: {
full : 'screenshots-directory',
metavar : '<dir>',
default : 'screenshots',
help : 'Screenshots output directory'
},
screenshotSize: {
full : 'screenshots-size',
metavar : '<size>',
type : 'string',
list : true,
callback : parseSize,
transform : parseSize,
help : 'Screenshots resolution, can be repeated'
},
screenshotFormat: {
full : 'screenshots-format',
metavar : '<format>',
default : 'png',
choices : ['jpg', 'png'],
help : 'Screenshots image format, one of [jpg, png]'
},
slides: {
metavar : '<range>',
type : 'string',
callback : parseRange,
transform : parseRange,
help : 'Range of slides to be exported, a combination of slide indexes and ranges (e.g. \'1-3,5,8\')'
}
});
function parseSize(size) {
// TODO: support device viewport sizes and graphics display standard resolutions
// see http://viewportsizes.com/ and https://en.wikipedia.org/wiki/Graphics_display_resolution
var match = size.match(/^(\d+)x(\d+)$/);
if (!match)
return '<size> must follow the <width>x<height> notation, e.g., 1280x720';
else
return { width: match[1], height: match[2] };
}
function parseRange(range) {
var regex = /(\d+)(?:-(\d+))?/g;
if (!range.match(regex))
return '<range> must be a combination of slide indexes and ranges, e.g., \'1-3,5,8\'';
var slide;
var slides = {};
while ((slide = regex.exec(range)) !== null)
if (typeof slide[2] !== 'undefined')
for (var i = parseInt(slide[1]); i <= parseInt(slide[2]); i++)
slides[i] = true;
else
slides[parseInt(slide[1])] = true;
return slides;
}
parser.nocommand()
.help('Defaults to the automatic command.\n' +
'Iterates over the available plugins, picks the compatible one for presentation at the \n' +
'specified <url> and uses it to export and write the PDF into the specified <filename>.');
parser.command('automatic')
.help('Iterates over the available plugins, picks the compatible one for presentation at the \n' +
'specified <url> and uses it to export and write the PDF into the specified <filename>.');
Object.keys(plugins).forEach(function (id) {
var command = parser.command(id);
if (typeof plugins[id].options === 'object')
command.options(plugins[id].options);
if (typeof plugins[id].help === 'string')
command.help(plugins[id].help);
});
// TODO: should be deactivated as well when it does not execute in a TTY context
if (os.name === 'windows')
parser.nocolors();
var options = parser.parse(process.argv.slice(2));
(async() => {
// TODO: support passing args to the the Chromium instance
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
const pdfWriter = hummus.createWriter(options.filename);
page.onLoadStarted = function () {
console.log('Loading page ' + options.url + ' ...');
};
page.onResourceTimeout = function (request) {
console.log('+- Request timeout: ' + JSON.stringify(request));
};
page.onResourceError = function (resource) {
console.log('+- Unable to load resource from URL: ' + resource.url);
console.log('|_ Error code: ' + resource.errorCode);
console.log('|_ Description: ' + resource.errorString);
};
// PhantomJS emits this event for both pages and frames
page.onLoadFinished = function (status) {
console.log('Loading page finished with status: ' + status);
};
page.on('console', (...args) => console.log(args));
page.onError = function (msg, trace) {
console.log('+- ' + msg);
(trace || []).forEach(function (t) {
console.log('|_ ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
};
page.goto(options.url, { waitUntil: 'load', timeout: 60000 })
.then(removeCssPrintStyles)
.then(delay(options.loadPause))
.then(createPlugin)
.then(configurePlugin)
.then(configurePrinter)
.then(exportSlides)
.then(plugin => {
pdfWriter.end();
process.stdout.write(`\nPrinted ${plugin.exportedSlides} slides\n`);
browser.close();
process.exit();
})
.catch(error => {
console.log(error);
browser.close();
process.exit(1);
});
// Can be removed when Puppeteer supports setting media type in rendering emulation
// See: https://github.com/GoogleChrome/puppeteer/issues/312
function removeCssPrintStyles() {
return page.evaluate(_ => {
// if (!document.styleSheets) return;
for (let j = 0; j < document.styleSheets.length; j++) {
const sheet = document.styleSheets[j];
if (!sheet.rules) continue;
for (let i = sheet.rules.length - 1; i >= 0; i--) {
if (sheet.rules[i].cssText.indexOf('@media print') !== -1) {
sheet.deleteRule(i);
} else if (sheet.rules[i].cssText.indexOf('@media screen') !== -1) {
const rule = sheet.rules[i].cssText;
sheet.deleteRule(i);
sheet.insertRule(rule.replace('@media screen', '@media all'), i);
}
}
}
});
}
async function createPlugin() {
var plugin;
if (!options.command || options.command === 'automatic') {
plugin = await createActivePlugin();
if (!plugin) {
console.log('No supported DeckTape plugin detected, falling back to generic plugin');
plugin = plugins['generic'].create(page, options);
}
} else {
plugin = plugins[options.command].create(page, options);
if (!await plugin.isActive()) {
throw Error('Unable to activate the ' + plugin.getName() + ' DeckTape plugin for the address: ' + options.url);
}
}
console.log(plugin.getName() + ' DeckTape plugin activated');
return plugin;
}
async function createActivePlugin() {
for (var id in plugins) {
if (id === 'generic')
continue;
var plugin = plugins[id].create(page, options);
if (await plugin.isActive())
return plugin;
}
}
function configurePrinter(plugin) {
if (!options.size)
if (typeof plugin.size === 'function')
options.size = plugin.size();
else
// TODO: per-plugin default size
options.size = { width: 1280, height: 720 };
page.setViewport({ width: options.size.width, height: options.size.height });
return plugin;
}
// TODO: ideally defined in the plugin prototype
async function printSlide(plugin) {
const buffer = await page.pdf({
width: options.size.width + 'px',
height: options.size.height + 'px',
printBackground: true,
pageRanges: '1',
displayHeaderFooter: false,
});
pdfWriter.appendPDFPagesFromPDF(new BufferReader(buffer), { specificRanges: [[0, 0]] });
plugin.exportedSlides++;
return buffer;
}
function exportSlides(plugin) {
// TODO: support a more advanced "fragment to pause" mapping for special use cases like GIF animations
// TODO: support plugin optional promise to wait until a particular mutation instead of a pause
return Promise.resolve(plugin)
.then(delay(options.pause))
.then(exportSlide)
.then(hasNextSlide)
.then(function (hasNext) {
if (hasNext && (!options.slides || plugin.currentSlide < Math.max.apply(null, Object.keys(options.slides)))) {
nextSlide(plugin);
return exportSlides(plugin);
} else {
return plugin;
}
});
}
async function exportSlide(plugin) {
// TODO: better logging when slide is skipped and move it to the main loop
process.stdout.write('\r' + await progressBar(plugin));
if (options.slides && !options.slides[plugin.currentSlide])
return Promise.resolve(plugin);
var decktape = Promise.resolve(plugin).then(printSlide);
if (options.screenshots)
decktape = (options.screenshotSize || [options.size]).reduce(function (decktape, resolution) {
return decktape.then(function () { page.viewportSize = resolution })
// Delay page rendering to wait for the resize event to complete,
// e.g. for impress.js (may be needed to be configurable)
.then(delay(1000))
.then(function () {
page.render(options.screenshotDirectory + '/' + options.filename.replace('.pdf', '_' + plugin.currentSlide + '_' + resolution.width + 'x' + resolution.height + '.' + options.screenshotFormat), { onlyViewport: true });
})
}, decktape)
.then(function () { page.viewportSize = options.size })
.then(delay(1000));
return decktape.then(value(plugin));
}
})();
function loadAvailablePlugins(pluginPath) {
return fs.readdirSync(pluginPath).reduce(function (plugins, plugin) {
var matches = plugin.match(/^(.*)\.js$/);
if (matches && fs.statSync(pluginPath + plugin).isFile())
plugins[matches[1]] = require(pluginPath + matches[1]);
return plugins;
}, {});
}
function configurePlugin(plugin) {
var config;
if (typeof plugin.configure === 'function')
config = Promise.resolve(plugin.configure()).then(value(plugin));
else
config = Promise.resolve(plugin);
return config.then(async function (plugin) {
plugin.progressBarOverflow = 0;
plugin.currentSlide = 1;
plugin.exportedSlides = 0;
plugin.totalSlides = await plugin.slideCount();
return plugin;
});
}
// TODO: ideally defined in the plugin prototype
function hasNextSlide(plugin) {
if (typeof plugin.hasNextSlide === 'function')
return plugin.hasNextSlide();
else
return plugin.currentSlide < plugin.totalSlides;
}
// TODO: ideally defined in the plugin prototype
function nextSlide(plugin) {
plugin.currentSlide++;
return plugin.nextSlide();
}
function delay(time) {
return function (value) {
return new Promise(function (fulfill) {
setTimeout(fulfill, time, value);
});
}
}
function value(value) {
return function () {
return value;
}
}
// TODO: add progress bar, duration, ETA and file size
async function progressBar(plugin) {
var cols = [];
var index = await plugin.currentSlideIndex();
cols.push('Printing slide ');
cols.push(padding('#' + index, 8, ' ', false));
cols.push(' (');
cols.push(padding(plugin.currentSlide, plugin.totalSlides ? plugin.totalSlides.toString().length : 3, ' '));
cols.push('/');
cols.push(plugin.totalSlides || ' ?');
cols.push(') ...');
// erase overflowing slide fragments
cols.push(padding('', plugin.progressBarOverflow - Math.max(index.length + 1 - 8, 0), ' ', false));
plugin.progressBarOverflow = Math.max(index.length + 1 - 8, 0);
return cols.join('');
}
function padding(str, len, char, left) {
if (typeof str === 'number')
str = str.toString();
var l = len - str.length;
var p = [];
while (l-- > 0)
p.push(char);
return left === undefined || left ?
p.join('').concat(str) :
str.concat(p.join(''));
}
class BufferReader {
constructor(buffer) {
this.rposition = 0;
this.buffer = buffer;
}
read(inAmount) {
var arr = [];
const amount = this.rposition + inAmount;
if (amount > this.buffer.length) {
amount = this.buffer.length - this.rposition;
}
for (var i = this.rposition; i < amount; ++i)
arr.push(this.buffer[i]);
this.rposition = amount;
return arr;
}
notEnded() {
return this.rposition < this.buffer.length;
}
setPosition(inPosition) {
this.rposition = inPosition;
}
setPositionFromEnd(inPosition) {
this.rposition = this.buffer.length - inPosition;
}
skip(inAmount) {
this.rposition += inAmount;
}
getCurrentPosition() {
return this.rposition;
}
close() {
}
}