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

remote.js 1.6KB

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