fileStoreStrategy.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { createObjectId } from './grid/createObjectId';
  4. import { httpStreamOutput } from './httpStream.js';
  5. //import {} from './s3/Server-side-file-store.js';
  6. import { ObjectID } from 'bson';
  7. var Minio = require('minio');
  8. export const STORAGE_NAME_FILESYSTEM = "fs";
  9. export const STORAGE_NAME_GRIDFS = "gridfs";
  10. export const STORAGE_NAME_S3 = "s3";
  11. /** Factory for FileStoreStrategy */
  12. export default class FileStoreStrategyFactory {
  13. /** constructor
  14. * @param classFileStoreStrategyFilesystem use this strategy for filesystem storage
  15. * @param storagePath file storage path
  16. * @param classFileStoreStrategyGridFs use this strategy for GridFS storage
  17. * @param gridFsBucket use this GridFS Bucket as GridFS Storage
  18. * @param classFileStoreStrategyS3 use this strategy for S3 storage
  19. * @param s3Bucket use this S3 Bucket as S3 Storage
  20. */
  21. constructor(classFileStoreStrategyFilesystem, storagePath, classFileStoreStrategyGridFs, gridFsBucket, classFileStoreStrategyS3, s3Bucket) {
  22. this.classFileStoreStrategyFilesystem = classFileStoreStrategyFilesystem;
  23. this.storagePath = storagePath;
  24. this.classFileStoreStrategyGridFs = classFileStoreStrategyGridFs;
  25. this.gridFsBucket = gridFsBucket;
  26. this.classFileStoreStrategyS3 = classFileStoreStrategyS3;
  27. this.s3Bucket = s3Bucket;
  28. }
  29. /** returns the right FileStoreStrategy
  30. * @param fileObj the current file object
  31. * @param versionName the current version
  32. * @param use this storage, or if not set, get the storage from fileObj
  33. */
  34. getFileStrategy(fileObj, versionName, storage) {
  35. if (!storage) {
  36. storage = fileObj.versions[versionName].storage;
  37. if (!storage) {
  38. if (fileObj.meta.source == "import" || fileObj.versions[versionName].meta.gridFsFileId) {
  39. // uploaded by import, so it's in GridFS (MongoDB)
  40. storage = STORAGE_NAME_GRIDFS;
  41. } else if (fileObj && fileObj.versions && fileObj.versions[version] && fileObj.versions[version].meta && fileObj.versions[version].meta.pipePath) {
  42. storage = STORAGE_NAME_S3;
  43. } else {
  44. // newly uploaded, so it's at the filesystem
  45. storage = STORAGE_NAME_FILESYSTEM;
  46. }
  47. }
  48. }
  49. let ret;
  50. if ([STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS, STORAGE_NAME_S3].includes(storage)) {
  51. if (storage == STORAGE_NAME_FILESYSTEM) {
  52. ret = new this.classFileStoreStrategyFilesystem(fileObj, versionName);
  53. } else if (storage == STORAGE_NAME_S3) {
  54. ret = new this.classFileStoreStrategyS3(this.s3Bucket, fileObj, versionName);
  55. } else if (storage == STORAGE_NAME_GRIDFS) {
  56. ret = new this.classFileStoreStrategyGridFs(this.gridFsBucket, fileObj, versionName);
  57. }
  58. }
  59. return ret;
  60. }
  61. }
  62. /** Strategy to store files */
  63. class FileStoreStrategy {
  64. /** constructor
  65. * @param fileObj the current file object
  66. * @param versionName the current version
  67. */
  68. constructor(fileObj, versionName) {
  69. this.fileObj = fileObj;
  70. this.versionName = versionName;
  71. }
  72. /** after successfull upload */
  73. onAfterUpload() {
  74. }
  75. /** download the file
  76. * @param http the current http request
  77. * @param cacheControl cacheControl of FilesCollection
  78. */
  79. interceptDownload(http, cacheControl) {
  80. }
  81. /** after file remove */
  82. onAfterRemove() {
  83. }
  84. /** returns a read stream
  85. * @return the read stream
  86. */
  87. getReadStream() {
  88. }
  89. /** returns a write stream
  90. * @param filePath if set, use this path
  91. * @return the write stream
  92. */
  93. getWriteStream(filePath) {
  94. }
  95. /** writing finished
  96. * @param finishedData the data of the write stream finish event
  97. */
  98. writeStreamFinished(finishedData) {
  99. }
  100. /** returns the new file path
  101. * @param storagePath use this storage path
  102. * @return the new file path
  103. */
  104. getNewPath(storagePath, name) {
  105. if (!_.isString(name)) {
  106. name = this.fileObj.name;
  107. }
  108. const ret = path.join(storagePath, this.fileObj._id + "-" + this.versionName + "-" + name);
  109. return ret;
  110. }
  111. /** remove the file */
  112. unlink() {
  113. }
  114. /** rename the file (physical)
  115. * @li at database the filename is updated after this method
  116. * @param newFilePath the new file path
  117. */
  118. rename(newFilePath) {
  119. }
  120. /** return the storage name
  121. * @return the storage name
  122. */
  123. getStorageName() {
  124. }
  125. }
  126. /** Strategy to store attachments at GridFS (MongoDB) */
  127. export class FileStoreStrategyGridFs extends FileStoreStrategy {
  128. /** constructor
  129. * @param gridFsBucket use this GridFS Bucket
  130. * @param fileObj the current file object
  131. * @param versionName the current version
  132. */
  133. constructor(gridFsBucket, fileObj, versionName) {
  134. super(fileObj, versionName);
  135. this.gridFsBucket = gridFsBucket;
  136. }
  137. /** download the file
  138. * @param http the current http request
  139. * @param cacheControl cacheControl of FilesCollection
  140. */
  141. interceptDownload(http, cacheControl) {
  142. const readStream = this.getReadStream();
  143. const downloadFlag = http?.params?.query?.download;
  144. let ret = false;
  145. if (readStream) {
  146. ret = true;
  147. httpStreamOutput(readStream, this.fileObj.name, http, downloadFlag, cacheControl);
  148. }
  149. return ret;
  150. }
  151. /** after file remove */
  152. onAfterRemove() {
  153. this.unlink();
  154. super.onAfterRemove();
  155. }
  156. /** returns a read stream
  157. * @return the read stream
  158. */
  159. getReadStream() {
  160. const gfsId = this.getGridFsObjectId();
  161. let ret;
  162. if (gfsId) {
  163. ret = this.gridFsBucket.openDownloadStream(gfsId);
  164. }
  165. return ret;
  166. }
  167. /** returns a write stream
  168. * @param filePath if set, use this path
  169. * @return the write stream
  170. */
  171. getWriteStream(filePath) {
  172. const fileObj = this.fileObj;
  173. const versionName = this.versionName;
  174. const metadata = { ...fileObj.meta, versionName, fileId: fileObj._id };
  175. const ret = this.gridFsBucket.openUploadStream(this.fileObj.name, {
  176. contentType: fileObj.type || 'binary/octet-stream',
  177. metadata,
  178. });
  179. return ret;
  180. }
  181. /** writing finished
  182. * @param finishedData the data of the write stream finish event
  183. */
  184. writeStreamFinished(finishedData) {
  185. const gridFsFileIdName = this.getGridFsFileIdName();
  186. Attachments.update({ _id: this.fileObj._id }, { $set: { [gridFsFileIdName]: finishedData._id.toHexString(), } });
  187. }
  188. /** remove the file */
  189. unlink() {
  190. const gfsId = this.getGridFsObjectId();
  191. if (gfsId) {
  192. this.gridFsBucket.delete(gfsId, err => {
  193. if (err) {
  194. console.error("error on gfs bucket.delete: ", err);
  195. }
  196. });
  197. }
  198. const gridFsFileIdName = this.getGridFsFileIdName();
  199. Attachments.update({ _id: this.fileObj._id }, { $unset: { [gridFsFileIdName]: 1 } });
  200. }
  201. /** return the storage name
  202. * @return the storage name
  203. */
  204. getStorageName() {
  205. return STORAGE_NAME_GRIDFS;
  206. }
  207. /** returns the GridFS Object-Id
  208. * @return the GridFS Object-Id
  209. */
  210. getGridFsObjectId() {
  211. let ret;
  212. const gridFsFileId = this.getGridFsFileId();
  213. if (gridFsFileId) {
  214. ret = createObjectId({ gridFsFileId });
  215. }
  216. return ret;
  217. }
  218. /** returns the GridFS Object-Id
  219. * @return the GridFS Object-Id
  220. */
  221. getGridFsFileId() {
  222. const ret = (this.fileObj.versions[this.versionName].meta || {})
  223. .gridFsFileId;
  224. return ret;
  225. }
  226. /** returns the property name of gridFsFileId
  227. * @return the property name of gridFsFileId
  228. */
  229. getGridFsFileIdName() {
  230. const ret = `versions.${this.versionName}.meta.gridFsFileId`;
  231. return ret;
  232. }
  233. }
  234. /** Strategy to store attachments at filesystem */
  235. export class FileStoreStrategyFilesystem extends FileStoreStrategy {
  236. /** constructor
  237. * @param fileObj the current file object
  238. * @param versionName the current version
  239. */
  240. constructor(fileObj, versionName) {
  241. super(fileObj, versionName);
  242. }
  243. /** returns a read stream
  244. * @return the read stream
  245. */
  246. getReadStream() {
  247. const ret = fs.createReadStream(this.fileObj.versions[this.versionName].path)
  248. return ret;
  249. }
  250. /** returns a write stream
  251. * @param filePath if set, use this path
  252. * @return the write stream
  253. */
  254. getWriteStream(filePath) {
  255. if (!_.isString(filePath)) {
  256. filePath = this.fileObj.versions[this.versionName].path;
  257. }
  258. const ret = fs.createWriteStream(filePath);
  259. return ret;
  260. }
  261. /** writing finished
  262. * @param finishedData the data of the write stream finish event
  263. */
  264. writeStreamFinished(finishedData) {
  265. }
  266. /** remove the file */
  267. unlink() {
  268. const filePath = this.fileObj.versions[this.versionName].path;
  269. fs.unlink(filePath, () => {});
  270. }
  271. /** rename the file (physical)
  272. * @li at database the filename is updated after this method
  273. * @param newFilePath the new file path
  274. */
  275. rename(newFilePath) {
  276. fs.renameSync(this.fileObj.versions[this.versionName].path, newFilePath);
  277. }
  278. /** return the storage name
  279. * @return the storage name
  280. */
  281. getStorageName() {
  282. return STORAGE_NAME_FILESYSTEM;
  283. }
  284. }
  285. /** Strategy to store attachments at S3 */
  286. export class FileStoreStrategyS3 extends FileStoreStrategy {
  287. /** constructor
  288. * @param s3Bucket use this S3 Bucket
  289. * @param fileObj the current file object
  290. * @param versionName the current version
  291. */
  292. constructor(s3Bucket, fileObj, versionName) {
  293. super(fileObj, versionName);
  294. this.s3Bucket = s3Bucket;
  295. }
  296. /** after successfull upload */
  297. onAfterUpload() {
  298. if (process.env.S3) {
  299. Meteor.settings.s3 = JSON.parse(process.env.S3).s3;
  300. }
  301. const s3Conf = Meteor.settings.s3 || {};
  302. const bound = Meteor.bindEnvironment((callback) => {
  303. return callback();
  304. });
  305. /* https://github.com/veliovgroup/Meteor-Files/blob/master/docs/aws-s3-integration.md */
  306. /* Check settings existence in `Meteor.settings` */
  307. /* This is the best practice for app security */
  308. /*
  309. if (s3Conf && s3Conf.key && s3Conf.secret && s3Conf.bucket && s3Conf.region && s3Conf.sslEnabled) {
  310. // Create a new S3 object
  311. const s3 = new S3({
  312. secretAccessKey: s3Conf.secret,
  313. accessKeyId: s3Conf.key,
  314. region: s3Conf.region,
  315. sslEnabled: s3Conf.sslEnabled, // optional
  316. httpOptions: {
  317. timeout: 6000,
  318. agent: false
  319. }
  320. });
  321. }
  322. */
  323. if (s3Conf && s3Conf.key && s3Conf.secret && s3Conf.bucket && s3Conf.endPoint && s3Conf.port && s3Conf.sslEnabled) {
  324. // Create a new S3 object
  325. var s3Client = new Minio.Client({
  326. endPoint: s3Conf.endPoint,
  327. port: s3Conf.port,
  328. useSSL: s3Conf.sslEnabled,
  329. accessKey: s3Conf.key,
  330. secretKey: s3Conf.secret
  331. //region: s3Conf.region,
  332. // sslEnabled: true, // optional
  333. //httpOptions: {
  334. // timeout: 6000,
  335. // agent: false
  336. //
  337. });
  338. // Declare the Meteor file collection on the Server
  339. const UserFiles = new FilesCollection({
  340. debug: false, // Change to `true` for debugging
  341. storagePath: storagePath,
  342. collectionName: 'userFiles',
  343. // Disallow Client to execute remove, use the Meteor.method
  344. allowClientCode: false,
  345. // Start moving files to AWS:S3
  346. // after fully received by the Meteor server
  347. onAfterUpload(fileRef) {
  348. // Run through each of the uploaded file
  349. _.each(fileRef.versions, (vRef, version) => {
  350. // We use Random.id() instead of real file's _id
  351. // to secure files from reverse engineering on the AWS client
  352. const filePath = 'files/' + (Random.id()) + '-' + version + '.' + fileRef.extension;
  353. // Create the AWS:S3 object.
  354. // Feel free to change the storage class from, see the documentation,
  355. // `STANDARD_IA` is the best deal for low access files.
  356. // Key is the file name we are creating on AWS:S3, so it will be like files/XXXXXXXXXXXXXXXXX-original.XXXX
  357. // Body is the file stream we are sending to AWS
  358. const fileObj = this.fileObj;
  359. const versionName = this.versionName;
  360. const metadata = { ...fileObj.meta, versionName, fileId: fileObj._id };
  361. s3Client.putObject({
  362. // ServerSideEncryption: 'AES256', // Optional
  363. //StorageClass: 'STANDARD',
  364. Bucket: s3Conf.bucket,
  365. Key: filePath,
  366. Body: fs.createReadStream(vRef.path),
  367. metadata,
  368. ContentType: vRef.type,
  369. }, (error) => {
  370. bound(() => {
  371. if (error) {
  372. console.error(error);
  373. } else {
  374. // Update FilesCollection with link to the file at AWS
  375. const upd = { $set: {} };
  376. upd['$set']['versions.' + version + '.meta.pipePath'] = filePath;
  377. this.collection.update({
  378. _id: fileRef._id
  379. }, upd, (updError) => {
  380. if (updError) {
  381. console.error(updError);
  382. } else {
  383. // Unlink original files from FS after successful upload to AWS:S3
  384. this.unlink(this.collection.findOne(fileRef._id), version);
  385. }
  386. });
  387. }
  388. });
  389. });
  390. });
  391. },
  392. });
  393. }
  394. }
  395. // Intercept access to the file
  396. // And redirect request to AWS:S3
  397. interceptDownload(http, fileRef, version) {
  398. let path;
  399. if (fileRef && fileRef.versions && fileRef.versions[version] && fileRef.versions[version].meta && fileRef.versions[version].meta.pipePath) {
  400. path = fileRef.versions[version].meta.pipePath;
  401. }
  402. if (path) {
  403. // If file is successfully moved to AWS:S3
  404. // We will pipe request to AWS:S3
  405. // So, original link will stay always secure
  406. // To force ?play and ?download parameters
  407. // and to keep original file name, content-type,
  408. // content-disposition, chunked "streaming" and cache-control
  409. // we're using low-level .serve() method
  410. const opts = {
  411. Bucket: s3Conf.bucket,
  412. Key: path
  413. };
  414. if (http.request.headers.range) {
  415. const vRef = fileRef.versions[version];
  416. let range = _.clone(http.request.headers.range);
  417. const array = range.split(/bytes=([0-9]*)-([0-9]*)/);
  418. const start = parseInt(array[1]);
  419. let end = parseInt(array[2]);
  420. if (isNaN(end)) {
  421. // Request data from AWS:S3 by small chunks
  422. end = (start + this.chunkSize) - 1;
  423. if (end >= vRef.size) {
  424. end = vRef.size - 1;
  425. }
  426. }
  427. opts.Range = `bytes=${start}-${end}`;
  428. http.request.headers.range = `bytes=${start}-${end}`;
  429. }
  430. const fileColl = this;
  431. s3Client.getObject(opts, function (error) {
  432. if (error) {
  433. console.error(error);
  434. if (!http.response.finished) {
  435. http.response.end();
  436. }
  437. } else {
  438. if (http.request.headers.range && this.httpResponse.headers['content-range']) {
  439. // Set proper range header in according to what is returned from AWS:S3
  440. http.request.headers.range = this.httpResponse.headers['content-range'].split('/')[0].replace('bytes ', 'bytes=');
  441. }
  442. const dataStream = new stream.PassThrough();
  443. fileColl.serve(http, fileRef, fileRef.versions[version], version, dataStream);
  444. dataStream.end(this.data.Body);
  445. }
  446. });
  447. return true;
  448. }
  449. // While file is not yet uploaded to AWS:S3
  450. // It will be served file from FS
  451. return false;
  452. }
  453. /** after file remove */
  454. onAfterRemove() {
  455. if (process.env.S3) {
  456. Meteor.settings.s3 = JSON.parse(process.env.S3).s3;
  457. }
  458. const s3Conf = Meteor.settings.s3 || {};
  459. const bound = Meteor.bindEnvironment((callback) => {
  460. return callback();
  461. });
  462. if (s3Conf && s3Conf.key && s3Conf.secret && s3Conf.bucket && s3Conf.endPoint && s3Conf.port && s3Conf.sslEnabled) {
  463. // Create a new S3 object
  464. var s3Client = new Minio.Client({
  465. endPoint: s3Conf.endPoint,
  466. port: s3Conf.port,
  467. useSSL: s3Conf.sslEnabled,
  468. accessKey: s3Conf.key,
  469. secretKey: s3Conf.secret
  470. });
  471. }
  472. this.unlink();
  473. super.onAfterRemove();
  474. // Intercept FilesCollection's remove method to remove file from AWS:S3
  475. const _origRemove = UserFiles.remove;
  476. UserFiles.remove = function (selector, callback) {
  477. const cursor = this.collection.find(selector);
  478. cursor.forEach((fileRef) => {
  479. _.each(fileRef.versions, (vRef) => {
  480. if (vRef && vRef.meta && vRef.meta.pipePath) {
  481. // Remove the object from AWS:S3 first, then we will call the original FilesCollection remove
  482. s3Client.deleteObject({
  483. Bucket: s3Conf.bucket,
  484. Key: vRef.meta.pipePath,
  485. }, (error) => {
  486. bound(() => {
  487. if (error) {
  488. console.error(error);
  489. }
  490. });
  491. });
  492. }
  493. });
  494. });
  495. // Remove original file from database
  496. _origRemove.call(this, selector, callback);
  497. };
  498. }
  499. /** returns a read stream
  500. * @return the read stream
  501. */
  502. getReadStream() {
  503. const s3Id = this.getS3ObjectId();
  504. let ret;
  505. if (s3Id) {
  506. ret = this.s3Bucket.openDownloadStream(s3Id);
  507. }
  508. return ret;
  509. }
  510. /** returns a write stream
  511. * @param filePath if set, use this path
  512. * @return the write stream
  513. */
  514. getWriteStream(filePath) {
  515. const fileObj = this.fileObj;
  516. const versionName = this.versionName;
  517. const metadata = { ...fileObj.meta, versionName, fileId: fileObj._id };
  518. const ret = this.s3Bucket.openUploadStream(this.fileObj.name, {
  519. contentType: fileObj.type || 'binary/octet-stream',
  520. metadata,
  521. });
  522. return ret;
  523. }
  524. /** writing finished
  525. * @param finishedData the data of the write stream finish event
  526. */
  527. writeStreamFinished(finishedData) {
  528. const s3FileIdName = this.getS3FileIdName();
  529. Attachments.update({ _id: this.fileObj._id }, { $set: { [s3FileIdName]: finishedData._id.toHexString(), } });
  530. }
  531. /** remove the file */
  532. unlink() {
  533. const s3Id = this.gets3ObjectId();
  534. if (s3Id) {
  535. this.s3Bucket.delete(s3Id, err => {
  536. if (err) {
  537. console.error("error on S3 bucket.delete: ", err);
  538. }
  539. });
  540. }
  541. const s3FileIdName = this.getS3FileIdName();
  542. Attachments.update({ _id: this.fileObj._id }, { $unset: { [s3FileIdName]: 1 } });
  543. }
  544. /** return the storage name
  545. * @return the storage name
  546. */
  547. getStorageName() {
  548. return STORAGE_NAME_S3;
  549. }
  550. /** returns the GridFS Object-Id
  551. * @return the GridFS Object-Id
  552. */
  553. getS3ObjectId() {
  554. let ret;
  555. const s3FileId = this.s3FileId();
  556. if (s3FileId) {
  557. ret = createObjectId({ s3FileId });
  558. }
  559. return ret;
  560. }
  561. /** returns the S3 Object-Id
  562. * @return the S3 Object-Id
  563. */
  564. getS3FileId() {
  565. const ret = (this.fileObj.versions[this.versionName].meta || {})
  566. .s3FileId;
  567. return ret;
  568. }
  569. /** returns the property name of s3FileId
  570. * @return the property name of s3FileId
  571. */
  572. getS3FileIdName() {
  573. const ret = `versions.${this.versionName}.meta.s3FileId`;
  574. return ret;
  575. }
  576. };
  577. /** move the fileObj to another storage
  578. * @param fileObj move this fileObj to another storage
  579. * @param storageDestination the storage destination (fs or gridfs)
  580. * @param fileStoreStrategyFactory get FileStoreStrategy from this factory
  581. */
  582. export const moveToStorage = function(fileObj, storageDestination, fileStoreStrategyFactory) {
  583. Object.keys(fileObj.versions).forEach(versionName => {
  584. const strategyRead = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  585. const strategyWrite = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName, storageDestination);
  586. if (strategyRead.constructor.name != strategyWrite.constructor.name) {
  587. const readStream = strategyRead.getReadStream();
  588. const filePath = strategyWrite.getNewPath(fileStoreStrategyFactory.storagePath);
  589. const writeStream = strategyWrite.getWriteStream(filePath);
  590. writeStream.on('error', error => {
  591. console.error('[writeStream error]: ', error, fileObj._id);
  592. });
  593. readStream.on('error', error => {
  594. console.error('[readStream error]: ', error, fileObj._id);
  595. });
  596. writeStream.on('finish', Meteor.bindEnvironment((finishedData) => {
  597. strategyWrite.writeStreamFinished(finishedData);
  598. }));
  599. // https://forums.meteor.com/t/meteor-code-must-always-run-within-a-fiber-try-wrapping-callbacks-that-you-pass-to-non-meteor-libraries-with-meteor-bindenvironmen/40099/8
  600. readStream.on('end', Meteor.bindEnvironment(() => {
  601. Attachments.update({ _id: fileObj._id }, { $set: {
  602. [`versions.${versionName}.storage`]: strategyWrite.getStorageName(),
  603. [`versions.${versionName}.path`]: filePath,
  604. } });
  605. strategyRead.unlink();
  606. }));
  607. readStream.pipe(writeStream);
  608. }
  609. });
  610. };
  611. export const copyFile = function(fileObj, newCardId, fileStoreStrategyFactory) {
  612. const newCard = ReactiveCache.getCard(newCardId);
  613. Object.keys(fileObj.versions).forEach(versionName => {
  614. const strategyRead = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  615. const readStream = strategyRead.getReadStream();
  616. const strategyWrite = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName, STORAGE_NAME_FILESYSTEM);
  617. const tempPath = path.join(fileStoreStrategyFactory.storagePath, Random.id() + "-" + versionName + "-" + fileObj.name);
  618. const writeStream = strategyWrite.getWriteStream(tempPath);
  619. writeStream.on('error', error => {
  620. console.error('[writeStream error]: ', error, fileObj._id);
  621. });
  622. readStream.on('error', error => {
  623. console.error('[readStream error]: ', error, fileObj._id);
  624. });
  625. // https://forums.meteor.com/t/meteor-code-must-always-run-within-a-fiber-try-wrapping-callbacks-that-you-pass-to-non-meteor-libraries-with-meteor-bindenvironmen/40099/8
  626. readStream.on('end', Meteor.bindEnvironment(() => {
  627. const fileId = new ObjectID().toString();
  628. Attachments.addFile(
  629. tempPath,
  630. {
  631. fileName: fileObj.name,
  632. type: fileObj.type,
  633. meta: {
  634. boardId: newCard.boardId,
  635. cardId: newCardId,
  636. listId: newCard.listId,
  637. swimlaneId: newCard.swimlaneId,
  638. source: 'copy',
  639. copyFrom: fileObj._id,
  640. copyStorage: strategyRead.getStorageName(),
  641. },
  642. userId: fileObj.userId,
  643. size: fileObj.fileSize,
  644. fileId,
  645. },
  646. (err, fileRef) => {
  647. if (err) {
  648. console.log(err);
  649. } else {
  650. // Set the userId again
  651. Attachments.update({ _id: fileRef._id }, { $set: { userId: fileObj.userId } });
  652. }
  653. },
  654. true,
  655. );
  656. }));
  657. readStream.pipe(writeStream);
  658. });
  659. };
  660. export const rename = function(fileObj, newName, fileStoreStrategyFactory) {
  661. Object.keys(fileObj.versions).forEach(versionName => {
  662. const strategy = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  663. const newFilePath = strategy.getNewPath(fileStoreStrategyFactory.storagePath, newName);
  664. strategy.rename(newFilePath);
  665. Attachments.update({ _id: fileObj._id }, { $set: {
  666. "name": newName,
  667. [`versions.${versionName}.path`]: newFilePath,
  668. } });
  669. });
  670. };