local.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import type { ReadStream } from 'fs';
  2. import type { Writable } from 'stream';
  3. import { Readable } from 'stream';
  4. import { pipeline } from 'stream/promises';
  5. import type { Response } from 'express';
  6. import { ResponseMode, type RespondOptions } from '~/server/interfaces/attachment';
  7. import type { IAttachmentDocument } from '~/server/models/attachment';
  8. import loggerFactory from '~/utils/logger';
  9. import { configManager } from '../config-manager';
  10. import {
  11. AbstractFileUploader, type TemporaryUrl, type SaveFileParam,
  12. } from './file-uploader';
  13. import {
  14. ContentHeaders, applyHeaders,
  15. } from './utils';
  16. const logger = loggerFactory('growi:service:fileUploaderLocal');
  17. const fs = require('fs');
  18. const fsPromises = require('fs/promises');
  19. const path = require('path');
  20. const mkdir = require('mkdirp');
  21. const urljoin = require('url-join');
  22. // TODO: rewrite this module to be a type-safe implementation
  23. class LocalFileUploader extends AbstractFileUploader {
  24. /**
  25. * @inheritdoc
  26. */
  27. override isValidUploadSettings(): boolean {
  28. throw new Error('Method not implemented.');
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. override listFiles() {
  34. throw new Error('Method not implemented.');
  35. }
  36. /**
  37. * @inheritdoc
  38. */
  39. override saveFile(param: SaveFileParam) {
  40. throw new Error('Method not implemented.');
  41. }
  42. /**
  43. * @inheritdoc
  44. */
  45. override deleteFiles() {
  46. throw new Error('Method not implemented.');
  47. }
  48. deleteFileByFilePath(filePath: string): void {
  49. throw new Error('Method not implemented.');
  50. }
  51. /**
  52. * @inheritdoc
  53. */
  54. override determineResponseMode() {
  55. return configManager.getConfig('fileUpload:local:useInternalRedirect')
  56. ? ResponseMode.DELEGATE
  57. : ResponseMode.RELAY;
  58. }
  59. /**
  60. * @inheritdoc
  61. */
  62. override async uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void> {
  63. throw new Error('Method not implemented.');
  64. }
  65. /**
  66. * @inheritdoc
  67. */
  68. override respond(res: Response, attachment: IAttachmentDocument, opts?: RespondOptions): void {
  69. throw new Error('Method not implemented.');
  70. }
  71. /**
  72. * @inheritdoc
  73. */
  74. override findDeliveryFile(attachment: IAttachmentDocument): Promise<NodeJS.ReadableStream> {
  75. throw new Error('Method not implemented.');
  76. }
  77. /**
  78. * @inheritDoc
  79. */
  80. override async generateTemporaryUrl(attachment: IAttachmentDocument, opts?: RespondOptions): Promise<TemporaryUrl> {
  81. throw new Error('LocalFileUploader does not support ResponseMode.REDIRECT.');
  82. }
  83. }
  84. module.exports = function(crowi) {
  85. const lib = new LocalFileUploader(crowi);
  86. const basePath = path.posix.join(crowi.publicDir, 'uploads');
  87. function getFilePathOnStorage(attachment) {
  88. const dirName = (attachment.page != null)
  89. ? 'attachment'
  90. : 'user';
  91. const filePath = path.posix.join(basePath, dirName, attachment.fileName);
  92. return filePath;
  93. }
  94. async function readdirRecursively(dirPath) {
  95. const directories = await fsPromises.readdir(dirPath, { withFileTypes: true });
  96. const files = await Promise.all(directories.map((directory) => {
  97. const childDirPathOrFilePath = path.resolve(dirPath, directory.name);
  98. return directory.isDirectory() ? readdirRecursively(childDirPathOrFilePath) : childDirPathOrFilePath;
  99. }));
  100. return files.flat();
  101. }
  102. lib.isValidUploadSettings = function() {
  103. return true;
  104. };
  105. (lib as any).deleteFile = async function(attachment) {
  106. const filePath = getFilePathOnStorage(attachment);
  107. return lib.deleteFileByFilePath(filePath);
  108. };
  109. (lib as any).deleteFiles = async function(attachments) {
  110. attachments.map((attachment) => {
  111. return (lib as any).deleteFile(attachment);
  112. });
  113. };
  114. lib.deleteFileByFilePath = async function(filePath) {
  115. // check file exists
  116. try {
  117. fs.statSync(filePath);
  118. }
  119. catch (err) {
  120. logger.warn(`Any AttachmentFile which path is '${filePath}' does not exist in local fs`);
  121. return;
  122. }
  123. return fs.unlinkSync(filePath);
  124. };
  125. lib.uploadAttachment = async function(fileStream, attachment) {
  126. logger.debug(`File uploading: fileName=${attachment.fileName}`);
  127. const filePath = getFilePathOnStorage(attachment);
  128. const dirpath = path.posix.dirname(filePath);
  129. // mkdir -p
  130. mkdir.sync(dirpath);
  131. const writeStream: Writable = fs.createWriteStream(filePath);
  132. return pipeline(fileStream, writeStream);
  133. };
  134. lib.saveFile = async function({ filePath, contentType, data }) {
  135. const absFilePath = path.posix.join(basePath, filePath);
  136. const dirpath = path.posix.dirname(absFilePath);
  137. // mkdir -p
  138. mkdir.sync(dirpath);
  139. const fileStream = new Readable();
  140. fileStream.push(data);
  141. fileStream.push(null); // EOF
  142. const writeStream: Writable = fs.createWriteStream(absFilePath);
  143. return pipeline(fileStream, writeStream);
  144. };
  145. /**
  146. * Find data substance
  147. *
  148. * @param {Attachment} attachment
  149. * @return {stream.Readable} readable stream
  150. */
  151. lib.findDeliveryFile = async function(attachment) {
  152. const filePath = getFilePathOnStorage(attachment);
  153. // check file exists
  154. try {
  155. fs.statSync(filePath);
  156. }
  157. catch (err) {
  158. throw new Error(`Any AttachmentFile that relate to the Attachment (${attachment._id.toString()}) does not exist in local fs`);
  159. }
  160. // return stream.Readable
  161. return fs.createReadStream(filePath);
  162. };
  163. /**
  164. * check the file size limit
  165. *
  166. * In detail, the followings are checked.
  167. * - per-file size limit (specified by MAX_FILE_SIZE)
  168. */
  169. (lib as any).checkLimit = async function(uploadFileSize) {
  170. const maxFileSize = configManager.getConfig('app:maxFileSize');
  171. const totalLimit = configManager.getConfig('app:fileUploadTotalLimit');
  172. return lib.doCheckLimit(uploadFileSize, maxFileSize, totalLimit);
  173. };
  174. /**
  175. * Respond to the HTTP request.
  176. * @param {Response} res
  177. * @param {Response} attachment
  178. */
  179. lib.respond = function(res, attachment, opts) {
  180. // Responce using internal redirect of nginx or Apache.
  181. const storagePath = getFilePathOnStorage(attachment);
  182. const relativePath = path.relative(crowi.publicDir, storagePath);
  183. const internalPathRoot = configManager.getConfig('fileUpload:local:internalRedirectPath');
  184. const internalPath = urljoin(internalPathRoot, relativePath);
  185. const isDownload = opts?.download ?? false;
  186. const contentHeaders = new ContentHeaders(attachment, { inline: !isDownload });
  187. applyHeaders(res, [
  188. ...contentHeaders.toExpressHttpHeaders(),
  189. { field: 'X-Accel-Redirect', value: internalPath },
  190. { field: 'X-Sendfile', value: storagePath },
  191. ]);
  192. return res.end();
  193. };
  194. /**
  195. * List files in storage
  196. */
  197. lib.listFiles = async function() {
  198. // `mkdir -p` to avoid ENOENT error
  199. await mkdir(basePath);
  200. const filePaths = await readdirRecursively(basePath);
  201. return Promise.all(
  202. filePaths.map(
  203. file => fsPromises.stat(file).then(({ size }) => ({
  204. name: path.relative(basePath, file),
  205. size,
  206. })),
  207. ),
  208. );
  209. };
  210. return lib;
  211. };