-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
144 lines (127 loc) · 4.07 KB
/
index.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
const express = require('express')
const puppeteer = require('puppeteer-core')
const { executablePath } = require('puppeteer')
require('dotenv').config()
const app = express()
const port = process.env.PORT || 10000
const cache = {}
// app.get('/', async (request, response) => {
// try {
// response.render('home.html')
// } catch (error) {
// if (error.message === 'Protocol error (Page.navigate): Cannot navigate to invalid URL')
// return response.status(404).end()
// console.log(error)
// response
// .status(500)
// .json({ error: 'An error occurred while capturing the screenshot' })
// }
// })
app.get('/snap', async (request, response) => {
let browser = null
let page = null
try {
console.log('Performance Check: Job Started')
let url = decodeURIComponent(request.query.url)
// Check if the screenshot is already cached
if (cache[url]) {
console.log('Serving from cache:', url)
response.set('Content-Type', 'image/jpeg')
response.send(cache[url])
return
}
// Prepend "http://" if the URL doesn't start with a protocol
if (!(/^https?:\/\//i).test(url)) {
url = `http://` + url
}
browser = await puppeteer.launch({
args: [
'--disable-setuid-sandbox',
'--no-sandbox',
'--single-process',
'--no-zygote'
],
executablePath:
process.env.NODE_ENV === 'production' ?
process.env.PUPPETEER_EXECUTABLE_PATH :
executablePath()
})
page = await browser.newPage()
// Set a custom viewport size
await page.setViewport({ width: 1024, height: 768 })
await page.goto(url, { waitUntil: 'networkidle0' })
const snap = await page.screenshot()
cache[url] = snap
response.set('Content-Type', 'image/jpeg')
response.send(snap)
} catch (error) {
if (error.message === 'Protocol error (Page.navigate): Cannot navigate to invalid URL')
return response.status(404).end()
console.log(error)
response
.status(500)
.json({ error: 'An error occurred while capturing the screenshot' })
} finally {
await page.close()
await browser.close()
console.log('Performance Check: Job Ended')
}
})
app.get('/pdf', async (request, response) => {
let browser = null
let page = null
try {
console.log('Performance Check: Job Started')
if (request.method !== 'GET') return response.status(405).end()
// Strip leading slash from request path
let url = decodeURIComponent(request.query.url.replace(/^\/+/, ''))
// Check if the pdf is already cached
if (cache[url]) {
console.log('Serving from cache:', url)
response.set('Content-Type', 'application/pdf')
response.send(cache[url])
return
}
// Prepend "http://" if the URL doesn't start with a protocol
if (!(/^https?:\/\//i).test(url)) {
url = `http://` + url
}
browser = await puppeteer.launch({
args: [
'--disable-setuid-sandbox',
'--no-sandbox',
'--single-process',
'--no-zygote'
],
executablePath:
process.env.NODE_ENV === 'production' ?
process.env.PUPPETEER_EXECUTABLE_PATH :
executablePath()
})
page = await browser.newPage()
// Block favicon.ico requests from reaching puppeteer
if (url === 'favicon.ico') return response.status(404).end()
await page.goto(url, { waitUntil: 'networkidle0' })
console.log(`Converting: ` + url)
const pdfBuffer = await page.pdf({ format: 'A4' })
cache[url] = pdfBuffer
if (!pdfBuffer) return response.status(400).send('Error: Could not generate PDF')
// Instruct browser to cache PDF for maxAge ms
if (process.env.NODE_ENV !== 'development') response.setHeader('Cache-control', `public, max-age=1000`)
// Set Content type to PDF and send the PDF to the client
response.setHeader('Content-type', 'application/pdf')
response.send(pdfBuffer)
} catch (error) {
if (error.message === 'Protocol error (Page.navigate): Cannot navigate to invalid URL')
return response.status(404).end()
console.error(error)
response.status(500).send('Error: Please try again.')
} finally {
await page.close()
await browser.close()
console.log('Performance Check: Job Ended')
}
})
app.listen(port, () => {
console.log('Snapper is listening on port ' + port)
})