Ghost/core/server/storage/local-file-store.js

153 lines
5.3 KiB
JavaScript
Raw Normal View History

// # Local File System Image Storage module
// The (default) module for storing images, using the local file system
var serveStatic = require('express').static,
fs = require('fs-extra'),
os = require('os'),
path = require('path'),
util = require('util'),
Promise = require('bluebird'),
config = require('../config'),
🎨 configurable logging with bunyan (#7431) - 🛠 add bunyan and prettyjson, remove morgan - ✨ add logging module - GhostLogger class that handles setup of bunyan - PrettyStream for stdout - ✨ config for logging - @TODO: testing level fatal? - ✨ log each request via GhostLogger (express middleware) - @TODO: add errors to output - 🔥 remove errors.updateActiveTheme - we can read the value from config - 🔥 remove 15 helper functions in core/server/errors/index.js - all these functions get replaced by modules: 1. logging 2. error middleware handling for html/json 3. error creation (which will be part of PR #7477) - ✨ add express error handler for html/json - one true error handler for express responses - contains still some TODO's, but they are not high priority for first implementation/integration - this middleware only takes responsibility of either rendering html responses or return json error responses - 🎨 use new express error handler in middleware/index - 404 and 500 handling - 🎨 return error instead of error message in permissions/index.js - the rule for error handling should be: if you call a unit, this unit should return a custom Ghost error - 🎨 wrap serve static module - rule: if you call a module/unit, you should always wrap this error - it's always the same rule - so the caller never has to worry about what comes back - it's always a clear error instance - in this case: we return our notfounderror if serve static does not find the resource - this avoid having checks everywhere - 🎨 replace usages of errors/index.js functions and adapt tests - use logging.error, logging.warn - make tests green - remove some usages of logging and throwing api errors -> because when a request is involved, logging happens automatically - 🐛 return errorDetails to Ghost-Admin - errorDetails is used for Theme error handling - 🎨 use 500er error for theme is missing error in theme-handler - 🎨 extend file rotation to 1w
2016-10-04 18:33:43 +03:00
errors = require('../errors'),
i18n = require('../i18n'),
utils = require('../utils'),
BaseStore = require('./base'),
remove = Promise.promisify(fs.remove);
function LocalFileStore() {
BaseStore.call(this);
}
util.inherits(LocalFileStore, 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
LocalFileStore.prototype.save = function save(image, targetDir) {
targetDir = targetDir || this.getTargetDir(config.getContentPath('images'));
var targetFilename;
return this.getUniqueFileName(this, image, targetDir).then(function (filename) {
targetFilename = filename;
return Promise.promisify(fs.mkdirs)(targetDir);
}).then(function () {
return Promise.promisify(fs.copy)(image.path, targetFilename);
}).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
var fullUrl = (
utils.url.urlJoin('/', utils.url.getSubdir(),
config.get('paths').imagesRelPath,
path.relative(config.getContentPath('images'), targetFilename))
).replace(new RegExp('\\' + path.sep, 'g'), '/');
return fullUrl;
}).catch(function (e) {
return Promise.reject(e);
});
};
LocalFileStore.prototype.exists = function exists(filename) {
return new Promise(function (resolve) {
fs.stat(filename, function (err) {
var exists = !err;
resolve(exists);
});
});
};
// middleware for serving the files
LocalFileStore.prototype.serve = function serve(options) {
options = options || {};
// CASE: serve themes
// serveStatic can't be used to serve themes, because
// download files depending on the route (see `send` npm module)
if (options.isTheme) {
return function downloadTheme(req, res, next) {
var themeName = options.name,
themePath = path.join(config.getContentPath('themes'), themeName),
zipName = themeName + '.zip',
// store this in a unique temporary folder
zipBasePath = path.join(os.tmpdir(), utils.uid(10)),
zipPath = path.join(zipBasePath, zipName),
stream;
Promise.promisify(fs.ensureDir)(zipBasePath)
.then(function () {
return Promise.promisify(utils.zipFolder)(themePath, zipPath);
})
.then(function (length) {
res.set({
'Content-disposition': 'attachment; filename={themeName}.zip'.replace('{themeName}', themeName),
'Content-Type': 'application/zip',
'Content-Length': length
});
stream = fs.createReadStream(zipPath);
stream.pipe(res);
})
.catch(function (err) {
next(err);
})
.finally(function () {
remove(zipBasePath);
});
};
} else {
// CASE: serve images
// For some reason send divides the max age number by 1000
// Fallthrough: false ensures that if an image isn't found, it automatically 404s
🎨 configurable logging with bunyan (#7431) - 🛠 add bunyan and prettyjson, remove morgan - ✨ add logging module - GhostLogger class that handles setup of bunyan - PrettyStream for stdout - ✨ config for logging - @TODO: testing level fatal? - ✨ log each request via GhostLogger (express middleware) - @TODO: add errors to output - 🔥 remove errors.updateActiveTheme - we can read the value from config - 🔥 remove 15 helper functions in core/server/errors/index.js - all these functions get replaced by modules: 1. logging 2. error middleware handling for html/json 3. error creation (which will be part of PR #7477) - ✨ add express error handler for html/json - one true error handler for express responses - contains still some TODO's, but they are not high priority for first implementation/integration - this middleware only takes responsibility of either rendering html responses or return json error responses - 🎨 use new express error handler in middleware/index - 404 and 500 handling - 🎨 return error instead of error message in permissions/index.js - the rule for error handling should be: if you call a unit, this unit should return a custom Ghost error - 🎨 wrap serve static module - rule: if you call a module/unit, you should always wrap this error - it's always the same rule - so the caller never has to worry about what comes back - it's always a clear error instance - in this case: we return our notfounderror if serve static does not find the resource - this avoid having checks everywhere - 🎨 replace usages of errors/index.js functions and adapt tests - use logging.error, logging.warn - make tests green - remove some usages of logging and throwing api errors -> because when a request is involved, logging happens automatically - 🐛 return errorDetails to Ghost-Admin - errorDetails is used for Theme error handling - 🎨 use 500er error for theme is missing error in theme-handler - 🎨 extend file rotation to 1w
2016-10-04 18:33:43 +03:00
// Wrap server static errors
return function serveStaticContent(req, res, next) {
return serveStatic(config.getContentPath('images'), {maxAge: utils.ONE_YEAR_MS, fallthrough: false})(req, res, function (err) {
if (err) {
if (err.statusCode === 404) {
return next(new errors.NotFoundError({message: i18n.t('errors.errors.pageNotFound')}));
🎨 configurable logging with bunyan (#7431) - 🛠 add bunyan and prettyjson, remove morgan - ✨ add logging module - GhostLogger class that handles setup of bunyan - PrettyStream for stdout - ✨ config for logging - @TODO: testing level fatal? - ✨ log each request via GhostLogger (express middleware) - @TODO: add errors to output - 🔥 remove errors.updateActiveTheme - we can read the value from config - 🔥 remove 15 helper functions in core/server/errors/index.js - all these functions get replaced by modules: 1. logging 2. error middleware handling for html/json 3. error creation (which will be part of PR #7477) - ✨ add express error handler for html/json - one true error handler for express responses - contains still some TODO's, but they are not high priority for first implementation/integration - this middleware only takes responsibility of either rendering html responses or return json error responses - 🎨 use new express error handler in middleware/index - 404 and 500 handling - 🎨 return error instead of error message in permissions/index.js - the rule for error handling should be: if you call a unit, this unit should return a custom Ghost error - 🎨 wrap serve static module - rule: if you call a module/unit, you should always wrap this error - it's always the same rule - so the caller never has to worry about what comes back - it's always a clear error instance - in this case: we return our notfounderror if serve static does not find the resource - this avoid having checks everywhere - 🎨 replace usages of errors/index.js functions and adapt tests - use logging.error, logging.warn - make tests green - remove some usages of logging and throwing api errors -> because when a request is involved, logging happens automatically - 🐛 return errorDetails to Ghost-Admin - errorDetails is used for Theme error handling - 🎨 use 500er error for theme is missing error in theme-handler - 🎨 extend file rotation to 1w
2016-10-04 18:33:43 +03:00
}
return next(new errors.GhostError({err: err}));
🎨 configurable logging with bunyan (#7431) - 🛠 add bunyan and prettyjson, remove morgan - ✨ add logging module - GhostLogger class that handles setup of bunyan - PrettyStream for stdout - ✨ config for logging - @TODO: testing level fatal? - ✨ log each request via GhostLogger (express middleware) - @TODO: add errors to output - 🔥 remove errors.updateActiveTheme - we can read the value from config - 🔥 remove 15 helper functions in core/server/errors/index.js - all these functions get replaced by modules: 1. logging 2. error middleware handling for html/json 3. error creation (which will be part of PR #7477) - ✨ add express error handler for html/json - one true error handler for express responses - contains still some TODO's, but they are not high priority for first implementation/integration - this middleware only takes responsibility of either rendering html responses or return json error responses - 🎨 use new express error handler in middleware/index - 404 and 500 handling - 🎨 return error instead of error message in permissions/index.js - the rule for error handling should be: if you call a unit, this unit should return a custom Ghost error - 🎨 wrap serve static module - rule: if you call a module/unit, you should always wrap this error - it's always the same rule - so the caller never has to worry about what comes back - it's always a clear error instance - in this case: we return our notfounderror if serve static does not find the resource - this avoid having checks everywhere - 🎨 replace usages of errors/index.js functions and adapt tests - use logging.error, logging.warn - make tests green - remove some usages of logging and throwing api errors -> because when a request is involved, logging happens automatically - 🐛 return errorDetails to Ghost-Admin - errorDetails is used for Theme error handling - 🎨 use 500er error for theme is missing error in theme-handler - 🎨 extend file rotation to 1w
2016-10-04 18:33:43 +03:00
}
next();
});
};
}
};
LocalFileStore.prototype.delete = function deleteFile(fileName, targetDir) {
targetDir = targetDir || this.getTargetDir(config.getContentPath('images'));
var pathToDelete = path.join(targetDir, fileName);
return remove(pathToDelete);
};
/**
* Reads bytes from disk for a target image
* path: path of target image (without content path!)
*/
LocalFileStore.prototype.read = function read(options) {
options = options || {};
// remove trailing slashes
options.path = (options.path || '').replace(/\/$|\\$/, '');
var targetPath = path.join(config.getContentPath('images'), options.path);
return new Promise(function (resolve, reject) {
fs.readFile(targetPath, function (err, bytes) {
if (err) {
return reject(new errors.GhostError({
err: err,
message: 'Could not read image: ' + targetPath
}));
}
resolve(bytes);
});
});
};
module.exports = LocalFileStore;