gridfs.ts 6.0 KB

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