Turn audio into a shareable video. forked from nypublicradio/audiogram

remote.js 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. var AWS = require("aws-sdk"),
  2. fs = require("fs");
  3. module.exports = function(bucket, storagePath) {
  4. var s3Options = { params: { Bucket: bucket } };
  5. if (process.env.S3_ENDPOINT) {
  6. s3Options.endpoint = process.env.S3_ENDPOINT;
  7. }
  8. var s3 = new AWS.S3(s3Options);
  9. // Test credentials
  10. s3.headBucket({}, function(err){ if (err) { throw err; } });
  11. function upload(source, key, cb) {
  12. var params = {
  13. Key: storagePath + key,
  14. Body: fs.createReadStream(source)
  15. };
  16. // gzipping results in inconsistent file size :(
  17. s3.putObject(params, cb);
  18. }
  19. function download(key, destination, cb) {
  20. var file = fs.createWriteStream(destination)
  21. .on("error", cb)
  22. .on("close", cb);
  23. s3.getObject({ Key: storagePath + key })
  24. .createReadStream()
  25. .pipe(file);
  26. }
  27. function clean(cb) {
  28. s3.listObjects({ Prefix: storagePath }, function(err, data){
  29. if (err || !data.Contents || !data.Contents.length) {
  30. return cb(err);
  31. }
  32. var objects = data.Contents.map(function(obj) {
  33. return { Key: obj.Key };
  34. });
  35. deleteObjects(objects, !!data.IsTruncated, cb);
  36. });
  37. }
  38. function deleteObjects(objects, truncated, cb) {
  39. s3.deleteObjects({ Delete: { Objects: objects } }, function(err, data){
  40. if (err) {
  41. return cb(err);
  42. }
  43. if (truncated) {
  44. return clean(cb);
  45. }
  46. return cb(null);
  47. });
  48. }
  49. // TODO make this more configurable
  50. function getURL(id) {
  51. return "https://" + bucket + "/" + storagePath + "video/" + id + ".mp4";
  52. }
  53. return {
  54. upload: upload,
  55. download: download,
  56. getURL: getURL,
  57. clean: clean
  58. };
  59. };