forked from joe1chen/nodebb-plugin-s3-uploads
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
309 lines (251 loc) · 7.59 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
var Package = require("./package.json");
var AWS = require('aws-sdk'),
mime = require("mime"),
uuid = require("uuid").v4,
fs = require('fs'),
request = require('request'),
path = require('path'),
winston = module.parent.require('winston'),
gm = module.parent.require('gm').subClass({imageMagick: true}),
meta = module.parent.require('./meta'),
db = module.parent.require('./database');
(function(plugin) {
"use strict";
var S3Conn = null;
var settings = {
"accessKeyId": false,
"secretAccessKey": false,
"region": process.env.AWS_DEFAULT_REGION || 'us-east-1',
"bucket": process.env.S3_UPLOADS_BUCKET || undefined,
"host": process.env.S3_UPLOADS_HOST || 's3.amazonaws.com',
"path": process.env.S3_UPLOADS_PATH || undefined
};
var accessKeyIdFromDb = false;
var secretAccessKeyFromDb = false;
var adminRoute = '/admin/plugins/s3-uploads';
function fetchSettings(callback){
db.getObjectFields(Package.name, Object.keys(settings), function(err, newSettings){
if (err) {
winston.error(err.message);
if (typeof callback === 'function') {
callback(err);
}
return;
}
accessKeyIdFromDb = false;
secretAccessKeyFromDb = false;
if(newSettings.accessKeyId){
settings.accessKeyId = newSettings.accessKeyId;
accessKeyIdFromDb = true;
}else{
settings.accessKeyId = false;
}
if(newSettings.secretAccessKey){
settings.secretAccessKey = newSettings.secretAccessKey;
secretAccessKeyFromDb = false;
}else{
settings.secretAccessKey = false;
}
if(!newSettings.bucket){
settings.bucket = process.env.S3_UPLOADS_BUCKET || "";
}else{
settings.bucket = newSettings.bucket;
}
if(!newSettings.host){
settings.host = process.env.S3_UPLOADS_HOST || "";
}else{
settings.host = newSettings.host;
}
if(!newSettings.path){
settings.path = process.env.S3_UPLOADS_PATH || "";
}else{
settings.path = newSettings.path;
}
if(settings.accessKeyId && settings.secretAccessKey){
AWS.config.update({
accessKeyId: settings.accessKeyId,
secretAccessKey: settings.secretAccessKey
});
}
if (settings.region) {
AWS.config.update({
region: settings.region
});
}
if (typeof callback === 'function') {
callback();
}
});
}
function S3(){
if(!S3Conn){
S3Conn = new AWS.S3();
}
return S3Conn;
}
function makeError(err){
if(err instanceof Error){
err.message = Package.name + " :: " + err.message;
}else{
err = new Error(Package.name + " :: " + err);
}
winston.error(err.message);
return err;
}
plugin.activate = function(){
fetchSettings();
};
plugin.deactivate = function(){
S3Conn = null;
};
plugin.load = function(params, callback){
fetchSettings(function(err) {
if (err) {
return winston.error(err.message);
}
params.router.get(adminRoute, params.middleware.applyCSRF, params.middleware.admin.buildHeader, renderAdmin);
params.router.get('/api' + adminRoute, params.middleware.applyCSRF, renderAdmin);
params.router.post('/api' + adminRoute + '/s3settings', s3settings);
params.router.post('/api' + adminRoute + '/credentials', credentials);
callback();
});
};
function renderAdmin(req, res) {
// Regenerate csrf token
var token = req.csrfToken();
var data = {
bucket: settings.bucket,
host: settings.host,
path: settings.path,
region: settings.region,
accessKeyId: (accessKeyIdFromDb && settings.accessKeyId) || '',
secretAccessKey: (accessKeyIdFromDb && settings.secretAccessKey) || '',
csrf: token
};
res.render('admin/plugins/s3-uploads', data);
}
function s3settings(req, res, next) {
var data = req.body;
var newSettings = {
bucket: data.bucket || '',
host: data.host || '',
path: data.path || '',
region: data.region || ''
};
saveSettings(newSettings, res, next);
}
function credentials(req, res, next) {
var data = req.body;
var newSettings = {
accessKeyId: data.accessKeyId || '',
secretAccessKey: data.secretAccessKey || ''
};
saveSettings(newSettings, res, next);
}
function saveSettings(settings, res, next) {
db.setObject(Package.name, settings, function(err) {
if (err) {
return next(makeError(err));
}
fetchSettings();
res.json('Saved!');
});
}
plugin.uploadImage = function (data, callback) {
var image = data.image;
if (!image) {
return callback(new Error('invalid image'));
}
var type = image.url ? 'url' : 'file';
if (type === 'file') {
if (!image.path) {
return callback(new Error('invalid image path'));
}
fs.readFile(image.path, function(err, buffer) {
uploadToS3(image.name, err, buffer, callback);
});
}
else {
var filename = image.url.split('/').pop();
var imageDimension = parseInt(meta.config.profileImageDimension, 10) || 128;
// Resize image.
gm(request(image.url), filename)
.resize(imageDimension + "^", imageDimension + "^")
.stream(function(err, stdout, stderr) {
if (err) {
return callback(makeError(err));
}
// This is sort of a hack - We're going to stream the gm output to a buffer and then upload.
// See https://github.com/aws/aws-sdk-js/issues/94
var buf = new Buffer(0);
stdout.on('data', function(d) {
buf = Buffer.concat([buf, d]);
});
stdout.on('end', function() {
uploadToS3(filename, null, buf, callback);
});
}
);
}
};
plugin.uploadFile = function (data, callback) {
var file = data.file;
if (!file) {
return callback(new Error('invalid file'));
}
if (!file.path) {
return callback(new Error('invalid file path'));
}
fs.readFile(file.path, function(err, buffer) {
uploadToS3(file.name, err, buffer, callback);
});
};
function uploadToS3(filename, err, buffer, callback) {
if (err) {
return callback(makeError(err));
}
var s3Path;
if (settings.path && 0 < settings.path.length) {
s3Path = settings.path;
if (!s3Path.match(/\/$/)) {
// Add trailing slash
s3Path = s3Path + '/';
}
}
else {
s3Path = '/';
}
var s3KeyPath = s3Path.replace(/^\//, ''); // S3 Key Path should not start with slash.
var params = {
Bucket: settings.bucket,
ACL: "public-read",
Key: s3KeyPath + uuid() + path.extname(filename),
Body: buffer,
ContentLength: buffer.length,
ContentType: mime.lookup(filename)
};
S3().putObject(params, function(err) {
if (err) {
return callback(makeError(err));
}
var host = 's3.amazonaws.com';
if (settings.host && 0 < settings.host.length) {
host = settings.host;
}
callback(null, {
name: filename,
// Use protocol-less urls so that both HTTP and HTTPS work:
url: '//' + host + '/' + params.Bucket + '/' + params.Key,
});
});
}
var admin = plugin.admin = {};
admin.menu = function(headers, callback) {
headers.plugins.push({
"route": '/plugins/s3-uploads',
"icon": 'fa-picture-o',
"name": 'S3 Uploads'
});
callback(null, headers);
};
}(module.exports));