createOnAfterUpload.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import { Meteor } from 'meteor/meteor';
  2. import { _ } from 'meteor/underscore';
  3. import { Random } from 'meteor/random';
  4. import { FilesCollection } from 'meteor/ostrio:files';
  5. import stream from 'stream';
  6. import S3 from 'aws-sdk/clients/s3'; /* http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html */
  7. /* See fs-extra and graceful-fs NPM packages */
  8. /* For better i/o performance */
  9. import fs from 'fs';
  10. /* Example: S3='{"s3":{"key": "xxx", "secret": "xxx", "bucket": "xxx", "region": "xxx""}}' meteor */
  11. if (process.env.S3) {
  12. Meteor.settings.s3 = JSON.parse(process.env.S3).s3;
  13. const s3Conf = Meteor.settings.s3 || {};
  14. const bound = Meteor.bindEnvironment((callback) => {
  15. return callback();
  16. });
  17. /* Check settings existence in `Meteor.settings` */
  18. /* This is the best practice for app security */
  19. if (s3Conf && s3Conf.key && s3Conf.secret && s3Conf.bucket && s3Conf.region) {
  20. // Create a new S3 object
  21. const s3 = new S3({
  22. secretAccessKey: s3Conf.secret,
  23. accessKeyId: s3Conf.key,
  24. region: s3Conf.region,
  25. // sslEnabled: true, // optional
  26. httpOptions: {
  27. timeout: 6000,
  28. agent: false
  29. }
  30. });
  31. // Declare the Meteor file collection on the Server
  32. const UserFiles = new FilesCollection({
  33. debug: false, // Change to `true` for debugging
  34. storagePath: 'assets/app/uploads/uploadedFiles',
  35. collectionName: 'userFiles',
  36. // Disallow Client to execute remove, use the Meteor.method
  37. allowClientCode: false,
  38. // Start moving files to AWS:S3
  39. // after fully received by the Meteor server
  40. onAfterUpload(fileRef) {
  41. // Run through each of the uploaded file
  42. _.each(fileRef.versions, (vRef, version) => {
  43. // We use Random.id() instead of real file's _id
  44. // to secure files from reverse engineering on the AWS client
  45. const filePath = 'files/' + (Random.id()) + '-' + version + '.' + fileRef.extension;
  46. // Create the AWS:S3 object.
  47. // Feel free to change the storage class from, see the documentation,
  48. // `STANDARD_IA` is the best deal for low access files.
  49. // Key is the file name we are creating on AWS:S3, so it will be like files/XXXXXXXXXXXXXXXXX-original.XXXX
  50. // Body is the file stream we are sending to AWS
  51. s3.putObject({
  52. // ServerSideEncryption: 'AES256', // Optional
  53. StorageClass: 'STANDARD',
  54. Bucket: s3Conf.bucket,
  55. Key: filePath,
  56. Body: fs.createReadStream(vRef.path),
  57. ContentType: vRef.type,
  58. }, (error) => {
  59. bound(() => {
  60. if (error) {
  61. console.error(error);
  62. } else {
  63. // Update FilesCollection with link to the file at AWS
  64. const upd = { $set: {} };
  65. upd['$set']['versions.' + version + '.meta.pipePath'] = filePath;
  66. this.collection.update({
  67. _id: fileRef._id
  68. }, upd, (updError) => {
  69. if (updError) {
  70. console.error(updError);
  71. } else {
  72. // Unlink original files from FS after successful upload to AWS:S3
  73. this.unlink(this.collection.findOne(fileRef._id), version);
  74. }
  75. });
  76. }
  77. });
  78. });
  79. });
  80. },
  81. // Intercept access to the file
  82. // And redirect request to AWS:S3
  83. interceptDownload(http, fileRef, version) {
  84. let path;
  85. if (fileRef && fileRef.versions && fileRef.versions[version] && fileRef.versions[version].meta && fileRef.versions[version].meta.pipePath) {
  86. path = fileRef.versions[version].meta.pipePath;
  87. }
  88. if (path) {
  89. // If file is successfully moved to AWS:S3
  90. // We will pipe request to AWS:S3
  91. // So, original link will stay always secure
  92. // To force ?play and ?download parameters
  93. // and to keep original file name, content-type,
  94. // content-disposition, chunked "streaming" and cache-control
  95. // we're using low-level .serve() method
  96. const opts = {
  97. Bucket: s3Conf.bucket,
  98. Key: path
  99. };
  100. if (http.request.headers.range) {
  101. const vRef = fileRef.versions[version];
  102. let range = _.clone(http.request.headers.range);
  103. const array = range.split(/bytes=([0-9]*)-([0-9]*)/);
  104. const start = parseInt(array[1]);
  105. let end = parseInt(array[2]);
  106. if (isNaN(end)) {
  107. // Request data from AWS:S3 by small chunks
  108. end = (start + this.chunkSize) - 1;
  109. if (end >= vRef.size) {
  110. end = vRef.size - 1;
  111. }
  112. }
  113. opts.Range = `bytes=${start}-${end}`;
  114. http.request.headers.range = `bytes=${start}-${end}`;
  115. }
  116. const fileColl = this;
  117. s3.getObject(opts, function (error) {
  118. if (error) {
  119. console.error(error);
  120. if (!http.response.finished) {
  121. http.response.end();
  122. }
  123. } else {
  124. if (http.request.headers.range && this.httpResponse.headers['content-range']) {
  125. // Set proper range header in according to what is returned from AWS:S3
  126. http.request.headers.range = this.httpResponse.headers['content-range'].split('/')[0].replace('bytes ', 'bytes=');
  127. }
  128. const dataStream = new stream.PassThrough();
  129. fileColl.serve(http, fileRef, fileRef.versions[version], version, dataStream);
  130. dataStream.end(this.data.Body);
  131. }
  132. });
  133. return true;
  134. }
  135. // While file is not yet uploaded to AWS:S3
  136. // It will be served file from FS
  137. return false;
  138. }
  139. });
  140. // Intercept FilesCollection's remove method to remove file from AWS:S3
  141. const _origRemove = UserFiles.remove;
  142. UserFiles.remove = function (selector, callback) {
  143. const cursor = this.collection.find(selector);
  144. cursor.forEach((fileRef) => {
  145. _.each(fileRef.versions, (vRef) => {
  146. if (vRef && vRef.meta && vRef.meta.pipePath) {
  147. // Remove the object from AWS:S3 first, then we will call the original FilesCollection remove
  148. s3.deleteObject({
  149. Bucket: s3Conf.bucket,
  150. Key: vRef.meta.pipePath,
  151. }, (error) => {
  152. bound(() => {
  153. if (error) {
  154. console.error(error);
  155. }
  156. });
  157. });
  158. }
  159. });
  160. });
  161. // Remove original file from database
  162. _origRemove.call(this, selector, callback);
  163. };
  164. } else {
  165. throw new Meteor.Error(401, 'Missing Meteor file settings');
  166. }
  167. }