attachments.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. 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. // OLD:
  65. //const ret = fileId + "-original-" + filenameWithoutExtension;
  66. // NEW: Save file only with filename of ObjectID, not including filename.
  67. // Fixes https://github.com/wekan/wekan/issues/4416#issuecomment-1510517168
  68. const ret = fileId;
  69. // remove fileId from meta, it was only stored there to have this information here in the namingFunction function
  70. return ret;
  71. },
  72. sanitize(str, max, replacement) {
  73. // keep the original filename
  74. return str;
  75. },
  76. storagePath() {
  77. const ret = fileStoreStrategyFactory.storagePath;
  78. return ret;
  79. },
  80. onAfterUpload(fileObj) {
  81. // current storage is the filesystem, update object and database
  82. Object.keys(fileObj.versions).forEach(versionName => {
  83. fileObj.versions[versionName].storage = STORAGE_NAME_FILESYSTEM;
  84. });
  85. Attachments.update({ _id: fileObj._id }, { $set: { "versions" : fileObj.versions } });
  86. Attachments.update({ _id: fileObj.uploadedAtOstrio }, { $set: { "uploadedAtOstrio" : this._now() } });
  87. let storageDestination = fileObj.meta.copyStorage || STORAGE_NAME_GRIDFS;
  88. Meteor.defer(() => Meteor.call('validateAttachmentAndMoveToStorage', fileObj._id, storageDestination));
  89. },
  90. interceptDownload(http, fileObj, versionName) {
  91. const ret = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).interceptDownload(http, this.cacheControl);
  92. return ret;
  93. },
  94. onAfterRemove(files) {
  95. files.forEach(fileObj => {
  96. Object.keys(fileObj.versions).forEach(versionName => {
  97. fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).onAfterRemove();
  98. });
  99. });
  100. },
  101. // We authorize the attachment download either:
  102. // - if the board is public, everyone (even unconnected) can download it
  103. // - if the board is private, only board members can download it
  104. protected(fileObj) {
  105. // file may have been deleted already again after upload validation failed
  106. if (!fileObj) {
  107. return false;
  108. }
  109. const board = Boards.findOne(fileObj.meta.boardId);
  110. if (board.isPublic()) {
  111. return true;
  112. }
  113. return board.hasMember(this.userId);
  114. },
  115. });
  116. if (Meteor.isServer) {
  117. Attachments.allow({
  118. insert(userId, fileObj) {
  119. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  120. },
  121. update(userId, fileObj) {
  122. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  123. },
  124. remove(userId, fileObj) {
  125. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  126. },
  127. fetch: ['meta'],
  128. });
  129. Meteor.methods({
  130. moveAttachmentToStorage(fileObjId, storageDestination) {
  131. check(fileObjId, String);
  132. check(storageDestination, String);
  133. const fileObj = Attachments.findOne({_id: fileObjId});
  134. moveToStorage(fileObj, storageDestination, fileStoreStrategyFactory);
  135. },
  136. renameAttachment(fileObjId, newName) {
  137. check(fileObjId, String);
  138. check(newName, String);
  139. const fileObj = Attachments.findOne({_id: fileObjId});
  140. rename(fileObj, newName, fileStoreStrategyFactory);
  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;