attachment.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import loggerFactory from '~/utils/logger';
  2. import { AttachmentType } from '../interfaces/attachment';
  3. import { Attachment } from '../models/attachment';
  4. const fs = require('fs');
  5. const mongoose = require('mongoose');
  6. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  7. const logger = loggerFactory('growi:service:AttachmentService');
  8. /**
  9. * the service class for Attachment and file-uploader
  10. */
  11. class AttachmentService {
  12. /** @type {import('~/server/crowi').default} Crowi instance */
  13. crowi;
  14. /** @param {import('~/server/crowi').default} crowi Crowi instance */
  15. constructor(crowi) {
  16. this.crowi = crowi;
  17. }
  18. async createAttachment(file, user, pageId = null, attachmentType) {
  19. const { fileUploadService } = this.crowi;
  20. // check limit
  21. const res = await fileUploadService.checkLimit(file.size);
  22. if (!res.isUploadable) {
  23. throw new Error(res.errorMessage);
  24. }
  25. const fileStream = fs.createReadStream(file.path, {
  26. flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true,
  27. });
  28. // create an Attachment document and upload file
  29. let attachment;
  30. try {
  31. attachment = Attachment.createWithoutSave(pageId, user, file.originalname, file.mimetype, file.size, attachmentType);
  32. await fileUploadService.uploadAttachment(fileStream, attachment);
  33. await attachment.save();
  34. }
  35. catch (err) {
  36. // delete temporary file
  37. fs.unlink(file.path, (err) => { if (err) { logger.error('Error while deleting tmp file.') } });
  38. throw err;
  39. }
  40. return attachment;
  41. }
  42. async removeAllAttachments(attachments) {
  43. const { fileUploadService } = this.crowi;
  44. const attachmentsCollection = mongoose.connection.collection('attachments');
  45. const unorderAttachmentsBulkOp = attachmentsCollection.initializeUnorderedBulkOp();
  46. if (attachments.length === 0) {
  47. return;
  48. }
  49. attachments.forEach((attachment) => {
  50. unorderAttachmentsBulkOp.find({ _id: attachment._id }).delete();
  51. });
  52. await unorderAttachmentsBulkOp.execute();
  53. await fileUploadService.deleteFiles(attachments);
  54. return;
  55. }
  56. async removeAttachment(attachmentId) {
  57. const { fileUploadService } = this.crowi;
  58. const attachment = await Attachment.findById(attachmentId);
  59. await fileUploadService.deleteFile(attachment);
  60. await attachment.remove();
  61. return;
  62. }
  63. async isBrandLogoExist() {
  64. const query = { attachmentType: AttachmentType.BRAND_LOGO };
  65. const count = await Attachment.countDocuments(query);
  66. return count >= 1;
  67. }
  68. }
  69. module.exports = AttachmentService;