-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
172 lines (147 loc) · 4.89 KB
/
server.js
File metadata and controls
172 lines (147 loc) · 4.89 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
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
const assert = require('assert');
const fs = require('fs');
const https = require('https');
const path = require('path');
const url = require('url');
const chromeLauncher = require('chrome-launcher');
const compression = require('compression');
const express = require('express');
const now = require('performance-now');
const uuidv4 = require('uuid/v4');
const cache = require('./lib/cache');
const renderer = require('./lib/renderer');
const cors = require('cors');
const app = express();
const CONFIG_PATH = path.resolve(__dirname, '../config.json');
const PROGRESS_BAR_PATH = path.resolve(__dirname, '../node_modules/progress-bar-element/progress-bar.html');
const PORT = process.env.PORT || '3000';
let config = {};
// Load config from config.json if it exists.
if (fs.existsSync(CONFIG_PATH)) {
config = JSON.parse(fs.readFileSync(CONFIG_PATH));
assert(config instanceof Object);
}
// Only start a cache if configured and not in testing.
if (!module.parent && !!config['cache']) {
app.get('/render/:url(*)', cache.middleware());
app.get('/screenshot/:url(*)', cache.middleware());
// Always clear the cache for now, while things are changing.
cache.clearCache();
}
// Allows the config to be overriden
app.setConfig = (newConfig) => {
const oldConfig = config;
config = newConfig;
config.chrome = oldConfig.chrome;
config.port = oldConfig.port;
};
app.use(cors());
app.use(compression());
app.use('/progress-bar.html', express.static(PROGRESS_BAR_PATH));
app.get('/', (request, response) => {
response.sendFile(path.resolve(__dirname, 'index.html'));
});
function isRestricted(urlReq) {
const protocol = (url.parse(urlReq).protocol || '');
if (!protocol.match(/^https?/)) return true;
if (!config['renderOnly']) return false;
for (let i = 0; i < config['renderOnly'].length; i++) {
if (urlReq.startsWith(config['renderOnly'][i])) {
return false;
}
}
return true;
}
// If configured, report action & time to Google Analytics.
function track(action, time) {
if (config['analyticsTrackingId']) {
const postOptions = {
host: 'www.google-analytics.com',
path: '/collect',
method: 'POST'
};
const post = https.request(postOptions);
post.write(`v=1&t=event&ec=render&ea=${action}&ev=${Math.round(time)}&tid=${config['analyticsTrackingId']}&cid=${uuidv4()}`);
post.end();
}
}
app.get('/render/:url(*)', async(request, response) => {
if (isRestricted(request.params.url)) {
response.status(403).send('Render request forbidden, domain excluded');
return;
}
try {
const start = now();
const result = await renderer.serialize(request.params.url, request.query, config);
response.set('x-renderer', 'rendertron');
response.status(result.status).send({html: result.body});
track('render', now() - start);
} catch (err) {
response.status(400).send('Cannot render requested URL');
console.error('Cannot render requested URL');
console.error(err);
}
});
app.get('/screenshot/:url(*)', async(request, response) => {
if (isRestricted(request.params.url)) {
response.status(403).send('Render request forbidden, domain excluded');
return;
}
try {
const start = now();
const result = await renderer.captureScreenshot(request.params.url, request.query, config);
const img = new Buffer(result, 'base64');
response.set({
'Content-Type': 'image/jpeg',
'Content-Length': img.length
});
response.end(img);
track('screenshot', now() - start);
} catch (err) {
response.status(400).send('Cannot render requested URL');
console.error('Cannot render requested URL');
console.error(err);
}
});
app.get('/_ah/health', (request, response) => response.send('OK'));
app.stop = async() => {
await config.chrome.kill();
};
const appPromise = chromeLauncher.launch({
chromeFlags: ['--headless', '--disable-gpu', '--remote-debugging-address=0.0.0.0'],
port: 0
}).then((chrome) => {
console.log('Chrome launched with debugging on port', chrome.port);
config.chrome = chrome;
config.port = chrome.port;
// Don't open a port when running from inside a module (eg. tests). Importing
// module can control this.
if (!module.parent) {
app.listen(PORT, function() {
console.log('Listening on port', PORT);
});
}
return app;
}).catch((error) => {
console.error(error);
// Critical failure, exit with error code.
process.exit(1);
});
let exceptionCount = 0;
async function logUncaughtError(error) {
console.error('Uncaught exception');
console.error(error);
exceptionCount++;
// Restart instance due to several failures.
if (exceptionCount > 5) {
console.log(`Detected ${exceptionCount} errors, shutting instance down`);
if (config && config.chrome)
await app.stop();
process.exit(1);
}
}
if (!module.parent) {
process.on('uncaughtException', logUncaughtError);
process.on('unhandledRejection', logUncaughtError);
}
module.exports = appPromise;