gridfs.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import { Readable } from 'stream';
  2. import util from 'util';
  3. import mongoose from 'mongoose';
  4. import { createModel } from 'mongoose-gridfs';
  5. import type { RespondOptions } from '~/server/interfaces/attachment';
  6. import type { IAttachmentDocument } from '~/server/models';
  7. import loggerFactory from '~/utils/logger';
  8. import { configManager } from '../config-manager';
  9. import { AbstractFileUploader, type TemporaryUrl, type SaveFileParam } from './file-uploader';
  10. import { ContentHeaders } from './utils';
  11. const logger = loggerFactory('growi:service:fileUploaderGridfs');
  12. // TODO: rewrite this module to be a type-safe implementation
  13. class GridfsFileUploader extends AbstractFileUploader {
  14. /**
  15. * @inheritdoc
  16. */
  17. override isValidUploadSettings(): boolean {
  18. throw new Error('Method not implemented.');
  19. }
  20. /**
  21. * @inheritdoc
  22. */
  23. override listFiles() {
  24. throw new Error('Method not implemented.');
  25. }
  26. /**
  27. * @inheritdoc
  28. */
  29. override saveFile(param: SaveFileParam) {
  30. throw new Error('Method not implemented.');
  31. }
  32. /**
  33. * @inheritdoc
  34. */
  35. override deleteFiles() {
  36. throw new Error('Method not implemented.');
  37. }
  38. /**
  39. * @inheritdoc
  40. */
  41. override respond(): void {
  42. throw new Error('GridfsFileUploader does not support ResponseMode.DELEGATE.');
  43. }
  44. /**
  45. * @inheritdoc
  46. */
  47. override findDeliveryFile(attachment: IAttachmentDocument): Promise<NodeJS.ReadableStream> {
  48. throw new Error('Method not implemented.');
  49. }
  50. /**
  51. * @inheritDoc
  52. */
  53. override async generateTemporaryUrl(attachment: IAttachmentDocument, opts?: RespondOptions): Promise<TemporaryUrl> {
  54. throw new Error('GridfsFileUploader does not support ResponseMode.REDIRECT.');
  55. }
  56. }
  57. module.exports = function(crowi) {
  58. const lib = new GridfsFileUploader(crowi);
  59. const COLLECTION_NAME = 'attachmentFiles';
  60. const CHUNK_COLLECTION_NAME = `${COLLECTION_NAME}.chunks`;
  61. // instantiate mongoose-gridfs
  62. const AttachmentFile = createModel({
  63. modelName: COLLECTION_NAME,
  64. bucketName: COLLECTION_NAME,
  65. connection: mongoose.connection,
  66. });
  67. // get Collection instance of chunk
  68. const chunkCollection = mongoose.connection.collection(CHUNK_COLLECTION_NAME);
  69. // create promisified method
  70. AttachmentFile.promisifiedWrite = util.promisify(AttachmentFile.write).bind(AttachmentFile);
  71. AttachmentFile.promisifiedUnlink = util.promisify(AttachmentFile.unlink).bind(AttachmentFile);
  72. lib.isValidUploadSettings = function() {
  73. return true;
  74. };
  75. (lib as any).deleteFile = async function(attachment) {
  76. const filenameValue = attachment.fileName;
  77. const attachmentFile = await AttachmentFile.findOne({ filename: filenameValue });
  78. if (attachmentFile == null) {
  79. logger.warn(`Any AttachmentFile that relate to the Attachment (${attachment._id.toString()}) does not exist in GridFS`);
  80. return;
  81. }
  82. return AttachmentFile.promisifiedUnlink({ _id: attachmentFile._id });
  83. };
  84. (lib as any).deleteFiles = async function(attachments) {
  85. const filenameValues = attachments.map((attachment) => {
  86. return attachment.fileName;
  87. });
  88. const fileIdObjects = await AttachmentFile.find({ filename: { $in: filenameValues } }, { _id: 1 });
  89. const idsRelatedFiles = fileIdObjects.map((obj) => { return obj._id });
  90. return Promise.all([
  91. AttachmentFile.deleteMany({ filename: { $in: filenameValues } }),
  92. chunkCollection.deleteMany({ files_id: { $in: idsRelatedFiles } }),
  93. ]);
  94. };
  95. /**
  96. * get size of data uploaded files using (Promise wrapper)
  97. */
  98. // const getCollectionSize = () => {
  99. // return new Promise((resolve, reject) => {
  100. // chunkCollection.stats((err, data) => {
  101. // if (err) {
  102. // // return 0 if not exist
  103. // if (err.errmsg.includes('not found')) {
  104. // return resolve(0);
  105. // }
  106. // return reject(err);
  107. // }
  108. // return resolve(data.size);
  109. // });
  110. // });
  111. // };
  112. /**
  113. * check the file size limit
  114. *
  115. * In detail, the followings are checked.
  116. * - per-file size limit (specified by MAX_FILE_SIZE)
  117. * - mongodb(gridfs) size limit (specified by MONGO_GRIDFS_TOTAL_LIMIT)
  118. */
  119. (lib as any).checkLimit = async function(uploadFileSize) {
  120. const maxFileSize = configManager.getConfig('crowi', 'app:maxFileSize');
  121. const totalLimit = lib.getFileUploadTotalLimit();
  122. return lib.doCheckLimit(uploadFileSize, maxFileSize, totalLimit);
  123. };
  124. (lib as any).uploadAttachment = async function(fileStream, attachment) {
  125. logger.debug(`File uploading: fileName=${attachment.fileName}`);
  126. const contentHeaders = new ContentHeaders(attachment);
  127. return AttachmentFile.promisifiedWrite(
  128. {
  129. // put type and the file name for reference information when uploading
  130. filename: attachment.fileName,
  131. contentType: contentHeaders.contentType?.value.toString(),
  132. },
  133. fileStream,
  134. );
  135. };
  136. lib.saveFile = async function({ filePath, contentType, data }) {
  137. const readable = new Readable();
  138. readable.push(data);
  139. readable.push(null); // EOF
  140. return AttachmentFile.promisifiedWrite(
  141. {
  142. filename: filePath,
  143. contentType,
  144. },
  145. readable,
  146. );
  147. };
  148. /**
  149. * Find data substance
  150. *
  151. * @param {Attachment} attachment
  152. * @return {stream.Readable} readable stream
  153. */
  154. lib.findDeliveryFile = async function(attachment) {
  155. const filenameValue = attachment.fileName;
  156. const attachmentFile = await AttachmentFile.findOne({ filename: filenameValue });
  157. if (attachmentFile == null) {
  158. throw new Error(`Any AttachmentFile that relate to the Attachment (${attachment._id.toString()}) does not exist in GridFS`);
  159. }
  160. // return stream.Readable
  161. return AttachmentFile.read({ _id: attachmentFile._id });
  162. };
  163. /**
  164. * List files in storage
  165. */
  166. (lib as any).listFiles = async function() {
  167. const attachmentFiles = await AttachmentFile.find();
  168. return attachmentFiles.map(({ filename: name, length: size }) => ({
  169. name, size,
  170. }));
  171. };
  172. return lib;
  173. };