2017-04-07 01:29:05 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var fs = require('fs');
|
|
|
|
var config = require('config');
|
2018-03-30 22:34:27 +02:00
|
|
|
var s3 = null;
|
2017-04-07 01:29:05 +02:00
|
|
|
|
2018-01-08 12:43:47 +01:00
|
|
|
// use AWS S3 or local folder depending on config
|
|
|
|
if (config.get("storage_local_path")) {
|
|
|
|
var AWS = require('mock-aws-s3');
|
|
|
|
AWS.config.basePath = config.get("storage_local_path");
|
2018-03-30 22:34:27 +02:00
|
|
|
s3 = new AWS.S3();
|
2018-01-08 12:43:47 +01:00
|
|
|
} else {
|
|
|
|
var AWS = require('aws-sdk');
|
2018-03-30 22:34:27 +02:00
|
|
|
var storage_endpoint = config.get("storage_endpoint");
|
|
|
|
const ep = new AWS.Endpoint(storage_endpoint);
|
2017-04-07 13:07:09 +02:00
|
|
|
|
2018-03-30 22:34:27 +02:00
|
|
|
AWS.config.update(new AWS.Config({
|
|
|
|
accessKeyId: process.env.MINIO_ACCESS_KEY,
|
|
|
|
secretAccessKey: process.env.MINIO_SECRET_KEY,
|
|
|
|
region: config.get("storage_region"),
|
|
|
|
s3ForcePathStyle: true,
|
|
|
|
signatureVersion: 'v4'
|
|
|
|
}));
|
|
|
|
s3 = new AWS.S3({
|
|
|
|
endpoint: ep
|
|
|
|
});
|
2018-01-08 12:43:47 +01:00
|
|
|
}
|
|
|
|
|
2017-04-07 18:01:23 +02:00
|
|
|
s3.createBucket({
|
|
|
|
Bucket: config.get("storage_bucket"),
|
|
|
|
ACL: "public-read",
|
|
|
|
GrantRead: "*"
|
|
|
|
}, (err,res) => {
|
|
|
|
console.log("createBucket",err,res);
|
|
|
|
});
|
|
|
|
|
2017-04-07 01:29:05 +02:00
|
|
|
module.exports = {
|
|
|
|
removeFile: (path, callback) => {
|
|
|
|
const bucket = config.get("storage_bucket");
|
|
|
|
s3.deleteObject({
|
|
|
|
Bucket: bucket, Key: path
|
|
|
|
}, (err, res) => {
|
|
|
|
if (err){
|
|
|
|
console.error(err);
|
|
|
|
callback(err);
|
|
|
|
}else {
|
|
|
|
callback(null, res);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
},
|
|
|
|
uploadFile: function(fileName, mime, localFilePath, callback) {
|
|
|
|
if (typeof(localFilePath)!="string") {
|
|
|
|
callback({error:"missing path"}, null);
|
|
|
|
return;
|
|
|
|
}
|
2017-04-07 13:07:09 +02:00
|
|
|
console.log("[storage] uploading", localFilePath, " to ", fileName);
|
2017-04-07 01:29:05 +02:00
|
|
|
|
|
|
|
const bucket = config.get("storage_bucket");
|
|
|
|
const fileStream = fs.createReadStream(localFilePath);
|
|
|
|
fileStream.on('error', function (err) {
|
|
|
|
if (err) {
|
|
|
|
console.error(err);
|
|
|
|
callback(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
fileStream.on('open', function () {
|
|
|
|
s3.putObject({
|
|
|
|
Bucket: bucket,
|
|
|
|
Key: fileName,
|
|
|
|
ContentType: mime,
|
|
|
|
Body: fileStream
|
|
|
|
}, function (err) {
|
|
|
|
if (err){
|
|
|
|
console.error(err);
|
|
|
|
callback(err);
|
2018-03-30 22:34:27 +02:00
|
|
|
} else {
|
2018-01-08 12:43:47 +01:00
|
|
|
const url = config.get("storage_cdn") + "/" + fileName;
|
2017-04-07 01:29:05 +02:00
|
|
|
console.log("[s3]" + localFilePath + " to " + url);
|
|
|
|
callback(null, url);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|