attachment.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // disable no-return-await for model functions
  2. /* eslint-disable no-return-await */
  3. // eslint-disable-next-line no-unused-vars
  4. const logger = require('@alias/logger')('growi:models:attachment');
  5. const path = require('path');
  6. const mongoose = require('mongoose');
  7. const uniqueValidator = require('mongoose-unique-validator');
  8. const ObjectId = mongoose.Schema.Types.ObjectId;
  9. module.exports = function(crowi) {
  10. function generateFileHash(fileName) {
  11. const hash = require('crypto').createHash('md5');
  12. hash.update(`${fileName}_${Date.now()}`);
  13. return hash.digest('hex');
  14. }
  15. const attachmentSchema = new mongoose.Schema({
  16. page: { type: ObjectId, ref: 'Page', index: true },
  17. creator: { type: ObjectId, ref: 'User', index: true },
  18. filePath: { type: String }, // DEPRECATED: remains for backward compatibility for v3.3.x or below
  19. fileName: { type: String, required: true, unique: true },
  20. originalName: { type: String },
  21. fileFormat: { type: String, required: true },
  22. fileSize: { type: Number, default: 0 },
  23. createdAt: { type: Date, default: Date.now },
  24. });
  25. attachmentSchema.plugin(uniqueValidator);
  26. attachmentSchema.virtual('filePathProxied').get(function() {
  27. return `/attachment/${this._id}`;
  28. });
  29. attachmentSchema.virtual('downloadPathProxied').get(function() {
  30. return `/download/${this._id}`;
  31. });
  32. attachmentSchema.set('toObject', { virtuals: true });
  33. attachmentSchema.set('toJSON', { virtuals: true });
  34. attachmentSchema.statics.createWithoutSave = function(pageId, user, fileStream, originalName, fileFormat, fileSize) {
  35. const Attachment = this;
  36. const extname = path.extname(originalName);
  37. let fileName = generateFileHash(originalName);
  38. if (extname.length > 1) { // ignore if empty or '.' only
  39. fileName = `${fileName}${extname}`;
  40. }
  41. const attachment = new Attachment();
  42. attachment.page = pageId;
  43. attachment.creator = user._id;
  44. attachment.originalName = originalName;
  45. attachment.fileName = fileName;
  46. attachment.fileFormat = fileFormat;
  47. attachment.fileSize = fileSize;
  48. attachment.createdAt = Date.now();
  49. return attachment;
  50. };
  51. return mongoose.model('Attachment', attachmentSchema);
  52. };