2013-11-07 20:00:39 +04:00
|
|
|
// # Local File System Image Storage module
|
|
|
|
// The (default) module for storing images, using the local file system
|
|
|
|
|
2014-07-28 17:19:49 +04:00
|
|
|
var _ = require('lodash'),
|
|
|
|
express = require('express'),
|
|
|
|
fs = require('fs-extra'),
|
|
|
|
path = require('path'),
|
2014-08-17 10:17:23 +04:00
|
|
|
Promise = require('bluebird'),
|
2014-07-28 17:19:49 +04:00
|
|
|
errors = require('../errors'),
|
|
|
|
config = require('../config'),
|
|
|
|
utils = require('../utils'),
|
|
|
|
baseStore = require('./base'),
|
2013-11-07 20:00:39 +04:00
|
|
|
|
2013-12-09 04:49:02 +04:00
|
|
|
localFileStore;
|
2013-11-07 20:00:39 +04:00
|
|
|
|
|
|
|
localFileStore = _.extend(baseStore, {
|
|
|
|
// ### Save
|
|
|
|
// Saves the image to storage (the file system)
|
|
|
|
// - image is the express image object
|
|
|
|
// - returns a promise which ultimately returns the full url to the uploaded image
|
|
|
|
'save': function (image) {
|
2014-08-17 10:17:23 +04:00
|
|
|
var targetDir = this.getTargetDir(config.paths.imagesPath),
|
2013-12-04 06:47:39 +04:00
|
|
|
targetFilename;
|
2013-11-07 20:00:39 +04:00
|
|
|
|
2014-08-17 10:17:23 +04:00
|
|
|
return this.getUniqueFileName(this, image, targetDir).then(function (filename) {
|
2013-12-04 06:47:39 +04:00
|
|
|
targetFilename = filename;
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.promisify(fs.mkdirs)(targetDir);
|
2013-12-04 06:47:39 +04:00
|
|
|
}).then(function () {
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.promisify(fs.copy)(image.path, targetFilename);
|
2013-12-04 06:47:39 +04:00
|
|
|
}).then(function () {
|
|
|
|
// The src for the image must be in URI format, not a file system path, which in Windows uses \
|
|
|
|
// For local file system storage can use relative path so add a slash
|
2014-07-17 18:33:21 +04:00
|
|
|
var fullUrl = (config.paths.subdir + '/' + config.paths.imagesRelPath + '/' + path.relative(config.paths.imagesPath, targetFilename)).replace(new RegExp('\\' + path.sep, 'g'), '/');
|
2014-08-17 10:17:23 +04:00
|
|
|
return fullUrl;
|
|
|
|
}).catch(function (e) {
|
2013-12-04 06:47:39 +04:00
|
|
|
errors.logError(e);
|
2014-08-17 10:17:23 +04:00
|
|
|
return Promise.reject(e);
|
2013-12-04 06:47:39 +04:00
|
|
|
});
|
2013-11-07 20:00:39 +04:00
|
|
|
},
|
|
|
|
|
|
|
|
'exists': function (filename) {
|
2014-08-17 10:17:23 +04:00
|
|
|
return new Promise(function (resolve) {
|
|
|
|
fs.exists(filename, function (exists) {
|
|
|
|
resolve(exists);
|
|
|
|
});
|
2013-11-07 20:00:39 +04:00
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
// middleware for serving the files
|
|
|
|
'serve': function () {
|
2013-12-31 03:13:25 +04:00
|
|
|
// For some reason send divides the max age number by 1000
|
2014-07-28 17:19:49 +04:00
|
|
|
return express['static'](config.paths.imagesPath, {maxAge: utils.ONE_YEAR_MS});
|
2013-11-07 20:00:39 +04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
module.exports = localFileStore;
|