attachments.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. this._now = new Date();
  86. Attachments.update({ _id: fileObj._id }, { $set: { "versions" : fileObj.versions } });
  87. Attachments.update({ _id: fileObj.uploadedAtOstrio }, { $set: { "uploadedAtOstrio" : this._now } });
  88. let storageDestination = fileObj.meta.copyStorage || STORAGE_NAME_GRIDFS;
  89. Meteor.defer(() => Meteor.call('validateAttachmentAndMoveToStorage', fileObj._id, storageDestination));
  90. },
  91. interceptDownload(http, fileObj, versionName) {
  92. const ret = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).interceptDownload(http, this.cacheControl);
  93. return ret;
  94. },
  95. onAfterRemove(files) {
  96. files.forEach(fileObj => {
  97. Object.keys(fileObj.versions).forEach(versionName => {
  98. fileStoreStrategyFactory.getFileStrategy(fileObj, versionName).onAfterRemove();
  99. });
  100. });
  101. },
  102. // We authorize the attachment download either:
  103. // - if the board is public, everyone (even unconnected) can download it
  104. // - if the board is private, only board members can download it
  105. protected(fileObj) {
  106. // file may have been deleted already again after upload validation failed
  107. if (!fileObj) {
  108. return false;
  109. }
  110. const board = Boards.findOne(fileObj.meta.boardId);
  111. if (board.isPublic()) {
  112. return true;
  113. }
  114. return board.hasMember(this.userId);
  115. },
  116. });
  117. if (Meteor.isServer) {
  118. Attachments.allow({
  119. insert(userId, fileObj) {
  120. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  121. },
  122. update(userId, fileObj) {
  123. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  124. },
  125. remove(userId, fileObj) {
  126. return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
  127. },
  128. fetch: ['meta'],
  129. });
  130. Meteor.methods({
  131. moveAttachmentToStorage(fileObjId, storageDestination) {
  132. check(fileObjId, String);
  133. check(storageDestination, String);
  134. const fileObj = Attachments.findOne({_id: fileObjId});
  135. moveToStorage(fileObj, storageDestination, fileStoreStrategyFactory);
  136. },
  137. renameAttachment(fileObjId, newName) {
  138. check(fileObjId, String);
  139. check(newName, String);
  140. const fileObj = Attachments.findOne({_id: fileObjId});
  141. rename(fileObj, newName, fileStoreStrategyFactory);
  142. },
  143. validateAttachment(fileObjId) {
  144. check(fileObjId, String);
  145. const fileObj = Attachments.findOne({_id: fileObjId});
  146. const isValid = Promise.await(isFileValid(fileObj, attachmentUploadMimeTypes, attachmentUploadSize, attachmentUploadExternalProgram));
  147. if (!isValid) {
  148. Attachments.remove(fileObjId);
  149. }
  150. },
  151. validateAttachmentAndMoveToStorage(fileObjId, storageDestination) {
  152. check(fileObjId, String);
  153. check(storageDestination, String);
  154. Meteor.call('validateAttachment', fileObjId);
  155. const fileObj = Attachments.findOne({_id: fileObjId});
  156. if (fileObj) {
  157. Meteor.defer(() => Meteor.call('moveAttachmentToStorage', fileObjId, storageDestination));
  158. }
  159. },
  160. });
  161. Meteor.startup(() => {
  162. Attachments.collection.createIndex({ 'meta.cardId': 1 });
  163. const storagePath = fileStoreStrategyFactory.storagePath;
  164. if (!fs.existsSync(storagePath)) {
  165. console.log("create storagePath because it doesn't exist: " + storagePath);
  166. fs.mkdirSync(storagePath, { recursive: true });
  167. }
  168. });
  169. }
  170. export default Attachments;