attachments.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import { Meteor } from 'meteor/meteor';
  2. import { FilesCollection } from 'meteor/ostrio:files';
  3. import { isFileValid } from './fileValidation';
  4. import { createBucket } from './lib/grid/createBucket';
  5. import fs from 'fs';
  6. import path from 'path';
  7. import { AttachmentStoreStrategyFilesystem, AttachmentStoreStrategyGridFs} from '/models/lib/attachmentStoreStrategy';
  8. import FileStoreStrategyFactory, {moveToStorage, rename, STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS} from '/models/lib/fileStoreStrategy';
  9. let attachmentUploadExternalProgram;
  10. let attachmentUploadMimeTypes = [];
  11. let attachmentUploadSize = 0;
  12. let attachmentBucket;
  13. let storagePath;
  14. if (Meteor.isServer) {
  15. attachmentBucket = createBucket('attachments');
  16. if (process.env.ATTACHMENTS_UPLOAD_MIME_TYPES) {
  17. attachmentUploadMimeTypes = process.env.ATTACHMENTS_UPLOAD_MIME_TYPES.split(',');
  18. attachmentUploadMimeTypes = attachmentUploadMimeTypes.map(value => value.trim());
  19. }
  20. if (process.env.ATTACHMENTS_UPLOAD_MAX_SIZE) {
  21. attachmentUploadSize = parseInt(process.env.ATTACHMENTS_UPLOAD_MAX_SIZE);
  22. if (isNaN(attachmentUploadSize)) {
  23. attachmentUploadSize = 0
  24. }
  25. }
  26. if (process.env.ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM) {
  27. attachmentUploadExternalProgram = process.env.ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM;
  28. if (!attachmentUploadExternalProgram.includes("{file}")) {
  29. attachmentUploadExternalProgram = undefined;
  30. }
  31. }
  32. storagePath = path.join(process.env.WRITABLE_PATH, 'attachments');
  33. }
  34. export const fileStoreStrategyFactory = new FileStoreStrategyFactory(AttachmentStoreStrategyFilesystem, storagePath, AttachmentStoreStrategyGridFs, attachmentBucket);
  35. // XXX Enforce a schema for the Attachments FilesCollection
  36. // see: https://github.com/VeliovGroup/Meteor-Files/wiki/Schema
  37. Attachments = new FilesCollection({
  38. debug: false, // Change to `true` for debugging
  39. collectionName: 'attachments',
  40. allowClientCode: true,
  41. namingFunction(opts) {
  42. let filenameWithoutExtension = ""
  43. let fileId = "";
  44. if (opts?.name) {
  45. // Client
  46. filenameWithoutExtension = opts.name.replace(/(.+)\..+/, "$1");
  47. fileId = opts.meta.fileId;
  48. delete opts.meta.fileId;
  49. } else if (opts?.file?.name) {
  50. // Server
  51. filenameWithoutExtension = opts.file.name.replace(new RegExp(opts.file.extensionWithDot + "$"), "")
  52. fileId = opts.fileId;
  53. }
  54. else {
  55. // should never reach here
  56. filenameWithoutExtension = Math.random().toString(36).slice(2);
  57. fileId = Math.random().toString(36).slice(2);
  58. }
  59. const ret = fileId + "-original-" + filenameWithoutExtension;
  60. // remove fileId from meta, it was only stored there to have this information here in the namingFunction function
  61. return ret;
  62. },
  63. storagePath() {
  64. const ret = fileStoreStrategyFactory.storagePath;
  65. return ret;
  66. },
  67. onAfterUpload(fileObj) {
  68. // current storage is the filesystem, update object and database
  69. Object.keys(fileObj.versions).forEach(versionName => {
  70. fileObj.versions[versionName].storage = STORAGE_NAME_FILESYSTEM;
  71. });
  72. Attachments.update({ _id: fileObj._id }, { $set: { "versions" : fileObj.versions } });
  73. let storageDestination = fileObj.meta.copyStorage || STORAGE_NAME_GRIDFS;
  74. Meteor.defer(() => Meteor.call('validateAttachmentAndMoveToStorage', fileObj._id, storageDestination));
  75. },
  76. interceptDownload(http, fileObj, versionName) {
  77. const ret = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).interceptDownload(http, this.cacheControl);
  78. return ret;
  79. },
  80. onAfterRemove(files) {
  81. files.forEach(fileObj => {
  82. Object.keys(fileObj.versions).forEach(versionName => {
  83. fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).onAfterRemove();
  84. });
  85. });
  86. },
  87. // We authorize the attachment download either:
  88. // - if the board is public, everyone (even unconnected) can download it
  89. // - if the board is private, only board members can download it
  90. protected(fileObj) {
  91. // file may have been deleted already again after upload validation failed
  92. if (!fileObj) {
  93. return false;
  94. }
  95. const board = Boards.findOne(fileObj.meta.boardId);
  96. if (board.isPublic()) {
  97. return true;
  98. }
  99. return board.hasMember(this.userId);
  100. },
  101. });
  102. if (Meteor.isServer) {
  103. Attachments.allow({
  104. insert(userId, fileObj) {
  105. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  106. },
  107. update(userId, fileObj) {
  108. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  109. },
  110. remove(userId, fileObj) {
  111. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  112. },
  113. fetch: ['meta'],
  114. });
  115. Meteor.methods({
  116. moveAttachmentToStorage(fileObjId, storageDestination) {
  117. check(fileObjId, String);
  118. check(storageDestination, String);
  119. const fileObj = Attachments.findOne({_id: fileObjId});
  120. moveToStorage(fileObj, storageDestination, fileStoreStrategyFactory);
  121. // since Meteor-Files 2.1.0 the filename is truncated to 28 characters, so rename the file after upload to the right filename back
  122. rename(fileObj, fileObj.name, fileStoreStrategyFactory);
  123. },
  124. renameAttachment(fileObjId, newName) {
  125. check(fileObjId, String);
  126. check(newName, String);
  127. const fileObj = Attachments.findOne({_id: fileObjId});
  128. rename(fileObj, newName, fileStoreStrategyFactory);
  129. },
  130. validateAttachment(fileObjId) {
  131. check(fileObjId, String);
  132. const fileObj = Attachments.findOne({_id: fileObjId});
  133. const isValid = Promise.await(isFileValid(fileObj, attachmentUploadMimeTypes, attachmentUploadSize, attachmentUploadExternalProgram));
  134. if (!isValid) {
  135. Attachments.remove(fileObjId);
  136. }
  137. },
  138. validateAttachmentAndMoveToStorage(fileObjId, storageDestination) {
  139. check(fileObjId, String);
  140. check(storageDestination, String);
  141. Meteor.call('validateAttachment', fileObjId);
  142. const fileObj = Attachments.findOne({_id: fileObjId});
  143. if (fileObj) {
  144. Meteor.defer(() => Meteor.call('moveAttachmentToStorage', fileObjId, storageDestination));
  145. }
  146. },
  147. });
  148. Meteor.startup(() => {
  149. Attachments.collection.createIndex({ 'meta.cardId': 1 });
  150. const storagePath = fileStoreStrategyFactory.storagePath;
  151. if (!fs.existsSync(storagePath)) {
  152. console.log("create storagePath because it doesn't exist: " + storagePath);
  153. fs.mkdirSync(storagePath, { recursive: true });
  154. }
  155. });
  156. }
  157. export default Attachments;