attachments.js 7.6 KB

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