This repository has been archived by the owner on Oct 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathserver.js
330 lines (284 loc) · 9.07 KB
/
server.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
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const express = require('express');
const puppeteer = require('puppeteer');
const randomUUID = require('random-uuid');
const fs = require('fs');
const util = require('util');
const marked = require('marked');
const ua = require('universal-analytics');
const {URL} = require('url');
const gsearch = require('./helpers/gsearch.js');
const PORT = process.env.PORT || 8080;
const GA_ACCOUNT = 'UA-114816386-1';
const app = express();
const isAllowedUrl = (string) => {
try {
const url = new URL(string);
return url.hostname !== 'pptraas.com' && !url.hostname.startsWith('puppeteerexamples');
} catch (err) {
return false;
}
};
// Adds cors, records analytics hit, and prevents self-calling loops.
app.use((request, response, next) => {
const url = request.query.url;
if (url && !isAllowedUrl(url)) {
return response.status(500).send({
error: 'URL is either invalid or not allowed'
});
}
response.set('Access-Control-Allow-Origin', '*');
// Record GA hit.
const visitor = ua(GA_ACCOUNT, {https: true});
visitor.pageview(request.originalUrl).send();
next();
});
app.get('/', async (request, response) => {
const readFile = util.promisify(fs.readFile);
const md = (await readFile('./README.md', {encoding: 'utf-8'}));
/* eslint-disable */
response.send(`
<!DOCTYPE html>
<html>
<head>
<title>Puppeteer as a service</title>
<meta name="description" content="A hosted service that makes the Chrome Puppeteer API accessible via REST based queries. Tracing, Screenshots and PDFs" />
<meta name="google-site-verification" content="4Tf-yH47m_tR7aSXu7t3EI91Gy4apbwnhg60Jzq_ieY" />
<style>
body {
padding: 40px;
}
body, h2, h3, h4 {
font-family: "Product Sans", sans-serif;
font-weight: 300;
}
</style>
</head>
<body>${marked(md)}</body>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${GA_ACCOUNT}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ACCOUNT}');
</script>
</html>
`);
/* eslint-enable */
});
// Init code that gets run before all request handlers.
app.all('*', async (request, response, next) => {
response.locals.browser = await puppeteer.launch({
dumpio: true,
// headless: false,
// executablePath: 'google-chrome',
args: ['--no-sandbox', '--disable-setuid-sandbox'], // , '--disable-dev-shm-usage']
});
next(); // pass control on to routes.
});
app.get('/screenshot', async (request, response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
// Default to a reasonably large viewport for full page screenshots.
const viewport = {
width: 1280,
height: 1024,
deviceScaleFactor: 2
};
let fullPage = true;
const size = request.query.size;
if (size) {
const [width, height] = size.split(',').map(item => Number(item));
if (!(isFinite(width) && isFinite(height))) {
return response.status(400).send(
'Malformed size parameter. Example: ?size=800,600');
}
viewport.width = width;
viewport.height = height;
fullPage = false;
}
const browser = response.locals.browser;
try {
const page = await browser.newPage();
await page.setViewport(viewport);
await page.goto(url, {waitUntil: 'networkidle0'});
const opts = {
fullPage,
// omitBackground: true
};
if (!fullPage) {
opts.clip = {
x: 0,
y: 0,
width: viewport.width,
height: viewport.height
};
}
let buffer;
const element = request.query.element;
if (element) {
const elementHandle = await page.$(element);
if (!elementHandle) {
return response.status(404).send(
`Element ${element} not found`);
}
buffer = await elementHandle.screenshot();
} else {
buffer = await page.screenshot(opts);
}
response.type('image/png').send(buffer);
} catch (err) {
response.status(500).send(err.toString());
}
await browser.close();
});
app.get('/metrics', async (request, response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
const browser = response.locals.browser;
const page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle0'});
const metrics = await page.metrics();
await browser.close();
response.type('application/json').send(JSON.stringify(metrics));
});
app.get('/pdf', async (request, response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
const browser = response.locals.browser;
const page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle0'});
const pdf = await page.pdf();
await browser.close();
response.type('application/pdf').send(pdf);
});
app.get('/ssr', async (request, response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
const browser = response.locals.browser;
try {
const page = await browser.newPage();
const res = await page.goto(url, {waitUntil: 'networkidle0'});
// Inject <base> on page to relative resources load properly.
await page.evaluate(url => {
/* global document */
const base = document.createElement('base');
base.href = url;
document.head.prepend(base); // Add to top of head, before all other resources.
}, url);
// Remove scripts(except structured data) and html imports. They've already executed and loaded on the page.
await page.evaluate(() => {
const elements = document.querySelectorAll(
'script:not([type="application/ld+json"]), link[rel="import"]');
elements.forEach(e => e.remove());
});
const html = await page.content();
response.status(res.status()).send(html);
} catch (e) {
response.status(500).send(e.toString());
}
await browser.close();
});
app.get('/trace', async (request, response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
const browser = response.locals.browser;
const filename = `/tmp/trace-${randomUUID()}.json`;
const page = await browser.newPage();
try {
page.on('error', error => {
console.log(url, error);
});
await page.tracing.start({path: filename, screenshots: true});
await page.goto(url, {waitUntil: 'networkidle0'});
await page.tracing.stop();
response.type('application/json').sendFile(filename);
} catch (e) {
response.status(500).send(e.toString());
}
await browser.close();
});
app.get('/version', async (request, response) => {
const browser = response.locals.browser;
const ua = await browser.userAgent();
await browser.close();
response.send(ua);
});
app.get('/gsearch', async (request, response) => {
const url = request.query.url;
if (!url) {
return response.status(400).send(
'Please provide a URL. Example: ?url=https://example.com');
}
const browser = response.locals.browser;
const results = await gsearch.run(browser, url, `/tmp/trace-${randomUUID()}.json`);
await browser.close();
const style = `
<style>
body {
padding: 1em;
font-size: 20px;
font-family: sans-serif;
font-weight: 300;
line-height: 1.4;
}
.summary a {
color: currentcolor;
text-decoration: none;
}
.red {
color: #F44336;
}
a {
color: magenta;
}
</style>
`;
response.send(style + results);
});
app.listen(PORT, function() {
console.log(`App is listening on port ${PORT}`);
});
// Make sure node server process stops if we get a terminating signal.
function processTerminator(sig) {
if (typeof sig === 'string') {
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()));
}
const signals = [
'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS',
'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'];
signals.forEach(sig => {
process.once(sig, () => processTerminator(sig));
});