2
0

attachments.js 6.8 KB

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