local.js 4.53 KB
Newer Older
1
'use strict'
2

3 4 5 6 7 8
const path = require('path')
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs-extra'))
const multer = require('multer')
const os = require('os')
const _ = require('lodash')
9 10 11 12 13 14

/**
 * Local Data Storage
 */
module.exports = {

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
  _uploadsPath: './repo/uploads',
  _uploadsThumbsPath: './data/thumbs',

  uploadImgHandler: null,

  /**
   * Initialize Local Data Storage model
   *
   * @return     {Object}  Local Data Storage model instance
   */
  init () {
    this._uploadsPath = path.resolve(ROOTPATH, appconfig.paths.repo, 'uploads')
    this._uploadsThumbsPath = path.resolve(ROOTPATH, appconfig.paths.data, 'thumbs')

    this.createBaseDirectories(appconfig)
    this.initMulter(appconfig)

    return this
  },

  /**
   * Init Multer upload handlers
   *
   * @param      {Object}   appconfig  The application config
   * @return     {boolean}  Void
   */
  initMulter (appconfig) {
    let maxFileSizes = {
      img: appconfig.uploads.maxImageFileSize * 1024 * 1024,
      file: appconfig.uploads.maxOtherFileSize * 1024 * 1024
    }

    // -> IMAGES

    this.uploadImgHandler = multer({
      storage: multer.diskStorage({
        destination: (req, f, cb) => {
          cb(null, path.resolve(ROOTPATH, appconfig.paths.data, 'temp-upload'))
        }
      }),
      fileFilter: (req, f, cb) => {
        // -> Check filesize

        if (f.size > maxFileSizes.img) {
          return cb(null, false)
        }

        // -> Check MIME type (quick check only)

        if (!_.includes(['image/png', 'image/jpeg', 'image/gif', 'image/webp'], f.mimetype)) {
          return cb(null, false)
        }

        cb(null, true)
      }
    }).array('imgfile', 20)

    // -> FILES

    this.uploadFileHandler = multer({
      storage: multer.diskStorage({
        destination: (req, f, cb) => {
          cb(null, path.resolve(ROOTPATH, appconfig.paths.data, 'temp-upload'))
        }
      }),
      fileFilter: (req, f, cb) => {
        // -> Check filesize

        if (f.size > maxFileSizes.file) {
          return cb(null, false)
        }

        cb(null, true)
      }
    }).array('binfile', 20)

    return true
  },

  /**
   * Creates a base directories (Synchronous).
   *
   * @param      {Object}  appconfig  The application config
   * @return     {Void}  Void
   */
  createBaseDirectories (appconfig) {
101
    winston.info('[SERVER.Local] Checking data directories...')
102 103 104

    try {
      fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.paths.data))
NGPixel's avatar
NGPixel committed
105
      fs.emptyDirSync(path.resolve(ROOTPATH, appconfig.paths.data))
106 107 108 109 110
      fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.paths.data, './cache'))
      fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.paths.data, './thumbs'))
      fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.paths.data, './temp-upload'))

      if (os.type() !== 'Windows_NT') {
111
        fs.chmodSync(path.resolve(ROOTPATH, appconfig.paths.data, './temp-upload'), '755')
112 113 114 115 116 117
      }

      fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.paths.repo))
      fs.ensureDirSync(path.resolve(ROOTPATH, appconfig.paths.repo, './uploads'))

      if (os.type() !== 'Windows_NT') {
118
        fs.chmodSync(path.resolve(ROOTPATH, appconfig.paths.repo, './uploads'), '755')
119 120 121 122 123
      }
    } catch (err) {
      winston.error(err)
    }

124
    winston.info('[SERVER.Local] Data and Repository directories are OK.')
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
  },

  /**
   * Gets the uploads path.
   *
   * @return     {String}  The uploads path.
   */
  getUploadsPath () {
    return this._uploadsPath
  },

  /**
   * Gets the thumbnails folder path.
   *
   * @return     {String}  The thumbs path.
   */
  getThumbsPath () {
    return this._uploadsThumbsPath
  },

  /**
   * Check if filename is valid and unique
   *
   * @param      {String}           f        The filename
   * @param      {String}           fld      The containing folder
   * @param      {boolean}          isImage  Indicates if image
   * @return     {Promise<String>}  Promise of the accepted filename
   */
  validateUploadsFilename (f, fld, isImage) {
    let fObj = path.parse(f)
    let fname = _.chain(fObj.name).trim().toLower().kebabCase().value().replace(/[^a-z0-9-]+/g, '')
    let fext = _.toLower(fObj.ext)

    if (isImage && !_.includes(['.jpg', '.jpeg', '.png', '.gif', '.webp'], fext)) {
      fext = '.png'
    }

    f = fname + fext
    let fpath = path.resolve(this._uploadsPath, fld, f)

    return fs.statAsync(fpath).then((s) => {
      throw new Error('File ' + f + ' already exists.')
    }).catch((err) => {
      if (err.code === 'ENOENT') {
        return f
      }
      throw err
    })
  }

}