attachment.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import path from 'path';
  2. import type { IAttachment } from '@growi/core';
  3. import { addSeconds } from 'date-fns/addSeconds';
  4. import {
  5. Schema, type Model, type Document,
  6. } from 'mongoose';
  7. import mongoosePaginate from 'mongoose-paginate-v2';
  8. import uniqueValidator from 'mongoose-unique-validator';
  9. import loggerFactory from '~/utils/logger';
  10. import { AttachmentType } from '../interfaces/attachment';
  11. import { getOrCreateModel } from '../util/mongoose-utils';
  12. // eslint-disable-next-line no-unused-vars
  13. const logger = loggerFactory('growi:models:attachment');
  14. function generateFileHash(fileName) {
  15. const hash = require('crypto').createHash('md5');
  16. hash.update(`${fileName}_${Date.now()}`);
  17. return hash.digest('hex');
  18. }
  19. type GetValidTemporaryUrl = () => string | null | undefined;
  20. type CashTemporaryUrlByProvideSec = (temporaryUrl: string, lifetimeSec: number) => Promise<IAttachmentDocument>;
  21. export interface IAttachmentDocument extends IAttachment, Document {
  22. getValidTemporaryUrl: GetValidTemporaryUrl
  23. cashTemporaryUrlByProvideSec: CashTemporaryUrlByProvideSec,
  24. }
  25. export interface IAttachmentModel extends Model<IAttachmentDocument> {
  26. createWithoutSave
  27. }
  28. const attachmentSchema = new Schema({
  29. page: { type: Schema.Types.ObjectId, ref: 'Page', index: true },
  30. creator: { type: Schema.Types.ObjectId, ref: 'User', index: true },
  31. filePath: { type: String }, // DEPRECATED: remains for backward compatibility for v3.3.x or below
  32. fileName: { type: String, required: true, unique: true },
  33. fileFormat: { type: String, required: true },
  34. fileSize: { type: Number, default: 0 },
  35. originalName: { type: String },
  36. temporaryUrlCached: { type: String },
  37. temporaryUrlExpiredAt: { type: Date },
  38. attachmentType: {
  39. type: String,
  40. enum: AttachmentType,
  41. required: true,
  42. },
  43. }, {
  44. timestamps: { createdAt: true, updatedAt: false },
  45. });
  46. attachmentSchema.plugin(uniqueValidator);
  47. attachmentSchema.plugin(mongoosePaginate);
  48. // virtual
  49. attachmentSchema.virtual('filePathProxied').get(function() {
  50. return `/attachment/${this._id}`;
  51. });
  52. attachmentSchema.virtual('downloadPathProxied').get(function() {
  53. return `/download/${this._id}`;
  54. });
  55. attachmentSchema.set('toObject', { virtuals: true });
  56. attachmentSchema.set('toJSON', { virtuals: true });
  57. attachmentSchema.statics.createWithoutSave = function(pageId, user, fileStream, originalName, fileFormat, fileSize, attachmentType) {
  58. // eslint-disable-next-line @typescript-eslint/no-this-alias
  59. const Attachment = this;
  60. const extname = path.extname(originalName);
  61. let fileName = generateFileHash(originalName);
  62. if (extname.length > 1) { // ignore if empty or '.' only
  63. fileName = `${fileName}${extname}`;
  64. }
  65. const attachment = new Attachment();
  66. attachment.page = pageId;
  67. attachment.creator = user._id;
  68. attachment.originalName = originalName;
  69. attachment.fileName = fileName;
  70. attachment.fileFormat = fileFormat;
  71. attachment.fileSize = fileSize;
  72. attachment.attachmentType = attachmentType;
  73. return attachment;
  74. };
  75. const getValidTemporaryUrl: GetValidTemporaryUrl = function(this: IAttachmentDocument) {
  76. if (this.temporaryUrlExpiredAt == null) {
  77. return null;
  78. }
  79. // return null when expired url
  80. if (this.temporaryUrlExpiredAt.getTime() < new Date().getTime()) {
  81. return null;
  82. }
  83. return this.temporaryUrlCached;
  84. };
  85. attachmentSchema.methods.getValidTemporaryUrl = getValidTemporaryUrl;
  86. const cashTemporaryUrlByProvideSec: CashTemporaryUrlByProvideSec = function(this: IAttachmentDocument, temporaryUrl, lifetimeSec) {
  87. if (temporaryUrl == null) {
  88. throw new Error('url is required.');
  89. }
  90. this.temporaryUrlCached = temporaryUrl;
  91. this.temporaryUrlExpiredAt = addSeconds(new Date(), lifetimeSec);
  92. return this.save();
  93. };
  94. attachmentSchema.methods.cashTemporaryUrlByProvideSec = cashTemporaryUrlByProvideSec;
  95. export const Attachment = getOrCreateModel<IAttachmentDocument, IAttachmentModel>('Attachment', attachmentSchema);