attachments.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. if (opts.file.extension) {
  52. filenameWithoutExtension = opts.file.name.replace(new RegExp(opts.file.extensionWithDot + "$"), "")
  53. } else {
  54. // file has no extension, so don't replace anything, otherwise the last character is removed (because extensionWithDot = '.')
  55. filenameWithoutExtension = opts.file.name;
  56. }
  57. fileId = opts.fileId;
  58. }
  59. else {
  60. // should never reach here
  61. filenameWithoutExtension = Math.random().toString(36).slice(2);
  62. fileId = Math.random().toString(36).slice(2);
  63. }
  64. const ret = fileId + "-original-" + filenameWithoutExtension;
  65. // remove fileId from meta, it was only stored there to have this information here in the namingFunction function
  66. return ret;
  67. },
  68. sanitize(str, max, replacement) {
  69. // keep the original filename
  70. return str;
  71. },
  72. storagePath() {
  73. const ret = fileStoreStrategyFactory.storagePath;
  74. return ret;
  75. },
  76. onAfterUpload(fileObj) {
  77. // current storage is the filesystem, update object and database
  78. Object.keys(fileObj.versions).forEach(versionName => {
  79. fileObj.versions[versionName].storage = STORAGE_NAME_FILESYSTEM;
  80. });
  81. Attachments.update({ _id: fileObj._id }, { $set: { "versions" : fileObj.versions } });
  82. let storageDestination = fileObj.meta.copyStorage || STORAGE_NAME_GRIDFS;
  83. Meteor.defer(() => Meteor.call('validateAttachmentAndMoveToStorage', fileObj._id, storageDestination));
  84. },
  85. interceptDownload(http, fileObj, versionName) {
  86. const ret = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).interceptDownload(http, this.cacheControl);
  87. return ret;
  88. },
  89. onAfterRemove(files) {
  90. files.forEach(fileObj => {
  91. Object.keys(fileObj.versions).forEach(versionName => {
  92. fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).onAfterRemove();
  93. });
  94. });
  95. },
  96. // We authorize the attachment download either:
  97. // - if the board is public, everyone (even unconnected) can download it
  98. // - if the board is private, only board members can download it
  99. protected(fileObj) {
  100. // file may have been deleted already again after upload validation failed
  101. if (!fileObj) {
  102. return false;
  103. }
  104. const board = Boards.findOne(fileObj.meta.boardId);
  105. if (board.isPublic()) {
  106. return true;
  107. }
  108. return board.hasMember(this.userId);
  109. },
  110. });
  111. if (Meteor.isServer) {
  112. Attachments.allow({
  113. insert(userId, fileObj) {
  114. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  115. },
  116. update(userId, fileObj) {
  117. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  118. },
  119. remove(userId, fileObj) {
  120. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  121. },
  122. fetch: ['meta'],
  123. });
  124. Meteor.methods({
  125. moveAttachmentToStorage(fileObjId, storageDestination) {
  126. check(fileObjId, String);
  127. check(storageDestination, String);
  128. const fileObj = Attachments.findOne({_id: fileObjId});
  129. moveToStorage(fileObj, storageDestination, fileStoreStrategyFactory);
  130. },
  131. renameAttachment(fileObjId, newName) {
  132. check(fileObjId, String);
  133. check(newName, String);
  134. const fileObj = Attachments.findOne({_id: fileObjId});
  135. rename(fileObj, newName, fileStoreStrategyFactory);
  136. },
  137. validateAttachment(fileObjId) {
  138. check(fileObjId, String);
  139. const fileObj = Attachments.findOne({_id: fileObjId});
  140. const isValid = Promise.await(isFileValid(fileObj, attachmentUploadMimeTypes, attachmentUploadSize, attachmentUploadExternalProgram));
  141. if (!isValid) {
  142. Attachments.remove(fileObjId);
  143. }
  144. },
  145. validateAttachmentAndMoveToStorage(fileObjId, storageDestination) {
  146. check(fileObjId, String);
  147. check(storageDestination, String);
  148. Meteor.call('validateAttachment', fileObjId);
  149. const fileObj = Attachments.findOne({_id: fileObjId});
  150. if (fileObj) {
  151. Meteor.defer(() => Meteor.call('moveAttachmentToStorage', fileObjId, storageDestination));
  152. }
  153. },
  154. });
  155. Meteor.startup(() => {
  156. Attachments.collection.createIndex({ 'meta.cardId': 1 });
  157. const storagePath = fileStoreStrategyFactory.storagePath;
  158. if (!fs.existsSync(storagePath)) {
  159. console.log("create storagePath because it doesn't exist: " + storagePath);
  160. fs.mkdirSync(storagePath, { recursive: true });
  161. }
  162. });
  163. }
  164. export default Attachments;