Ghost/core/server/middleware/serve-favicon.js

89 lines
3.2 KiB
JavaScript
Raw Normal View History

var fs = require('fs'),
path = require('path'),
crypto = require('crypto'),
storage = require('../storage'),
utils = require('../utils'),
settingsCache = require('../settings/cache'),
🙇 Blog icon utils and publisher.logo for JSON-LD (#8297) refs #8221, closes #7688, refs #7558 🙇 Improve meta data publisher logo behaviour This is a follow-up PR for #8285. Reasons: The code changes of #8285 caused error messages when falling back to the default `favicon.ico`, as the `image-size` tool doesn't support `ico` files. This PR takes the logic to decide which logo needs to be listed in our schema into a new fn `blog_logo.js`. There we have now three decisions: 1. If we have a publication **logo**, we'll take that one 2. If we have no publication logo, but an **icon** we'll use this one. 3. If we have none of the above things, we fall back to our default `favicon.ico` Additional, we're hard coding image dimensions for whenever the logo is an `.ico` file and built and extra decision to not call `image-size` when the dimension are already given. I will create another follow-up PR, which checks the extension type for the file and offers it as a util. 🛠 Blog icon util refs #7688 Serve functionality around the blog icon in its own util: - getIconDimensions -> async function that takes the filepath of on ico file and returns its dimensions - isIcoImageType -> returns true if file has `.ico` extension - getIconType -> returns icon-type (`x-icon` or `png`) - getIconUrl -> returns the absolut or relativ URL for the favicon: `[subdirectory or not]favicon.[ico or png]` 📖 Get .ico sizes for meta data & logo improvement refs #7558 refs #8221 Use the new `blogIconUtil` in meta data to fetch the dimensions of `.ico` files. Improvements for `publisher.logo`: We're now returning a hard-coded 'faked' image dimensions value to render an `imageObject` and prevent error our schema (Google structured data). As soon as an image (`.ico` or non-`.ico`) is too large, but - in case of non-`.ico` - a square format, be set the image-dimensions to 60px width and height. This reduces the chances of getting constantly error messages from Googles' webmaster tools. - add getIconPath util
2017-04-11 19:32:06 +03:00
blogIconUtils = require('../utils/blog-icon'),
buildContentResponse,
content;
buildContentResponse = function buildContentResponse(ext, buf) {
content = {
headers: {
'Content-Type': 'image/' + ext,
'Content-Length': buf.length,
ETag: '"' + crypto.createHash('md5').update(buf, 'utf8').digest('hex') + '"',
'Cache-Control': 'public, max-age=' + utils.ONE_DAY_S
},
body: buf
};
return content;
};
// ### serveFavicon Middleware
// Handles requests to favicon.png and favicon.ico
function serveFavicon() {
var iconType,
filePath;
return function serveFavicon(req, res, next) {
if (req.path.match(/^\/favicon\.(ico|png)/i)) {
// CASE: favicon is default
// confusing: if you upload an icon, it's same logic as storing images
// we store as /content/images, because this is the url path images get requested via the browser
// we are using an express route to skip /content/images and the result is a image path
// based on config.getContentPath('images') + req.path
// in this case we don't use path rewrite, that's why we have to make it manually
🙇 Blog icon utils and publisher.logo for JSON-LD (#8297) refs #8221, closes #7688, refs #7558 🙇 Improve meta data publisher logo behaviour This is a follow-up PR for #8285. Reasons: The code changes of #8285 caused error messages when falling back to the default `favicon.ico`, as the `image-size` tool doesn't support `ico` files. This PR takes the logic to decide which logo needs to be listed in our schema into a new fn `blog_logo.js`. There we have now three decisions: 1. If we have a publication **logo**, we'll take that one 2. If we have no publication logo, but an **icon** we'll use this one. 3. If we have none of the above things, we fall back to our default `favicon.ico` Additional, we're hard coding image dimensions for whenever the logo is an `.ico` file and built and extra decision to not call `image-size` when the dimension are already given. I will create another follow-up PR, which checks the extension type for the file and offers it as a util. 🛠 Blog icon util refs #7688 Serve functionality around the blog icon in its own util: - getIconDimensions -> async function that takes the filepath of on ico file and returns its dimensions - isIcoImageType -> returns true if file has `.ico` extension - getIconType -> returns icon-type (`x-icon` or `png`) - getIconUrl -> returns the absolut or relativ URL for the favicon: `[subdirectory or not]favicon.[ico or png]` 📖 Get .ico sizes for meta data & logo improvement refs #7558 refs #8221 Use the new `blogIconUtil` in meta data to fetch the dimensions of `.ico` files. Improvements for `publisher.logo`: We're now returning a hard-coded 'faked' image dimensions value to render an `imageObject` and prevent error our schema (Google structured data). As soon as an image (`.ico` or non-`.ico`) is too large, but - in case of non-`.ico` - a square format, be set the image-dimensions to 60px width and height. This reduces the chances of getting constantly error messages from Googles' webmaster tools. - add getIconPath util
2017-04-11 19:32:06 +03:00
filePath = blogIconUtils.getIconPath();
var originalExtension = path.extname(filePath).toLowerCase(),
requestedExtension = path.extname(req.path).toLowerCase();
// CASE: custom favicon exists, load it from local file storage
if (settingsCache.get('icon')) {
// depends on the uploaded icon extension
if (originalExtension !== requestedExtension) {
return res.redirect(302, utils.url.urlFor({relativeUrl: '/favicon' + originalExtension}));
}
😱 🎨 Refactor storage adapter (#8229) refs #7687 There are four main changes in this PR: we have outsourced the base storage adapter to npm, because for storage developers it's annoying to inherit from a script within Ghost we hacked theme storage handling into the default local storage adapter - this was reverted, instead we have added a static theme storage here use classes instead of prototyping optimise the storage adapter in general - everything is explained in each commit ---- * rename local-file-store to LocalFileStorage I would like to keep the name pattern i have used for scheduling. If a file is a class, the file name reflects the class name. We can discuss this, if concerns are raised. * Transform LocalFileStorage to class and inherit from new base - inherit from npm ghost-storage-base - rewrite to class - no further refactoring, happens later * Rename core/test/unit/storage/local-file-store_spec.js -> core/test/unit/storage/LocalFileStorage_spec.js * Fix wrong require in core/test/unit/storage/LocalFileStorage_spec.js * remove base storage and test - see https://github.com/kirrg001/Ghost-Storage-Base - the test has moved to this repo as well * Use npm ghost-storage-base in storage/index.js * remove the concept of getStorage('themes') This concept was added when we added themes as a feature. Back then, we have changed the local storage adapter to support images and themes. This has added some hacks into the local storage adapters. We want to revert this change and add a simple static theme storage. Will adapt the api/themes layer in the next commits. * Revert LocalFileStorage - revert serve - revert delete * add storagePath as property to LocalFileStorage - define one property which holds the storage path - could be considered to pass from outside, but found that not helpful, as other storage adapters do not need this property - IMPORTANT: save has no longer a targetDir option, because this was used to pass the alternative theme storage path - IMPORTANT: exists has now an alternative targetDir, this makes sense, because - you can either ask the storage exists('my-file') and it will look in the base storage path - or you pass a specific path where to look exists('my-file', /path/to/dir) * LocalFileStorage: get rid of store pattern - getUniqueFileName(THIS) - this doesn't make sense, instances always have access to this by default * Add static theme storage - inherits from the local file storage, because they both operate on the file system - IMPORTANT: added a TODO to consider a merge of themes/loader and themes/storage - but will be definitely not part of this PR * Use new static theme storage in api/themes - storage functions are simplified! * Add https://github.com/kirrg001/Ghost-Storage-Base as dependency - tarball for now, as i am still testing - will release if PR review get's accepted * Adapt tests and jscs/jshint * 🐛 fix storage.read in favicon utility - wrong implementation of error handling * 🎨 optimise error messages for custom storage adapter errors * little renaming in the storage utlity - purpose is to have access to the custom storage instance and to the custom storage class - see next commit why * optimise instanceof base storage - instanceof is always tricky in javascript - if multiple modules exist, it can happen that instanceof is false * fix getTargetDir - the importer uses the `targetDir` option to ensure that images land in the correct folder * ghost-storage-base@0.0.1 package.json dependency
2017-04-05 17:10:34 +03:00
storage.getStorage()
.read({path: filePath})
.then(function readFile(buf) {
🙇 Blog icon utils and publisher.logo for JSON-LD (#8297) refs #8221, closes #7688, refs #7558 🙇 Improve meta data publisher logo behaviour This is a follow-up PR for #8285. Reasons: The code changes of #8285 caused error messages when falling back to the default `favicon.ico`, as the `image-size` tool doesn't support `ico` files. This PR takes the logic to decide which logo needs to be listed in our schema into a new fn `blog_logo.js`. There we have now three decisions: 1. If we have a publication **logo**, we'll take that one 2. If we have no publication logo, but an **icon** we'll use this one. 3. If we have none of the above things, we fall back to our default `favicon.ico` Additional, we're hard coding image dimensions for whenever the logo is an `.ico` file and built and extra decision to not call `image-size` when the dimension are already given. I will create another follow-up PR, which checks the extension type for the file and offers it as a util. 🛠 Blog icon util refs #7688 Serve functionality around the blog icon in its own util: - getIconDimensions -> async function that takes the filepath of on ico file and returns its dimensions - isIcoImageType -> returns true if file has `.ico` extension - getIconType -> returns icon-type (`x-icon` or `png`) - getIconUrl -> returns the absolut or relativ URL for the favicon: `[subdirectory or not]favicon.[ico or png]` 📖 Get .ico sizes for meta data & logo improvement refs #7558 refs #8221 Use the new `blogIconUtil` in meta data to fetch the dimensions of `.ico` files. Improvements for `publisher.logo`: We're now returning a hard-coded 'faked' image dimensions value to render an `imageObject` and prevent error our schema (Google structured data). As soon as an image (`.ico` or non-`.ico`) is too large, but - in case of non-`.ico` - a square format, be set the image-dimensions to 60px width and height. This reduces the chances of getting constantly error messages from Googles' webmaster tools. - add getIconPath util
2017-04-11 19:32:06 +03:00
iconType = blogIconUtils.getIconType();
😱 🎨 Refactor storage adapter (#8229) refs #7687 There are four main changes in this PR: we have outsourced the base storage adapter to npm, because for storage developers it's annoying to inherit from a script within Ghost we hacked theme storage handling into the default local storage adapter - this was reverted, instead we have added a static theme storage here use classes instead of prototyping optimise the storage adapter in general - everything is explained in each commit ---- * rename local-file-store to LocalFileStorage I would like to keep the name pattern i have used for scheduling. If a file is a class, the file name reflects the class name. We can discuss this, if concerns are raised. * Transform LocalFileStorage to class and inherit from new base - inherit from npm ghost-storage-base - rewrite to class - no further refactoring, happens later * Rename core/test/unit/storage/local-file-store_spec.js -> core/test/unit/storage/LocalFileStorage_spec.js * Fix wrong require in core/test/unit/storage/LocalFileStorage_spec.js * remove base storage and test - see https://github.com/kirrg001/Ghost-Storage-Base - the test has moved to this repo as well * Use npm ghost-storage-base in storage/index.js * remove the concept of getStorage('themes') This concept was added when we added themes as a feature. Back then, we have changed the local storage adapter to support images and themes. This has added some hacks into the local storage adapters. We want to revert this change and add a simple static theme storage. Will adapt the api/themes layer in the next commits. * Revert LocalFileStorage - revert serve - revert delete * add storagePath as property to LocalFileStorage - define one property which holds the storage path - could be considered to pass from outside, but found that not helpful, as other storage adapters do not need this property - IMPORTANT: save has no longer a targetDir option, because this was used to pass the alternative theme storage path - IMPORTANT: exists has now an alternative targetDir, this makes sense, because - you can either ask the storage exists('my-file') and it will look in the base storage path - or you pass a specific path where to look exists('my-file', /path/to/dir) * LocalFileStorage: get rid of store pattern - getUniqueFileName(THIS) - this doesn't make sense, instances always have access to this by default * Add static theme storage - inherits from the local file storage, because they both operate on the file system - IMPORTANT: added a TODO to consider a merge of themes/loader and themes/storage - but will be definitely not part of this PR * Use new static theme storage in api/themes - storage functions are simplified! * Add https://github.com/kirrg001/Ghost-Storage-Base as dependency - tarball for now, as i am still testing - will release if PR review get's accepted * Adapt tests and jscs/jshint * 🐛 fix storage.read in favicon utility - wrong implementation of error handling * 🎨 optimise error messages for custom storage adapter errors * little renaming in the storage utlity - purpose is to have access to the custom storage instance and to the custom storage class - see next commit why * optimise instanceof base storage - instanceof is always tricky in javascript - if multiple modules exist, it can happen that instanceof is false * fix getTargetDir - the importer uses the `targetDir` option to ensure that images land in the correct folder * ghost-storage-base@0.0.1 package.json dependency
2017-04-05 17:10:34 +03:00
content = buildContentResponse(iconType, buf);
😱 🎨 Refactor storage adapter (#8229) refs #7687 There are four main changes in this PR: we have outsourced the base storage adapter to npm, because for storage developers it's annoying to inherit from a script within Ghost we hacked theme storage handling into the default local storage adapter - this was reverted, instead we have added a static theme storage here use classes instead of prototyping optimise the storage adapter in general - everything is explained in each commit ---- * rename local-file-store to LocalFileStorage I would like to keep the name pattern i have used for scheduling. If a file is a class, the file name reflects the class name. We can discuss this, if concerns are raised. * Transform LocalFileStorage to class and inherit from new base - inherit from npm ghost-storage-base - rewrite to class - no further refactoring, happens later * Rename core/test/unit/storage/local-file-store_spec.js -> core/test/unit/storage/LocalFileStorage_spec.js * Fix wrong require in core/test/unit/storage/LocalFileStorage_spec.js * remove base storage and test - see https://github.com/kirrg001/Ghost-Storage-Base - the test has moved to this repo as well * Use npm ghost-storage-base in storage/index.js * remove the concept of getStorage('themes') This concept was added when we added themes as a feature. Back then, we have changed the local storage adapter to support images and themes. This has added some hacks into the local storage adapters. We want to revert this change and add a simple static theme storage. Will adapt the api/themes layer in the next commits. * Revert LocalFileStorage - revert serve - revert delete * add storagePath as property to LocalFileStorage - define one property which holds the storage path - could be considered to pass from outside, but found that not helpful, as other storage adapters do not need this property - IMPORTANT: save has no longer a targetDir option, because this was used to pass the alternative theme storage path - IMPORTANT: exists has now an alternative targetDir, this makes sense, because - you can either ask the storage exists('my-file') and it will look in the base storage path - or you pass a specific path where to look exists('my-file', /path/to/dir) * LocalFileStorage: get rid of store pattern - getUniqueFileName(THIS) - this doesn't make sense, instances always have access to this by default * Add static theme storage - inherits from the local file storage, because they both operate on the file system - IMPORTANT: added a TODO to consider a merge of themes/loader and themes/storage - but will be definitely not part of this PR * Use new static theme storage in api/themes - storage functions are simplified! * Add https://github.com/kirrg001/Ghost-Storage-Base as dependency - tarball for now, as i am still testing - will release if PR review get's accepted * Adapt tests and jscs/jshint * 🐛 fix storage.read in favicon utility - wrong implementation of error handling * 🎨 optimise error messages for custom storage adapter errors * little renaming in the storage utlity - purpose is to have access to the custom storage instance and to the custom storage class - see next commit why * optimise instanceof base storage - instanceof is always tricky in javascript - if multiple modules exist, it can happen that instanceof is false * fix getTargetDir - the importer uses the `targetDir` option to ensure that images land in the correct folder * ghost-storage-base@0.0.1 package.json dependency
2017-04-05 17:10:34 +03:00
res.writeHead(200, content.headers);
res.end(content.body);
})
.catch(function (err) {
next(err);
});
} else {
originalExtension = path.extname(filePath).toLowerCase();
// CASE: always redirect to .ico for default icon
if (originalExtension !== requestedExtension) {
return res.redirect(302, utils.url.urlFor({relativeUrl: '/favicon.ico'}));
}
fs.readFile(filePath, function readFile(err, buf) {
if (err) {
return next(err);
}
content = buildContentResponse('x-icon', buf);
res.writeHead(200, content.headers);
res.end(content.body);
});
}
} else {
next();
}
};
}
module.exports = serveFavicon;