-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfxsnapshot.js
114 lines (99 loc) · 2.56 KB
/
fxsnapshot.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
// fxsnapshot.js
// Based on fxhash website-capture service:
// https://github.com/fxhash/gcloud-functions/tree/master/website-capture
const puppeteer = require('puppeteer');
const fs = require('fs').promises;
const argv = require('yargs')
.scriptName('fxsnapshot')
.usage(
'$0 [options] <count>',
'Capture a set of images from your local token.',
(yargs) => {
yargs.positional('count', {
describe: 'Number of images to capture',
type: 'number',
})
})
.default({
url: 'http://localhost:3301/',
width: 800,
height: 800,
timeout: 120,
captureViewport: false,
})
.describe('url', 'Local token url')
.help()
.version(false)
.example([
['$0 256', 'Capture 256 images'],
['$0 --url="file://.../" 256', 'Use custom url'],
])
.argv;
const viewportSettings = {
deviceScaleFactor: 1,
width: argv.width,
height: argv.height,
};
const saveFrame = async (page, i) => {
const fxhash = await page.evaluate(() => fxhash);
const iteration = String(i).padStart(4, '0');
const filename = `images/${iteration}-${fxhash}.png`;
console.log(filename);
if (argv.captureViewport) {
const capture = await page.screenshot()
await fs.writeFile(filename, capture, (err) => {
console.log(err ? err : filename);
});
} else {
const base64 = await page.$eval('canvas', (el) => {
return el.toDataURL();
});
const pureBase64 = base64.replace(/^data:image\/png;base64,/, "");
const b = Buffer.from(pureBase64, "base64");
await fs.writeFile(filename, b, (err) => {
console.log(err ? err : filename);
});
}
};
(async () => {
let browser = await puppeteer.launch({
headless: 'new',
ignoreHTTPSErrors: true,
});
if (!browser) {
process.exit(1);
}
let page = await browser.newPage();
await page.setViewport(viewportSettings);
await page.setDefaultNavigationTimeout(argv.timeout * 1000);
if (!page) {
process.exit(1);
}
page.on('error', (err) => {
console.log('PAGE ERROR:', err);
});
await page.evaluateOnNewDocument(() => {
window.addEventListener('fxhash-preview', () => {
console.log('FXPREVIEW');
});
});
let total = parseInt(argv.count);
let i = 1;
let working = false;
page.on('console', async (msg) => {
if (working) { return; }
working = true;
if (msg.text().match(/PREVIEW/)) {
await saveFrame(page, i);
if (i < total) {
i += 1;
page.goto(argv.url);
}
else {
process.exit(0);
}
}
working = false;
});
page.goto(argv.url);
})();