2016-08-22 17:54:10 +02:00
|
|
|
var moment = require('moment'),
|
|
|
|
path = require('path');
|
2013-11-07 16:00:39 +00:00
|
|
|
|
2014-08-28 23:48:49 -04:00
|
|
|
function StorageBase() {
|
2016-08-22 23:51:42 +02:00
|
|
|
Object.defineProperty(this, 'requiredFns', {
|
2016-11-09 09:17:27 +01:00
|
|
|
value: ['exists', 'save', 'serve', 'delete', 'read'],
|
2016-08-22 23:51:42 +02:00
|
|
|
writable: false
|
|
|
|
});
|
2014-08-28 23:48:49 -04:00
|
|
|
}
|
2013-11-07 16:00:39 +00:00
|
|
|
|
2014-08-28 23:48:49 -04:00
|
|
|
StorageBase.prototype.getTargetDir = function (baseDir) {
|
2016-06-03 09:06:18 +01:00
|
|
|
var m = moment(),
|
2014-09-02 23:24:12 -04:00
|
|
|
month = m.format('MM'),
|
2016-08-22 17:54:10 +02:00
|
|
|
year = m.format('YYYY');
|
2014-08-28 23:48:49 -04:00
|
|
|
|
|
|
|
if (baseDir) {
|
|
|
|
return path.join(baseDir, year, month);
|
|
|
|
}
|
|
|
|
|
|
|
|
return path.join(year, month);
|
|
|
|
};
|
|
|
|
|
|
|
|
StorageBase.prototype.generateUnique = function (store, dir, name, ext, i) {
|
|
|
|
var self = this,
|
|
|
|
filename,
|
|
|
|
append = '';
|
2013-11-07 16:00:39 +00:00
|
|
|
|
2014-08-28 23:48:49 -04:00
|
|
|
if (i) {
|
|
|
|
append = '-' + i;
|
2013-11-07 16:00:39 +00:00
|
|
|
}
|
2014-08-28 23:48:49 -04:00
|
|
|
|
2016-08-22 17:54:10 +02:00
|
|
|
if (ext) {
|
|
|
|
filename = path.join(dir, name + append + ext);
|
|
|
|
} else {
|
|
|
|
filename = path.join(dir, name + append);
|
|
|
|
}
|
2014-08-28 23:48:49 -04:00
|
|
|
|
|
|
|
return store.exists(filename).then(function (exists) {
|
|
|
|
if (exists) {
|
|
|
|
i = i + 1;
|
|
|
|
return self.generateUnique(store, dir, name, ext, i);
|
|
|
|
} else {
|
|
|
|
return filename;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
StorageBase.prototype.getUniqueFileName = function (store, image, targetDir) {
|
2016-08-22 17:54:10 +02:00
|
|
|
var ext = path.extname(image.name), name;
|
|
|
|
|
|
|
|
// poor extension validation
|
|
|
|
// .1 is not a valid extension
|
|
|
|
if (!ext.match(/.\d/)) {
|
2016-09-14 18:24:28 +01:00
|
|
|
name = this.getSanitizedFileName(path.basename(image.name, ext));
|
2016-08-22 17:54:10 +02:00
|
|
|
return this.generateUnique(store, targetDir, name, ext, 0);
|
|
|
|
} else {
|
2016-09-14 18:24:28 +01:00
|
|
|
name = this.getSanitizedFileName(path.basename(image.name));
|
2016-08-22 17:54:10 +02:00
|
|
|
return this.generateUnique(store, targetDir, name, null, 0);
|
|
|
|
}
|
2013-11-07 16:00:39 +00:00
|
|
|
};
|
|
|
|
|
2016-09-14 18:24:28 +01:00
|
|
|
StorageBase.prototype.getSanitizedFileName = function getSanitizedFileName(fileName) {
|
|
|
|
// below only matches ascii characters, @, and .
|
|
|
|
// unicode filenames like город.zip would therefore resolve to ----.zip
|
|
|
|
return fileName.replace(/[^\w@.]/gi, '-');
|
|
|
|
};
|
|
|
|
|
2014-08-28 23:48:49 -04:00
|
|
|
module.exports = StorageBase;
|