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

remote.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. var AWS = require("aws-sdk"),
  2. fs = require("fs");
  3. module.exports = function(bucket, storagePath) {
  4. storagePath = storagePath || "";
  5. // Normalize slashes in path
  6. if (storagePath.length) {
  7. storagePath = storagePath.replace(/^\/|\/$/g, "") + "/";
  8. }
  9. // Catch single slash path
  10. if (storagePath === "/") {
  11. storagePath = "";
  12. }
  13. // Remove s3:// just in case
  14. bucket = bucket.replace(/^(s3[:]\/\/)|\/$/g, "");
  15. var s3 = new AWS.S3({ params: { Bucket: bucket } });
  16. // Test credentials
  17. s3.headBucket({}, function(err){ if (err) { throw err; } });
  18. function upload(source, key, cb) {
  19. var params = {
  20. Key: storagePath + key,
  21. Body: fs.createReadStream(source),
  22. ACL: "public-read"
  23. };
  24. // gzipping results in inconsistent file size :(
  25. s3.upload(params, cb);
  26. }
  27. function download(key, destination, cb) {
  28. var file = fs.createWriteStream(destination)
  29. .on("error", cb)
  30. .on("close", cb);
  31. s3.getObject({ Key: storagePath + key })
  32. .createReadStream()
  33. .pipe(file);
  34. }
  35. function clean(cb) {
  36. s3.listObjects({ Prefix: storagePath }, function(err, data){
  37. if (err || !data.Contents || !data.Contents.length) {
  38. return cb(err);
  39. }
  40. var objects = data.Contents.map(function(obj) {
  41. return { Key: obj.Key };
  42. });
  43. deleteObjects(objects, !!data.IsTruncated, cb);
  44. });
  45. }
  46. function deleteObjects(objects, truncated, cb) {
  47. s3.deleteObjects({ Delete: { Objects: objects } }, function(err, data){
  48. if (err) {
  49. return cb(err);
  50. }
  51. if (truncated) {
  52. return clean(cb);
  53. }
  54. return cb(null);
  55. });
  56. }
  57. // TODO make this more configurable
  58. function getURL(id) {
  59. return "https://s3.amazonaws.com/" + bucket + "/" + storagePath + "video/" + id + ".mp4";
  60. }
  61. return {
  62. upload: upload,
  63. download: download,
  64. getURL: getURL,
  65. clean: clean
  66. };
  67. };