-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
205 lines (184 loc) · 5.66 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
const express = require('express')
const app = express()
const port = 3000
const puppeteer = require('puppeteer')
const fs = require('fs')
const fp = require('path')
const screenshotDir = '/tmp/screenshot/'
const pdfDir = '/tmp/pdf/'
const hbs = require('express-hbs')
const mustache = require('mustache')
// request header
// User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0
const userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0'
// need to add this header for some request
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
// const accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
// Accept-Language: en-US,en;q=0.5
// const acceptLang = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
// Accept-Encoding: gzip, deflate, br
// const acceptEncoding = 'gzip, deflate, br'
// Upgrade-Insecure-Requests: 1
// Connection: keep-alive
let browser
(async () => {
browser = await puppeteer.launch({
headless: true,
ignoreHTTPSErrors: true,
args: [
"--no-sandbox",
"--disable-gpu",
]
});
fs.mkdir(screenshotDir, { recursive: true }, (err) => {
if (err) throw err;
});
console.log("screenshot dir created")
fs.mkdir(pdfDir, { recursive: true }, (err) => {
if (err) throw err;
});
console.log("pdf dir created")
})();
function relative(path) {
return fp.join(__dirname, path);
}
app.use(express.json());
app.engine('hbs', hbs.express4());
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
app.use(express.static(relative('public')));
app.get('/', (req, res) => {
res.send('headless chrome api is ready to serve')
})
app.get('/generate/:template', (req, res) => {
const template = req.params.template
const data = req.query;
console.log(data)
try {
var content = fs.readFileSync(relative('templates/' + template), 'utf8');
const html = mustache.render(content, data)
res.send(html)
} catch (error) {
console.log(error)
res.status(500).send(error)
}
})
app.post('/content', async (req, res) => {
const url = req.body.url
var raw = req.body.raw
const js = req.body.js
try {
if (url) {
console.log('open: ' + url)
const content = await ssr(url, js)
if (raw) {
res.send(content)
} else {
res.json(content)
}
} else {
res.status(400).send("missing input value")
}
} catch (error) {
console.error(error)
res.status(500).send(error)
}
})
app.post('/screenshot', async (req, res) => {
const url = req.body.url
const js = req.body.js
let ext
if (req.body.ext) {
ext = req.body.ext
} else {
ext = 'png'
}
const date = Date.now()
let screenshotData = {
path: screenshotDir + date + '.' + ext
}
try {
if (url) {
console.log('open for screenshot: ' + url)
const context = await browser.createIncognitoBrowserContext();
const page = await loadPage(context, url, js)
await page.screenshot(screenshotData)
page.close()
context.close()
const filename = screenshotData.path
res.sendFile(filename)
res.on('finish', function() {
removeFile(filename)
});
} else {
res.status(400).send("missing input value")
}
} catch (error) {
console.error(error)
res.status(500).send(error)
}
})
app.post('/pdf', async (req, res) => {
const url = req.body.url
const js = req.body.js
const date = Date.now()
var landscape = req.body.landscape
let pdfData = {
path: pdfDir + date + '.pdf',
format: 'A4',
landscape: landscape
}
try {
if (url) {
console.log('open for screenshot: ' + url)
const context = await browser.createIncognitoBrowserContext();
const page = await loadPage(context, url, js)
await page.pdf(pdfData)
page.close()
context.close()
const filename = pdfData.path
res.sendFile(filename)
res.on('finish', function() {
removeFile(filename)
});
} else {
res.status(400).send("missing input value")
}
} catch (error) {
console.error(error)
res.status(500).send(error)
}
})
function removeFile(filename) {
fs.unlink(filename, (err) => {
if (err) throw err;
console.log('file deleted :' + filename);
});
}
async function loadPage(context, url, js = false) {
const page = await context.newPage();
await page.setUserAgent(userAgent);
page.setExtraHTTPHeaders({
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5'
});
if (js) {
page.setJavaScriptEnabled(true)
await page.goto(url, { waitUntil: 'networkidle0' });
} else {
await page.goto(url);
}
console.log(await page.title())
return page
}
async function ssr(url, js = false) {
const context = await browser.createIncognitoBrowserContext();
const page = await loadPage(context, url, js)
const html = await page.content(); // serialized HTML of page DOM.
page.close()
context.close()
return html;
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
})