p5.js-web-editor/server/controllers/aws.controller.js

88 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-07-16 01:05:18 +02:00
import uuid from 'node-uuid';
import policy from 's3-policy';
import s3 from 's3';
const client = s3.createClient({
maxAsyncS3: 20,
s3RetryCount: 3,
s3RetryDelay: 1000,
multipartUploadThreshold: 20971520, // this is the default (20 MB)
multipartUploadSize: 15728640, // this is the default (15 MB)
s3Options: {
accessKeyId: `${process.env.AWS_ACCESS_KEY}`,
secretAccessKey: `${process.env.AWS_SECRET_KEY}`,
},
});
const s3Bucket = `https://s3-us-west-2.amazonaws.com/${process.env.S3_BUCKET}/`;
2016-07-16 01:05:18 +02:00
function getExtension(filename) {
const i = filename.lastIndexOf('.');
return (i < 0) ? '' : filename.substr(i);
}
export function deleteObjectsFromS3(keyList, callback) {
const keys = keyList.map((key) => { return { Key: key }; }); // eslint-disable-line
if (keyList.length > 0) {
2017-03-30 18:14:07 +02:00
const params = {
Bucket: `${process.env.S3_BUCKET}`,
Delete: {
Objects: keys,
2017-03-30 18:14:07 +02:00
},
};
const del = client.deleteObjects(params);
del.on('end', () => {
if (callback) {
2017-03-30 18:14:07 +02:00
callback();
}
});
} else if (callback) {
callback();
2017-03-30 18:14:07 +02:00
}
}
export function deleteObjectFromS3(req, res) {
const objectKey = req.params.object_key;
deleteObjectsFromS3([objectKey], () => {
res.json({ success: true });
});
}
2016-07-16 01:05:18 +02:00
export function signS3(req, res) {
2017-01-11 21:50:36 +01:00
const fileExtension = getExtension(req.body.name);
const filename = uuid.v4() + fileExtension;
const acl = 'public-read';
const p = policy({
acl,
secret: process.env.AWS_SECRET_KEY,
length: 5000000, // in bytes?
bucket: process.env.S3_BUCKET,
key: filename,
expires: new Date(Date.now() + 60000),
});
const result = {
AWSAccessKeyId: process.env.AWS_ACCESS_KEY,
key: `${req.body.userId}/${filename}`,
2017-01-11 21:50:36 +01:00
policy: p.policy,
signature: p.signature
};
2016-07-16 01:05:18 +02:00
return res.json(result);
}
export function copyObjectInS3(req, res) {
const url = req.body.url;
const objectKey = url.split('/').pop();
const fileExtension = getExtension(objectKey);
const newFilename = uuid.v4() + fileExtension;
const params = {
Bucket: `${process.env.S3_BUCKET}`,
CopySource: `${process.env.S3_BUCKET}/${objectKey}`,
2017-03-23 19:50:47 +01:00
Key: newFilename
};
const copy = client.copyObject(params);
copy.on('end', () => {
res.json({ url: `${s3Bucket}${newFilename}` });
});
}