attachment.js 2.3 KB

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