-
Notifications
You must be signed in to change notification settings - Fork 6
/
lambda-pdf-thumbnail.js
208 lines (184 loc) · 5.59 KB
/
lambda-pdf-thumbnail.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
// get reference to S3 client
var async = require('async');
var AWS = require('aws-sdk');
var path = require('path');
var makePdfThumbnail = require('./make-pdf-thumbnail');
var util = require('util');
var tmp = require('tmp');
var fs = require('fs');
/* This function creates a thumbnail from a pdf.
* The source bucket and key, and destiny bucket and key must be specified of s3 must be specified.
*/
function generateThumbnail (s3, resolution, srcBucket, srcKey, dstBucket, dstKey, callback) {
'use strict';
var error;
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
error = new Error(
'unable to infer document type for key ' + srcKey
);
callback(error);
return;
}
var imageType = typeMatch[1];
if (imageType !== 'pdf') {
error = new Error(
'skipping non-pdf ' + srcKey
);
callback(error);
return;
}
// Download the image from S3, transform, and upload to a different S3 bucket.
async.waterfall([
function transform(next) {
var request = s3.getObject({
Bucket: srcBucket,
Key: srcKey
});
try {
var pdfStream = request.createReadStream();
} catch (e) {
return next(e);
}
tmp.file(function(err, path){
if (err) {
next(err);
return;
}
makePdfThumbnail.fromStreamToFile(pdfStream, path, resolution, function(err, tmpfilename) {
if (err) {
next(err);
return;
}
next(null, 'image/png', tmpfilename);
});
});
},
function upload(contentType, tmpfilename, next) {
// Stream the transformed image to a different S3 bucket.
var tmpFileStream = fs.createReadStream(tmpfilename);
s3.upload({
Bucket: dstBucket,
Key: dstKey,
Body: tmpFileStream,
ContentType: contentType
},
next);
}
], callback);
}
function S3EventHandler(options) {
'use strict';
options = options || {};
if (!('outputBucketName' in options) && !('tableName' in options)) {
throw new Error('Neither the output bucket or dynamodb table is specified');
}
if (!('region' in options)) {
throw new Error('region is not specified');
}
this.sourceHash = 'SourceBucket';
this.destinationHash = 'DestinationBucket';
this.resolution = 72;
var keys = ['outputBucketName', 'dynamodb', 's3', 'sourceHash',
'destinationHash', 'tableName', 'resolution'];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key in options) {
this[key] = options[key];
}
}
this.s3 = this.s3 || new AWS.S3({region: options.region});
this.dynamodb = this.dynamodb || new AWS.DynamoDB({region: options.region});
}
S3EventHandler.prototype._getDestinationBucketName = function(inputBucketName, callback) {
'use strict';
if (this.outputBucketName) {
callback(null, this.outputBucketName);
return;
}
var params = {
AttributesToGet: [
this.destinationHash
],
TableName: this.tableName,
Key: {}
};
params.Key[this.sourceHash] = {'S': inputBucketName};
var destinationHash = this.destinationHash;
this.dynamodb.getItem(params, function(err, result) {
if (result) {
callback(null, result.Item[destinationHash].S);
}
else {
callback(err);
}
});
};
S3EventHandler.prototype.handler = function(event, context) {
'use strict';
// Read options from the event.
var srcBucket = event.Records[0].s3.bucket.name;
// Object key may have spaces or unicode non-ASCII characters.
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
var s3 = this.s3;
var resolution = this.resolution;
this._getDestinationBucketName(srcBucket, function(err, dstBucket){
if (err) {
console.error(
'Unable to resize ' + srcKey + ' from ' + srcBucket +
' and upload to ' + dstBucket + '/' +
' due to an error: ' + util.inspect(err, {showHidden: false, depth: null})
);
context.fail();
return;
}
function done(err, keys) {
if (err) {
console.error(
'Unable to resize ' + srcKey + ' from ' + srcBucket +
' and upload to ' + dstBucket + '/' +
' due to an error: ' + util.inspect(err, {showHidden: false, depth: null})
);
context.fail();
}
else {
for (var i = 0; i < keys.length; i++) {
console.log(
'Successfully resized ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + keys[i]
);
}
context.done();
}
}
var work = [];
function createWork(resolution, dstKey) {
return function(callback) {
generateThumbnail(s3, resolution, srcBucket, srcKey, dstBucket, dstKey, function(err){
callback(err, dstKey);
});
};
}
function getFileBase(srcKey) {
var filePath = (path.dirname(srcKey) == "." ? "" : path.dirname(srcKey) + "/");
return filePath + path.basename(srcKey, '.pdf');
}
if (!isNaN(resolution)) {
work.push(createWork(resolution, getFileBase(srcKey) + '-thumbnail.png'));
}
else if (resolution !== null && typeof resolution === 'object') {
for (var key in resolution) {
if (resolution.hasOwnProperty(key)) {
var dstKey = getFileBase(srcKey) + key + '.png';
work.push(createWork(resolution[key], dstKey));
}
}
}
async.parallel(work, done);
}.bind(this));
};
module.exports = {
S3EventHandler: S3EventHandler,
generateThumbnail: generateThumbnail
};