-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
272 lines (220 loc) · 7.89 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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
var assert = require('assert')
, multiparty = require('multiparty')
, knox = require('knox')
, uuid = require('node-uuid')
, mime = require('mime')
, Batch = require('batch')
, gm = require('gm')
;
var Framer = module.exports = function Framer(opts) {
if (typeof opts !== 'object') opts = {};
var self = this;
assert(typeof opts.s3 === 'object', 'opts.s3 required');
assert(typeof opts.s3.key === 'string', 'opts.s3.key required');
assert(typeof opts.s3.secret === 'string', 'opts.s3.secret required');
assert(typeof opts.s3.bucket === 'string', 'opts.s3.bucket required');
opts.s3.secure = (opts.s3.secure) ? true : false;
this._s3Client = knox.createClient(opts.s3);
if(opts.useImageMagick) {
gm = gm.subClass({
imageMagick: true
});
}
this.handleUpload = function (opts) {
if (!opts) opts = {};
opts.prefix = opts.prefix || "";
var makePublicReadable = opts.makePublicReadable || false
, log = opts.log || function (){}
, prefix = opts.prefix || ""
, authHandler = opts.authHandler;
return function (req, res, callback) {
callback = callback === undefined ? null : callback;
var acceptHeader = req.headers.accept;
var isTypeHtml = (/text\/html/).test(acceptHeader);
var isTypeText = (/text\/text/).test(acceptHeader);
var contentType = 'application/json';
if(isTypeHtml) contentType = 'text/html';
else if(isTypeText) contentType = 'text/text';
var headers = {}
, form = new multiparty.Form()
, batch = new Batch();
if (makePublicReadable) headers['x-amz-acl'] = 'public-read';
var onUnexpectedEnd = function () {
self._handleError(500, res, new Error('incomplete upload'));
};
batch.push(function(cb) {
if (authHandler) {
form.on('field', function(name, value) {
if ( name === 'authorization') {
authHandler(value, cb);
}
});
}
else cb(null, '');
});
batch.push(function(cb) {
form.on('part', function(part) {
if (! part.filename) return;
cb(null, part);
});
});
batch.end(function(err, results) {
if (err) {
return self._handleError(401, res, err);
}
form.removeListener('close', onUnexpectedEnd);
var userPrefix = results[0]
, part = results[1]
, filename = part.filename
, destPrefix = (userPrefix) ? '/' + userPrefix + '/' : '/'
, destPath = encodeURI(destPrefix + uuid.v1() + '/' + filename)
, type = mime.lookup(destPath)
;
headers['Content-Length'] = part.byteCount;
headers['Content-Type'] = type;
self._s3Client.putStream(part, destPath, headers, function (err, s3Response) {
if (err) {
if(callback){
callback(err, s3Response);
} else {
res.writeHead(500, {'content-type': 'application/json'});
res.end(JSON.stringify({ statusCode: 500, error: err.toString() }));
}
return;
}
res.writeHead(res.statusCode, {'content-type': contentType});
if (s3Response.statusCode === 200) {
if(callback){
s3Response.custom_uri = {
uri: prefix + destPath,
type: type
};
callback(null, s3Response);
} else {
res.end(JSON.stringify({ statusCode: 200, uri: prefix + '/raw' + destPath, type: type }));
}
}
else {
var bufs = [];
s3Response.on('data', function (d){ bufs.push(d); });
s3Response.on('end', function () {
// just return the ugly xml body for now
var body =Buffer.concat(bufs).toString();
if(callback){
callback(null, s3Response);
}else {
res.end(JSON.stringify({ statusCode: s3Response.statusCode, error: body }));
}
});
}
});
});
form.on('close', onUnexpectedEnd);
form.on('error', function(err) {
//just log the errors for now
console.log('multipart error: ' + err);
});
form.parse(req);
};
};
this.serveImage = function (opts) {
if (!opts) opts = {};
opts.prefix = opts.prefix || "";
opts.cacheMaxAge = opts.cacheMaxAge || 220752000; // 1year, 60*60*24*7*365
return function (req, res) {
var url = req.url.substring(opts.prefix.length);
//20-20 min
//20x20 resize, center crop
//20+20 max
var parts = url.split('/');
var sizeOptions = parts[1];
var path = '/' + parts.slice(2).join('/');
self._s3Client.get(path).on('response', function(s3res){
if (opts.cacheMaxAge) {
res.setHeader('Cache-Control', 'public, max-age=' + opts.cacheMaxAge);
}
s3res.on('error', function (err) {
self._handleError(500, res, err);
});
if (s3res.statusCode !== 200) {
return self._handleError(s3res.statusCode, res, new Error('not found'));
}
res.setHeader('Content-Type', s3res.headers['content-type']);
res.setHeader('transfer-encoding', 'chunked');
if (sizeOptions === 'raw') {
if (s3res.headers['content-length']) {
res.setHeader('Content-Length', s3res.headers['content-length']);
}
return s3res.pipe(res);
}
self._transform(gm(s3res), sizeOptions).stream().pipe(res);
})
.on('error', function (err) {
self._handleError(500, res, err);
})
.end();
};
};
this.serveFile = function (opts) {
if (!opts) opts = {};
opts.prefix = opts.prefix || "";
opts.cacheMaxAge = opts.cacheMaxAge || 220752000; // 1year, 60*60*24*7*365
return function (req, res) {
var url = req.url.substring(opts.prefix.length);
self._s3Client.get(url).on('response', function(s3res){
if (opts.cacheMaxAge) {
res.setHeader('Cache-Control: max-age', opts.cacheMaxAge); // 1 week
}
s3res.on('error', function (err) {
self._handleError(500, res, err);
});
res.setHeader('Content-Type', s3res.headers['content-type']);
if (s3res.headers['content-length']) {
res.setHeader('Content-Length', s3res.headers['content-length']);
}
return s3res.pipe(res);
})
.on('error', function (err) {
self._handleError(500, res, err);
})
.end();
};
};
this.deleteFile = function(opts){
if (!opts) opts = {};
opts.prefix = opts.prefix || "";
return function(req, res, uri, cb) {
cb = cb === undefined ? null : cb;
self._s3Client.del(uri).on('response', function(s3res){
s3res.on('error', function (err) {
self._handleError(500, res, err);
});
return s3res.pipe(res);
}).on('error', function(err){
self._handleError(500, res, err);
}).end();
}; // end of return function object
}; // end of deleteFile
this._handleError = function (code, res, err) {
res.writeHead(code, {'content-type': 'application/json'});
res.end(JSON.stringify({ statusCode: code, error: err.toString() }));
};
this._transform = function (obj, optionsString) {
var size, w, h;
if (optionsString.indexOf('x') > -1) {
size = optionsString.split('x'); w = size[0]; h = size[1];
return obj.resize(w, h, '^').gravity('Center').crop(w, h, 0, 0);
}
else if (optionsString.indexOf('+') > -1) {
size = optionsString.split('+'); w = size[0]; h = size[1];
return obj.resize(w, h, '^');
}
else if (optionsString.indexOf('-') > -1) {
size = optionsString.split('-'); w = size[0]; h = size[1];
return obj.resize(w, h);
}
else {
return obj;
}
};
};