This repository has been archived by the owner on Feb 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
functions.js
245 lines (220 loc) · 5.26 KB
/
functions.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
const {Lambda, S3} = require('aws-sdk');
const {get} = require('axios');
const crypto = require('crypto');
const {readFileSync} = require('fs');
const {Readable} = require('stream');
const streamToArray = require('stream-to-array');
const lambda = new Lambda();
const s3 = new S3();
/**
* Take a file and convert to a base64 encoded string.
*
* @param buffer A Buffer instance.
* @returns {string} A base64 encoded string.
*/
function base64Encode(buffer) {
return new Buffer.from(buffer).toString('base64');
}
/**
* Take a base64 encoded string and convert to a buffer.
*
* @param {string} base64
* @returns {Buffer}
*/
function base64Decode(base64) {
return new Buffer.from(base64, 'base64');
}
/**
* Convert a buffer to a stream
*
* @param {Buffer} buffer
* @returns {Readable}
*/
function bufferToStream(buffer) {
return new Readable({
read() {
this.push(buffer);
this.push(null);
}
});
}
/**
* Convert a stream to a buffer.
*
* @param {Readable} stream
* @returns {Promise<Buffer>}
*/
async function streamToBuffer(stream) {
const parts = await streamToArray(stream);
const buffers = parts.map(part => Buffer.isBuffer(part) ? part : Buffer.from(part));
return Buffer.concat(buffers);
}
/**
* Get an MD5 hash of a string.
*
* @param {string} data
* @returns {string}
*/
function md5(data) {
return crypto.createHash('md5').update(data).digest('hex');
}
/**
* Upload a file to Amazon S3.
*
* @param {string} bucket
* @param {string} file
* @param {Readable} stream
*/
async function uploadToS3(bucket, file, stream) {
const params = {
Bucket: bucket,
Key: file,
Body: stream,
};
return await new Promise((resolve, reject) => {
s3.upload(params, (err, data) => err ? reject(err) : resolve(data));
});
}
/**
* Fetch a file from Amazon S3.
*
* @param {string} bucket
* @param {string} file
*/
async function fetchFromS3(bucket, file) {
const params = {
Bucket: bucket,
Key: file,
};
return await new Promise((resolve, reject) => {
s3.getObject(params, (err, data) => err ? reject(err) : resolve(data));
});
}
/**
* Check if a file exists on Amazon S3 (doesn't work with directories).
*
* @param {string} bucket The S3 bucket name.
* @param {string} file The file path on S3.
* @returns {boolean} Whether or not the file exists.
*/
async function fileExistsOnS3(bucket, file) {
const params = {
Bucket: bucket,
Key: file,
};
return await new Promise((resolve, reject) => {
s3.headObject(params, (err, data) => err ? reject(err) : resolve(data));
});
}
/**
* Get a screenshot given a URL.
*
* @param {string }url
* @returns {string}
*/
async function captureScreenshot(url) {
const params = {
FunctionName: 'bluehost-generate-screenshot:active',
Payload: JSON.stringify({url}, null, 2),
};
return await new Promise((resolve, reject) => {
lambda.invoke(params, (err, {Payload}) => err ? reject(err) : resolve(JSON.parse(Payload)));
});
}
/**
* Asynchronously generate a screenshot given a URL.
*
* @param {string} bucket
* @param {string} key
* @param {string} url
* @returns {string}
*/
function queueScreenshotGeneration(bucket, key, url) {
const params = {
InvocationType: 'Event',
FunctionName: 'bluehost-url-to-screenshot-on-s3',
Payload: JSON.stringify({bucket, key, url}, null, 2),
};
lambda.invoke(params).send();
}
/**
* Send an image as a response.
*
* @param base64
* @returns {{headers: {"Content-Type": string}, isBase64Encoded: boolean, body: string, statusCode: number}}
*/
function sendImage(base64) {
return {
statusCode: 200,
headers: {
'Content-Type': 'image/png',
},
body: `data:image/png;base64,${base64}`,
isBase64Encoded: true,
};
}
/**
* Send a placeholder image as a response.
*
* @returns {{headers: {"Content-Type": string}, isBase64Encoded: boolean, body: string, statusCode: number}}
*/
function sendPlaceholderImage() {
return sendImage(base64Encode(readFileSync('./placeholder.png')));
}
/**
* Send an error response.
*
* @param {string} message
* @returns {{headers: {}, isBase64Encoded: boolean, body: *, statusCode: number}}
*/
function sendError(message = 'Unable to generate screenshot') {
return {
statusCode: 500,
headers: {},
body: JSON.stringify({
status: 'error',
message,
}),
isBase64Encoded: false,
};
}
function sendRedirect(location, statusCode = 301) {
return {
statusCode: 301,
headers: {
Location: location,
},
body: '',
isBase64Encoded: false,
};
}
/**
* Send a 404 response.
*
* @returns {{statusCode: number}}
*/
function send404() {
return {
statusCode: 404,
};
}
function getS3Url(bucket, file) {
return `http://${bucket}.s3.amazonaws.com/${file}`;
}
module.exports = {
base64Decode,
base64Encode,
bufferToStream,
captureScreenshot,
fetchFromS3,
fileExistsOnS3,
getS3Url,
md5,
queueScreenshotGeneration,
send404,
sendError,
sendImage,
sendPlaceholderImage,
sendRedirect,
uploadToS3,
};