-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtweet_screenshot.js
More file actions
executable file
·70 lines (60 loc) · 2.22 KB
/
tweet_screenshot.js
File metadata and controls
executable file
·70 lines (60 loc) · 2.22 KB
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
const puppeteer = require('puppeteer');
const fs = require("fs");
const fsPromises = require('fs').promises;
let tweetid = process.argv[2];
if (!tweetid) tweetid = "1386777564392329230";
let outfile = process.argv[3];
if (!outfile) outfile = "screenshot.png";
let filenames = [], filesizes = [];
for (let i=0; i<5; i++) { filenames.push("image-" + i + ".png")};
(async() => {
let browser;
try {
browser = await puppeteer.launch();
const page = await browser.newPage();
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
await page.setViewport({
width: 1024,
height: 2048,
deviceScaleFactor: 1.0,
});
page
.on('console', message => console.log(`${message.type().substr(0, 3).toUpperCase()} ${message.text()}`))
.on('pageerror', ({ message }) => console.log(message))
.on('requestfailed', request => console.log(`${request.failure().errorText} ${request.url()}`))
//.on('response', response =>
// console.log(`${response.status()} ${response.url()}`))
var contentHtml = fs.readFileSync('tweet_local_embed.html', 'utf8');
contentHtml = contentHtml.replace("%%TWEETID%%", tweetid)
await page.setContent(contentHtml);
await delay(5000);
const elem = await page.$('#bounding');
const boundingBox = await elem.boundingBox();
await page.setViewport({
width: parseInt(boundingBox.width + boundingBox.x),
height: parseInt(boundingBox.height + boundingBox.y),
deviceScaleFactor: 1.0,
});
// get maximum sized screenshot -- they fail randomly
for (const fn of filenames) {
console.log("Saving ", fn);
await page.screenshot({path: fn});
const stats = await fsPromises.stat(fn);
filesizes.push(stats.size);
};
let i = filesizes.indexOf(Math.max(...filesizes));
await fsPromises.copyFile(filenames[i], outfile);
console.log("Saved to ", outfile);
for (const fn of filenames) {
console.log("Removing ", fn);
await fsPromises.unlink(fn);
}
} catch (error) {
console.error("Error generating screenshot:", error.message);
process.exit(1);
} finally {
if (browser) {
await browser.close();
}
}
})();