-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathindex.js
178 lines (141 loc) · 3.78 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
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
const setup = require(`./starter-kit/setup`)
const crypto = require(`crypto`)
const AWS = require(`aws-sdk`)
const s3 = new AWS.S3({
apiVersion: `2006-03-01`,
})
exports.handler = async (event, context, callback) => {
// For keeping the browser launch
context.callbackWaitsForEmptyEventLoop = false
let request = {}
if (event.body) {
request = JSON.parse(event.body)
}
const url = request.url
if (!url) {
callback(null, proxyError(`no url provided`))
return
}
const width = request.width || 1024
const height = request.height || 768
const fullPage = request.fullPage || false
const browser = await setup.getBrowser()
exports
.run(browser, url, width, height, fullPage)
.then(result => {
callback(null, proxyResponse(result))
})
.catch(err => {
callback(null, proxyError(err))
})
}
exports.run = async (browser, url, width, height, fullPage) => {
console.log(`Invoked: ${url} (${width}x${height})`)
if (!process.env.S3_BUCKET) {
throw new Error(
`Provide the S3 bucket to use by adding an S3_BUCKET` +
` environment variable to this Lambda's configuration`
)
}
const region = await s3GetBucketLocation(process.env.S3_BUCKET)
if (!region) {
throw new Error(`invalid bucket ${process.env.S3_BUCKET}`)
}
const keyBase = `${url}-(${width},${height})`
const digest = crypto
.createHash(`md5`)
.update(keyBase)
.digest(`hex`)
const key = `${digest}.png`
const screenshotUrl = `https://s3-${region}.amazonaws.com/${
process.env.S3_BUCKET
}/${key}`
const metadata = await s3HeadObject(key)
const now = new Date()
if (metadata) {
if (metadata.Expiration) {
const expires = getDateFromExpiration(metadata.Expiration)
if (now < expires) {
console.log(`Returning cached screenshot`)
return { url: screenshotUrl, expires }
}
} else {
throw new Error(`no expiration date set`)
}
}
console.log(`Taking new screenshot`)
const page = await browser.newPage()
await page.setViewport({ width, height, deviceScaleFactor: 2 })
await page.goto(url, { waitUntil: [`load`, `networkidle0`] })
// wait for full-size images to fade in
await page.waitFor(1000)
const screenshot = await page.screenshot({ fullPage })
const up = await s3PutObject(key, screenshot)
await page.close()
let expires
if (up && up.Expiration) {
expires = getDateFromExpiration(up.Expiration)
}
return { url: screenshotUrl, expires }
}
const proxyResponse = body => {
body.success = true
return {
statusCode: 200,
body: JSON.stringify(body),
}
}
const proxyError = err => {
let msg = err
if (err instanceof Error) {
msg = err.message
}
return {
statusCode: 400,
body: JSON.stringify({
success: false,
error: msg,
}),
}
}
const s3PutObject = async (key, body) => {
const params = {
ACL: `public-read`,
Bucket: process.env.S3_BUCKET,
Key: key,
Body: body,
ContentType: `image/png`,
}
return new Promise((resolve, reject) => {
s3.putObject(params, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
}
const s3GetBucketLocation = bucket => {
const params = {
Bucket: bucket,
}
return new Promise((resolve, reject) => {
s3.getBucketLocation(params, (err, data) => {
if (err) resolve(null)
else resolve(data.LocationConstraint)
})
})
}
const s3HeadObject = key => {
const params = {
Bucket: process.env.S3_BUCKET,
Key: key,
}
return new Promise((resolve, reject) => {
s3.headObject(params, (err, data) => {
if (err) resolve(null)
else resolve(data)
})
})
}
const expiryPattern = /expiry-date="([^"]*)"/
const getDateFromExpiration = expiration =>
new Date(expiryPattern.exec(expiration)[1])