All files / models attachment.js

18.6% Statements 16/86
0% Branches 0/20
3.85% Functions 1/26
18.6% Lines 16/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 18415x 15x 15x 15x 15x                 15x                                   15x       15x                                 15x                                           15x                                                   15x                     15x                                 15x                                               15x             15x                                           15x    
module.exports = function(crowi) {
  var debug = require('debug')('crowi:models:attachment')
  var mongoose = require('mongoose')
  var ObjectId = mongoose.Schema.Types.ObjectId
  var fileUploader = require('../util/fileUploader')(crowi)
 
  function generateFileHash(fileName) {
    var hasher = require('crypto').createHash('md5')
    hasher.update(fileName)
 
    return hasher.digest('hex')
  }
 
  const attachmentSchema = new mongoose.Schema(
    {
      page: { type: ObjectId, ref: 'Page', index: true },
      creator: { type: ObjectId, ref: 'User', index: true },
      filePath: { type: String, required: true },
      fileName: { type: String, required: true },
      originalName: { type: String },
      fileFormat: { type: String, required: true },
      fileSize: { type: Number, default: 0 },
      createdAt: { type: Date, default: Date.now },
    },
    {
      toJSON: {
        virtuals: true,
      },
    },
  )
 
  attachmentSchema.virtual('fileUrl').get(function() {
    return `/files/${this._id}`
  })
 
  attachmentSchema.statics.findById = function(id) {
    var Attachment = this
 
    return new Promise(function(resolve, reject) {
      Attachment.findOne({ _id: id }, function(err, data) {
        if (err) {
          return reject(err)
        }
 
        if (data === null) {
          return reject(new Error('Attachment not found'))
        }
        return resolve(data)
      })
    })
  }
 
  attachmentSchema.statics.getListByPageId = function(id) {
    var self = this
 
    return new Promise(function(resolve, reject) {
      self
        .find({ page: id })
        .sort({ updatedAt: 1 })
        .populate('creator')
        .exec(function(err, data) {
          if (err) {
            return reject(err)
          }
 
          if (data.length < 1) {
            return resolve([])
          }
 
          return resolve(data)
        })
    })
  }
 
  attachmentSchema.statics.create = function(pageId, creator, filePath, originalName, fileName, fileFormat, fileSize) {
    var Attachment = this
 
    return new Promise(function(resolve, reject) {
      var newAttachment = new Attachment()
 
      newAttachment.page = pageId
      newAttachment.creator = creator._id
      newAttachment.filePath = filePath
      newAttachment.originalName = originalName
      newAttachment.fileName = fileName
      newAttachment.fileFormat = fileFormat
      newAttachment.fileSize = fileSize
      newAttachment.createdAt = Date.now()
 
      newAttachment.save(function(err, data) {
        if (err) {
          debug('Error on saving attachment.', err)
          return reject(err)
        }
        debug('Attachment saved.', data)
        return resolve(data)
      })
    })
  }
 
  attachmentSchema.statics.guessExtByFileType = function(fileType) {
    let ext = ''
    const isImage = fileType.match(/^image\/(.+)/i)
 
    if (isImage) {
      ext = isImage[1].toLowerCase()
    }
 
    return ext
  }
 
  attachmentSchema.statics.createAttachmentFilePath = function(pageId, fileName, fileType) {
    const Attachment = this
    let ext = ''
    const fnExt = fileName.match(/(.*)(?:\.([^.]+$))/)
 
    if (fnExt) {
      ext = '.' + fnExt[2]
    } else {
      ext = Attachment.guessExtByFileType(fileType)
      if (ext !== '') {
        ext = '.' + ext
      }
    }
 
    return 'attachment/' + pageId + '/' + generateFileHash(fileName) + ext
  }
 
  attachmentSchema.statics.removeAttachmentsByPageId = function(pageId) {
    var Attachment = this
 
    return new Promise((resolve, reject) => {
      Attachment.getListByPageId(pageId)
        .then(attachments => {
          for (const attachment of attachments) {
            Attachment.removeAttachment(attachment)
              .then(res => {
                // do nothing
              })
              .catch(err => {
                debug('Attachment remove error', err)
              })
          }
 
          resolve(attachments)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
 
  attachmentSchema.statics.findDeliveryFile = function(attachment, forceUpdate) {
    // TODO
    var forceUpdate = forceUpdate || false
 
    return fileUploader.findDeliveryFile(attachment._id, attachment.filePath)
  }
 
  attachmentSchema.statics.removeAttachment = function(attachment) {
    const Attachment = this
    const filePath = attachment.filePath
 
    return new Promise((resolve, reject) => {
      Attachment.remove({ _id: attachment._id }, (err, data) => {
        if (err) {
          return reject(err)
        }
 
        fileUploader
          .deleteFile(attachment._id, filePath)
          .then(data => {
            resolve(data) // this may null
          })
          .catch(err => {
            reject(err)
          })
      })
    })
  }
 
  return mongoose.model('Attachment', attachmentSchema)
}