-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcontroller.js
820 lines (718 loc) · 27.6 KB
/
controller.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
const puppeteer = require('puppeteer-core');
const sharp = require('sharp');
const scroller = require('puppeteer-autoscroll-down');
const {Logger, NullLogger} = require("./logging");
const devices = puppeteer.KnownDevices;
const FORMAT_JPEG = 'jpeg';
const FORMAT_PNG = 'png';
const MAX_JPEG_DIMENSION_SIZE = 16384;
// The smaller stack size of musl libc means libvips may need to be used without a cache via
sharp.cache(false) // to avoid a stack overflow
/** @type {string|null} */
let browserVersion = null;
/** @type {string|null} */
let defaultUserAgent = null;
/**
*
* @param browser
* @param req
* @param res
* @param {(Cache|null)} cache
* @return {Promise<void>}
*/
module.exports = async (browser, req, res, cache) => {
/** @type {Logger} */
const logger = req.logger || new NullLogger();
if (!browserVersion) {
try {
browserVersion = await browser.version();
} catch (e) {
logger.error(e);
res.status(500).end('Error while fetching browser version: ' + e.message);
return;
}
logger.debug('Browser version:', browserVersion);
}
if (!defaultUserAgent) {
try {
defaultUserAgent = (await browser.userAgent()).replace("HeadlessChrome", "Chrome");
} catch (e) {
logger.error(e);
res.status(500).end('Error while fetching a default user agent: ' + e.message);
return;
}
logger.debug('Default user agent:', defaultUserAgent);
}
logger.debug('Request Query Args:', req.query);
/**
* https://pptr.dev/api/puppeteer.page.emulatetimezone
* https://github.com/unicode-org/icu/blob/main/icu4c/source/data/misc/metaZones.txt
*/
let timezone = req.query.timezone;
let url = req.query.url;
let device = req.query.device && typeof req.query.device === "string"
? req.query.device
: null;
let viewportWidth = parseInt(req.query['viewport-width']) > 0
? parseInt(req.query['viewport-width'])
: null;
let viewportHeight = parseInt(req.query['viewport-height']) > 0
? parseInt(req.query['viewport-height'])
: null;
let deviceScaleFactor = parseInt(req.query['device-scale-factor'])
? parseInt(req.query['device-scale-factor'])
: null;
let isMobile = typeof req.query['is-mobile'] === "string"
? !!parseInt(req.query['is-mobile'])
: null;
let hasTouch = typeof req.query['has-touch'] === "string"
? !!parseInt(req.query['has-touch'])
: null;
let isLandscape = typeof req.query['is-landscape'] === "string"
? !!parseInt(req.query['is-landscape'])
: null;
let userAgent = typeof req.query['user-agent'] === "string"
? req.query['user-agent']
: null;
let cookies = typeof req.query['cookies'] === "string"
? req.query['cookies']
: null;
let navigationTimeoutMs = typeof req.query['navigation-timeout-ms'] === "string" && req.query['navigation-timeout-ms'] && parseInt(req.query['navigation-timeout-ms']) >= 0
? parseInt(req.query['navigation-timeout-ms'])
: null;
/**
* @deprecated Use navigationTimeoutMs instead
* @type {number|null}
*/
let timeout = parseInt(req.query.timeout) >= 0
? parseInt(req.query.timeout)
: null;
if (!navigationTimeoutMs && timeout) {
navigationTimeoutMs = timeout;
}
let failOnTimeout = !!parseInt(req.query['fail-on-timeout'])
let waitUntilEvent = req.query['wait-until-event'];
let waitForSelector = req.query['wait-for-selector'];
let waitForSelectorTimeoutMs = typeof req.query['wait-for-selector-timeout-ms'] === "string" && req.query['wait-for-selector-timeout-ms'] && parseInt(req.query['wait-for-selector-timeout-ms']) >= 0
? parseInt(req.query['wait-for-selector-timeout-ms'])
: null;
let failOnWaitForSelectorTimeout = !!parseInt(req.query['fail-on-wait-for-selector-timeout']);
let waitForXPath = req.query['wait-for-xpath'];
let waitForXPathTimeoutMs = typeof req.query['wait-for-xpath-timeout-ms'] === "string" && req.query['wait-for-xpath-timeout-ms'] && parseInt(req.query['wait-for-xpath-timeout-ms']) >= 0
? parseInt(req.query['wait-for-xpath-timeout-ms'])
: null;
let failOnWaitForXPathTimeout = !!parseInt(req.query['fail-on-wait-for-xpath-timeout']);
let waitForFunction = req.query['wait-for-function'];
let waitForFunctionTimeoutMs = typeof req.query['wait-for-function-timeout-ms'] === "string" && req.query['wait-for-function-timeout-ms'] && parseInt(req.query['wait-for-function-timeout-ms']) >= 0
? parseInt(req.query['wait-for-function-timeout-ms'])
: null;
/** @type {'raf'|'mutation'|number|null} */
let waitForFunctionPolling = typeof req.query['wait-for-function-polling'] === "string" && req.query['wait-for-function-polling']
? (
['raf', 'mutation'].indexOf(req.query['wait-for-function-polling']) > -1
? req.query['wait-for-function-polling']
: (
req.query['wait-for-function-polling'].match(/[\d+]/)
? parseInt(req.query['wait-for-function-polling'])
: null
)
)
: null;
let failOnWaitForFunctionTimeout = !!parseInt(req.query['fail-on-wait-for-function-timeout']);
let delayMs = parseInt(req.query['delay-ms']) > 0
? parseInt(req.query['delay-ms'])
: null;
/**
* @deprecated Use delaysMs
* @type {number|null}
*/
let delay = parseInt(req.query.delay) > 0
? parseInt(req.query.delay)
: null;
if (!delayMs && delay) {
delayMs = delay;
}
let format = [FORMAT_PNG, FORMAT_JPEG].indexOf(req.query.format) > -1
? req.query.format
: FORMAT_PNG;
let quality = Math.abs(parseInt(req.query.quality) % 100)
? Math.abs(parseInt(req.query.quality) % 100)
: null;
let fullPage = !!parseInt(req.query.full);
let element = req.query.element;
let transparency = !!parseInt(req.query.transparency);
let captureBeyondViewport = !!parseInt(req.query['capture-beyond-viewport']);
let scrollPageToBottom = typeof req.query['scroll-page-to-bottom'] === "string"
? !!parseInt(req.query['scroll-page-to-bottom'])
: null;
let scrollPageToBottomSize = parseInt(req.query['scroll-page-to-bottom-size']) > 0
? parseInt(req.query['scroll-page-to-bottom-size'])
: null;
let scrollPageToBottomDelayMs = parseInt(req.query['scroll-page-to-bottom-delay-ms']) > 0
? parseInt(req.query['scroll-page-to-bottom-delay-ms'])
: null;
let scrollPageToBottomStepsLimit = parseInt(req.query['scroll-page-to-bottom-steps-limit']) > 0
? parseInt(req.query['scroll-page-to-bottom-steps-limit'])
: null;
let width = parseInt(req.query['width']) > 0
? parseInt(req.query['width'])
: null;
let maxHeight = parseInt(req.query['max-height']) > 0
? parseInt(req.query['max-height'])
: null;
/** @type {number|null} */
let ttl = parseInt(req.query.ttl) > 0
? parseInt(req.query.ttl)
: null;
if (!url) {
res.status(400).end('Missed url param');
return;
}
if (device && !devices[device]) {
let supported = Object.getOwnPropertyNames(devices).filter(device => {
return device !== 'length' && device !== '0' && isNaN(parseInt(device));
});
res.status(400).end('Unsupported device, supported: ' + supported.join(', '));
return;
}
/*if (device &&(viewportWidth || viewportHeight || deviceScaleFactor || typeof isMobile === "boolean" || typeof hasTouch === "boolean" || typeof isLandscape === "boolean")) {
res.status(400).end('Args "device" and at least one of ' +
'"viewport-width", "viewport-height", "device-scale-factor", "is-mobile", "has-touch", "is-landscape" ' +
'are exclusive');
return;
}*/
if (element && fullPage) {
res.status(400).end('Args "element" and "full" are exclusive');
return;
}
let cacheKey = (() => {
const query = JSON.parse(JSON.stringify(req.query));
delete query.ttl;
let entries = Object.entries(query).map(entry => entry[0] + '=' + entry[1]);
entries.sort();
return `|${entries.join('|')}|`;
})();
/** @type {(ReadableStream|Buffer|null)} */
let image;
if (cache) {
logger.debug('Fetching the entry from the cache', {
'key': cacheKey,
'cache': cache.describe(),
});
try {
image = await cache.get(cacheKey, ttl);
} catch (err) {
logger.error("Error while fetching a cache entry", err);
}
}
if (image) {
logger.debug('Cache contains the entry', {
'key': cacheKey,
'cache': cache.describe(),
});
res.writeHead(200, {
'Content-Type': 'image/' + format,
'Cache-Control': 'max-age=' + (ttl || 0),
'Content-Disposition': 'inline; filename=screenshot.' + format,
'X-Browser-Version': browserVersion,
'X-Cache-Status': 'hit',
});
image.pipe(res);
return;
}
if (cache) {
logger.debug('Cache does not contain the entry', {
'key': cacheKey,
'cache': cache.describe(),
});
}
let context;
try {
context = await browser.createBrowserContext();
} catch (e) {
logger.error(e);
res.status(400).end('Error while creating a new browser context: ' + e.message);
return;
}
let page;
try {
// https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#class-page
page = await context.newPage();
} catch (e) {
logger.error(e);
res.status(400).end('Error while creating a new page: ' + e.message);
return;
}
page.on('error', (e) => {
logger.error(e);
res.status(400).end('Page crashed!');
page.close();
context.close();
});
if (timezone) {
try {
await page.emulateTimezone(timezone);
} catch (e) {
logger.error('Error while setting timezone: ' + e.message);
res.status(400).end('Error while setting timezone: ' + e.message);
await page.close();
await context.close();
return;
}
}
let viewport = {};
if (device) {
viewport = JSON.parse(JSON.stringify(devices[device].viewport));
if (!userAgent) {
userAgent = devices[device].userAgent;
}
}
if (viewportWidth !== null) {
viewport.width = viewportWidth;
} else if (!viewport.width) {
viewport.width = 800;
}
if (viewportHeight !== null) {
viewport.height = viewportHeight;
} else if (!viewport.height) {
viewport.height = 600;
}
if (deviceScaleFactor !== null) {
viewport.deviceScaleFactor = deviceScaleFactor;
} else if (!viewport.deviceScaleFactor) {
viewport.deviceScaleFactor = 1;
}
if (isMobile !== null) {
viewport.isMobile = isMobile;
} else if (!viewport.isMobile) {
viewport.isMobile = false;
}
if (hasTouch !== null) {
viewport.hasTouch = hasTouch;
} else if (!viewport.hasTouch) {
viewport.hasTouch = false;
}
if (isLandscape !== null) {
viewport.isLandscape = isLandscape;
} else if (!viewport.isLandscape) {
viewport.isLandscape = false;
}
logger.debug('Setting viewport', viewport);
try {
await page.setViewport(viewport);
} catch (e) {
logger.error(e);
res.status(400).end('Error while setting viewport: ' + e.message);
await page.close();
await context.close();
return;
}
userAgent = userAgent || defaultUserAgent || 'mingalevme/screenshoter';
logger.debug('Setting user agent: ', userAgent);
try {
await page.setUserAgent(userAgent);
} catch (e) {
logger.error(e);
res.status(400).end('Error while setting user agent: ' + e.message);
await page.close();
await context.close();
return;
}
if (cookies) {
try {
cookies = JSON.parse(cookies);
} catch (e) {
logger.error(e);
res.status(400).end('Error while parsing cookies: ' + e.message);
await page.close();
await context.close();
return;
}
logger.debug('Setting cookies: ', cookies);
try {
await page.setCookie(...cookies);
} catch (e) {
logger.error(e);
res.status(400).end('Error while setting cookies: ' + e.message);
await page.close();
await context.close();
return;
}
}
let options = {};
if (navigationTimeoutMs !== null) {
options.timeout = navigationTimeoutMs;
}
if (waitUntilEvent) {
options.waitUntil = waitUntilEvent;
}
logger.debug('Navigating to url: ', {
url: url,
options: options,
viewport: viewport,
userAgent: userAgent
? userAgent
: '<default>',
});
try {
await page.goto(url, options);
} catch (e) {
if (e instanceof puppeteer.TimeoutError) {
if (failOnTimeout) {
logger.error('Error while navigating to url: ' + e.message);
res.status(504).end(e.message);
await page.close();
await context.close();
return;
} else {
logger.info('Non-Fatal error while navigating to url: ' + e.message, {
url: url,
});
}
} else {
logger.error(e);
await page.close();
await context.close();
res.status(502).end('Error while navigating to url: ' + e.message);
return;
}
}
if (waitForSelector) {
let waitForSelectorOptions = {};
if (waitForSelectorTimeoutMs !== null) {
waitForSelectorOptions.timeout = waitForSelectorTimeoutMs;
}
logger.debug('Waiting for selector: ', {
selector: waitForSelector,
options: waitForSelectorOptions,
});
try {
await page.waitForSelector(waitForSelector, waitForSelectorOptions);
logger.debug('Selector has been found: ', {
selector: waitForSelector,
options: waitForSelectorOptions,
});
} catch (e) {
if (!(e instanceof puppeteer.TimeoutError) || failOnWaitForSelectorTimeout) {
logger.error('Error while waiting for selector: ' + e.message, {
selector: waitForSelector,
options: waitForSelectorOptions,
});
res.status(504).end(e.message);
await page.close();
await context.close();
return;
} else {
logger.info('Non-Fatal error while waiting for selector: ' + e.message, {
selector: waitForSelector,
options: waitForSelectorOptions,
});
}
}
}
if (waitForXPath) {
let waitForXPathOptions = {};
if (waitForXPathTimeoutMs !== null) {
waitForXPathOptions.timeout = waitForXPathTimeoutMs;
}
logger.debug('Waiting for xpath: ', {
xpath: waitForXPath,
options: waitForXPathOptions,
});
try {
await page.waitForXPath(waitForXPath, waitForXPathOptions);
logger.debug('XPath has been found: ', {
xpath: waitForXPath,
options: waitForXPathOptions,
});
} catch (e) {
if (!(e instanceof puppeteer.TimeoutError) || failOnWaitForXPathTimeout) {
logger.error('Error while waiting for xpath: ' + e.message, {
xpath: waitForXPath,
options: waitForXPathOptions,
});
res.status(504).end(e.message);
await page.close();
await context.close();
return;
} else {
logger.info('Non-Fatal error while waiting for xpath: ' + e.message, {
xpath: waitForSelector,
options: waitForXPathOptions,
});
}
}
}
if (waitForFunction) {
let waitForFunctionOptions = {};
if (waitForFunctionTimeoutMs !== null) {
waitForFunctionOptions.timeout = waitForFunctionTimeoutMs;
}
if (waitForFunctionPolling !== null) {
waitForFunctionOptions.polling = waitForFunctionPolling;
}
logger.debug('Waiting for function', {
function: waitForFunction,
options: waitForFunctionOptions,
});
try {
await page.waitForFunction(waitForFunction, waitForFunctionOptions);
logger.debug('Waited for function', {
function: waitForFunction,
options: waitForFunctionOptions,
});
} catch (e) {
if (!(e instanceof puppeteer.TimeoutError) || failOnWaitForFunctionTimeout) {
logger.error('Error while waiting for function: ' + e.message, {
function: waitForFunction,
options: waitForFunctionOptions,
});
res.status(504).end(e.message);
await page.close();
await context.close();
return;
} else {
logger.info('Non-Fatal error while waiting for function: ' + e.message, {
function: waitForFunction,
options: waitForFunctionOptions,
});
}
}
}
if (delayMs) {
logger.debug('Delaying (ms) ...', delayMs);
await (async (timeoutMs) => {
return new Promise(resolve => {
setTimeout(resolve, timeoutMs);
});
})(delayMs);
}
if (scrollPageToBottom) {
let scrollingToBottomOptions = {}
if (scrollPageToBottomSize) {
scrollingToBottomOptions.size = scrollPageToBottomSize
}
if (scrollPageToBottomDelayMs) {
scrollingToBottomOptions.delay = scrollPageToBottomDelayMs
}
if (scrollPageToBottomStepsLimit) {
scrollingToBottomOptions.stepsLimit = scrollPageToBottomStepsLimit
}
logger.debug('Scrolling the page to the bottom ...', scrollingToBottomOptions);
try {
await scroller.scrollPageToBottom(page, scrollingToBottomOptions)
} catch (e) {
logger.error('Error while scrolling page to the bottom: ' + e.message, {
options: scrollingToBottomOptions,
});
res.status(400).end('Error while scrolling page to the bottom: ' + e.message);
await page.close();
await context.close();
return;
}
}
let clip = undefined;
if (element) {
try {
var rect = await page.evaluate((selector) => {
const rect = document.querySelector(selector).getBoundingClientRect();
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
};
}, element);
logger.debug('Element has been found', rect);
} catch (e) {
logger.error(e);
res.status(400).end('Element has not been found: ' + e.message);
await page.close();
await context.close();
return;
}
if (rect.width === 0 || rect.height === 0) {
logger.error('Invalid element dimensions', rect);
res.status(400).end('Invalid element dimensions: ' + JSON.stringify(rect));
await page.close();
await context.close();
return;
}
clip = {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
}
if (format === FORMAT_JPEG && (clip.height * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE || clip.width * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE)) {
format = FORMAT_PNG;
logger.info('Width and/or height are greater than jpeg-image dimension limit, format has been changed to ' + FORMAT_PNG);
}
}
if (format === FORMAT_JPEG && (fullPage || !clip)) { // Check if width/height if greater than MAX_JPEG_DIMENSION_SIZE
logger.debug('Determining size of page ...');
let bodyBoundingClientRect;
try {
bodyBoundingClientRect = await page.evaluate((selector) => {
const rect = document.querySelector(selector).getBoundingClientRect();
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
};
}, 'body');
} catch (e) {
logger.error(e);
res.status(400).end('Error while determining size of the page: ' + e.message);
await page.close();
await context.close();
return;
}
if (bodyBoundingClientRect) {
if (bodyBoundingClientRect.width === 0 || bodyBoundingClientRect.height === 0) {
logger.error('Invalid body dimensions while checking page size', bodyBoundingClientRect);
} else {
logger.debug('Size of page', {
width: bodyBoundingClientRect.width * viewport.deviceScaleFactor,
height: bodyBoundingClientRect.height * viewport.deviceScaleFactor,
});
if (format === FORMAT_JPEG && (bodyBoundingClientRect.height * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE || bodyBoundingClientRect.width * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE)) {
format = FORMAT_PNG;
logger.info('Width and/or height are greater than jpeg-image dimension limit, format has been changed to ' + FORMAT_PNG);
}
// if (bodyBoundingClientRect.height * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE || bodyBoundingClientRect.width * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE) {
// logger.info('Width and/or height are greater than jpeg-image dimension limit, screenshot will be cropped to', clip);
// clip = {
// x: bodyBoundingClientRect.x,
// y: bodyBoundingClientRect.y,
// width: bodyBoundingClientRect.width * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE
// ? Math.floor(MAX_JPEG_DIMENSION_SIZE/viewport.deviceScaleFactor)
// : bodyBoundingClientRect.width,
// height: bodyBoundingClientRect.height * viewport.deviceScaleFactor > MAX_JPEG_DIMENSION_SIZE
// ? Math.floor(MAX_JPEG_DIMENSION_SIZE/viewport.deviceScaleFactor)
// : bodyBoundingClientRect.height,
// }
// logger.debug('Width and/or height are greater than MAX_JPEG_DIMENSION_SIZE, screenshot will be cropped to', clip);
// fullPage = false;
// }
}
}
}
logger.debug('Taking screenshot', {
url: url,
element: element,
full: fullPage,
subarea: clip,
format: format,
transparency: transparency,
captureBeyondViewport: captureBeyondViewport,
});
try {
/** @type {Buffer} */
image = await page.screenshot({
type: format,
quality: quality
? quality
: undefined,
fullPage: fullPage,
captureBeyondViewport: captureBeyondViewport,
clip: clip,
omitBackground: transparency
? true
: undefined,
});
logger.debug('Screenshot has been taken', {
url: url,
element: element,
full: fullPage,
subarea: clip,
format: format,
transparency: transparency,
captureBeyondViewport: captureBeyondViewport,
});
} catch (e) {
logger.error(e);
res.status(400).end('Error while taking a screenshot: ' + e.message);
await page.close();
await context.close();
return;
}
if (image.byteLength === 0) {
const e = new Error('Page is too big?');
logger.error('Error while taking screenshot: ' + e.message);
res.status(400).end('Error while taking a screenshot: ' + e.message);
await page.close();
await context.close();
return;
}
if (width || maxHeight) {
try {
var imgObj = sharp(image);
} catch (e) {
logger.error(e);
res.status(400).end('Error while creating sharp-object: ' + e.message);
await page.close();
await context.close();
return;
}
try {
var metadata = await imgObj.metadata();
} catch (e) {
logger.error(e);
res.status(400).end('Error while fetching metadata from sharp-object: ' + e.message);
await page.close();
await context.close();
return;
}
try {
if (width && width !== metadata.width) {
let newHeight = parseInt(metadata.height * width / metadata.width);
if (maxHeight && newHeight > maxHeight) {
//image = await imgObj.resize(width, maxHeight).crop(sharp.gravity.northeast).toBuffer();
image = await imgObj.resize(width, maxHeight, {
position: sharp.gravity.northeast,
}).toBuffer();
} else {
image = await imgObj.resize(width).toBuffer();
}
} else if (maxHeight && metadata.height > maxHeight) {
//image = await imgObj.resize(metadata.width, maxHeight).crop(sharp.gravity.northeast).toBuffer();
image = await imgObj.resize(metadata.width, maxHeight, {
position: sharp.gravity.northeast,
}).toBuffer();
}
} catch (e) {
logger.error(e);
res.status(400).end('Error while resizing sharp-object: ' + e.message);
await page.close();
await context.close();
return;
}
}
res.writeHead(200, {
'Content-Type': 'image/' + format,
'Cache-Control': 'max-age=' + (ttl || 0),
'Content-Disposition': 'inline; filename=screenshot.' + format,
'X-Browser-Version': browserVersion,
'X-Cache-Status': 'miss',
});
res.end(image, 'binary');
if (cache) {
logger.debug('Setting cache entry', {
'key': cacheKey,
'cache': cache.describe(),
});
cache.set(cacheKey, image);
}
await page.close();
await context.close();
};