forked from FreshConsulting/dpd-imageWrangler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
263 lines (240 loc) · 7.13 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
/*jslint node: true */
'use strict';
/**
* Module dependencies
*/
var Resource = require('deployd/lib/resource'),
Session = require('deployd/lib/session'),
util = require('util'),
formidable = require('formidable'),
fs = require('fs'),
path = require('path'),
Minio = require('minio'),
gm = require('gm')
;
/**
* Module setup.
*/
function ImageWrangler( name, options ) {
Resource.apply( this, arguments );
if (this.config.accessKey && this.config.accessSecret && this.config.bucket) {
this.client = new Minio.Client({
endPoint: this.config.endpoint,
port: this.config.point,
useSSL: this.config.useSSL,
accessKey: this.config.accessKey,
secretKey: this.config.accessSecret
});
}
}
util.inherits( ImageWrangler, Resource );
ImageWrangler.prototype.clientGeneration = true;
ImageWrangler.events = ['post'];
ImageWrangler.basicDashboard = {
settings: [
{
name : 'accessKey',
type : 'text',
description : 'The Minio access key id'
}, {
name : 'accessSecret',
type : 'text',
description : 'The Minio secret access key'
}, {
name : 'port',
type : 'text',
description : 'The minio port'
}, {
name : 'useSSL',
type : 'checkbox',
description : 'Use SSL to connect to minio?'
}, {
name : 'endpoint',
type : 'text',
description : 'The Minio endpoint address'
}, {
name : 'tasks',
type : 'object',
description : 'JSON array of objects detailing the image specs to be created for each image uploaded to this endpoint'
}, {
name : 'bucket',
type : 'text',
}, {
name : 'basePath',
type : 'text',
description : 'base url for where someone could GET the file off the bucket (cloud front url if you are using that)'
}, {
name : 'publicRead',
type : 'checkbox',
description : 'when files are uploaded to your bucket, automatically set public read access?'
}, {
name : 'internalOnly',
type : 'checkbox',
description : 'Only allow internal scripts to send email'
}, {
name : 'imageQuality',
type : 'text',
description : '0-100 (default 95)'
}, {
name : 'crop',
type : 'checkbox',
description : 'center crop image if necessary'
}
]
};
/**
* Module methodes
*/
ImageWrangler.prototype.handle = function ( ctx, next ) {
var req = ctx.req;
var domain = {url: ctx.url};
var wrangler = this;
var parts = ctx.url.split('/').filter(function(p) { return p; });
var subDirPath = '';
if (parts.length > 0) subDirPath = parts.join('/');
if (!this.config.basePath)this.config.basePath = '';
if ( !ctx.req.internal && this.config.internalOnly ) {
return ctx.done({ statusCode: 403, message: 'Forbidden' });
}
var resizeTasks = JSON.parse(this.config.tasks);
if (req.method === 'POST' && !req.internal && req.headers['content-type'].indexOf('multipart/form-data') === 0) {
var form = new formidable.IncomingForm();
var remaining = 0;
var files = [];
var error;
var lastFile;
var responseObject = {};
var cleanseFilename = function(incomingFilename){
console.log("incoming filename: "+incomingFilename);
var filename = incomingFilename;
var extension = null;
if(incomingFilename.indexOf('.') != -1){
var pieces = incomingFilename.split('.');
extension = pieces.pop();
filename = pieces.join('.');
}
console.log("filename: "+filename);
console.log('extension: '+extension);
filename = filename.replace(/\s+/g, '-').toLowerCase(); //converst space to dash
console.log('replaced spaces with dashes: '+filename);
filename = filename.replace(/[^a-z0-9_\-]/gi, ''); // drop all other funny business
console.log('dropped bad characters: '+filename);
if(extension){
console.log('completed result: '+filename+'.'+extension);
return filename+'.'+extension;
}
return filename;
};
var resizeFile = function(){
if (resizeTasks.length>0) {
var task = resizeTasks.pop();
console.log('task: '+JSON.stringify(task));
var output = cleanseFilename(lastFile.name).split('.');
var outputName = output[0]+'-'+task.suffix+'.'+output[1];
output = lastFile.path.split('/');
output.pop();
var outputPath = output.join('/')+'/'+outputName;
var quality = 95;
if(wrangler.config.imageQuality){
quality = wrangler.config.imageQuality;
}
var completionBlock = function (err) {
if (!err) {
responseObject[task.suffix] = wrangler.config.basePath+subDirPath+'/'+outputName;
var stat = fs.statSync(outputPath);
wrangler.uploadFile('/'+subDirPath+'/'+outputName, stat.size, lastFile.type, fs.createReadStream(outputPath), resizeFile);
}else{
console.log(' error writing: '+err);
ctx.done(err);
}
};
if (wrangler.config.crop) {
gm(lastFile.path)
.quality(quality)
.autoOrient()
.resize(task.width, task.height, '^')
.gravity('Center')
.extent(task.width, task.height)
.write(outputPath, completionBlock);
}else{
gm(lastFile.path)
.quality(quality)
.autoOrient()
.resize(task.width, task.height)
.write(outputPath, completionBlock);
}
}else{
if (req.headers.referer) {
ctx.done(null, responseObject);
} else {
ctx.done(null, files);
}
}
};
form.parse(req)
.on('file', function(name, file) {
remaining++;
lastFile = file;
//write original version to s3 for safe keeping
var output = cleanseFilename(file.name).split('.');
var outputName = output[0]+'-original.'+output[1];
wrangler.uploadFile('/'+subDirPath+'/'+outputName, file.size, lastFile.type, fs.createReadStream(file.path), resizeFile);
})
.on('error', function(err) {
ctx.done(err);
error = err;
});
req.resume();
return;
}
next();
};
ImageWrangler.prototype.uploadFile = function(filename, filesize, mime, stream, fn) {
var bucket = this;
console.log('filename:'+filename);
console.log('fileSize:'+filesize);
console.log('mime:'+mime);
/*
this.client.putStream(stream, filename, headers, function(err, res) {
console.log('res: '+res.statusCode);
if (err){
fn(err);
}else{
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
fn(err || message);
});
} else {
fn();
}
}
});*/
var metaData = {
'Content-Type': mime,
}
if(this.config.publicRead){
metaData['x-amz-acl'] = 'public-read';
}
minioClient.fPutObject(this.config.bucket, filename, stream, metaData, function(err, etag) {
return console.log(err, etag) // err should be null
if (err){
fn(err);
}else{
fn();
}
})
};
ImageWrangler.prototype.readStream = function(stream, fn) {
var buffer = '';
stream.on('data', function(data) {
buffer += data;
}).on('end', function() {
fn(null, buffer);
}).on('error', function(err) {
fn(err);
});
};
/**
* Module export
*/
module.exports = ImageWrangler;