From 92e0bff80c3232a50056dddc7aab35f4ea750926 Mon Sep 17 00:00:00 2001 From: Richard Hansen Date: Mon, 19 Apr 2021 22:47:02 -0400 Subject: [PATCH] favicon: Refactor handler and add tests --- src/node/hooks/express/specialpages.js | 36 +++++++----- src/tests/backend/specs/favicon-test-skin.png | Bin 0 -> 419 bytes src/tests/backend/specs/favicon.js | 55 ++++++++++++++++++ 3 files changed, 75 insertions(+), 16 deletions(-) create mode 100644 src/tests/backend/specs/favicon-test-skin.png create mode 100644 src/tests/backend/specs/favicon.js diff --git a/src/node/hooks/express/specialpages.js b/src/node/hooks/express/specialpages.js index b49132e91..725139c09 100644 --- a/src/node/hooks/express/specialpages.js +++ b/src/node/hooks/express/specialpages.js @@ -2,9 +2,12 @@ const path = require('path'); const eejs = require('../../eejs'); +const fs = require('fs'); +const fsp = fs.promises; const toolbar = require('../../utils/toolbar'); const hooks = require('../../../static/js/pluginfw/hooks'); const settings = require('../../utils/Settings'); +const util = require('util'); const webaccess = require('./webaccess'); exports.expressCreateServer = (hookName, args, cb) => { @@ -74,23 +77,24 @@ exports.expressCreateServer = (hookName, args, cb) => { })); }); - args.app.get('/favicon.ico', (req, res) => { - let filePath = path.join( - settings.root, - 'src', - 'static', - 'skins', - settings.skinName, - 'favicon.ico' - ); - res.setHeader('Cache-Control', `public, max-age=${settings.maxAge}`); - res.sendFile(filePath, (err) => { - // there is no custom favicon, send the default favicon - if (err) { - filePath = path.join(settings.root, 'src', 'static', 'favicon.ico'); - res.sendFile(filePath); + args.app.get('/favicon.ico', (req, res, next) => { + (async () => { + const fns = [ + path.join(settings.root, 'src', 'static', 'skins', settings.skinName, 'favicon.ico'), + path.join(settings.root, 'src', 'static', 'favicon.ico'), + ]; + for (const fn of fns) { + try { + await fsp.access(fn, fs.constants.R_OK); + } catch (err) { + continue; + } + res.setHeader('Cache-Control', `public, max-age=${settings.maxAge}`); + await util.promisify(res.sendFile.bind(res))(fn); + return; } - }); + next(); + })().catch((err) => next(err || new Error(err))); }); return cb(); diff --git a/src/tests/backend/specs/favicon-test-skin.png b/src/tests/backend/specs/favicon-test-skin.png new file mode 100644 index 0000000000000000000000000000000000000000..87bdadbbb323675893ecc522b73bfffdf21aea60 GIT binary patch literal 419 zcmV;U0bKrxP)4J8~X zffI5dxrX=5g`fHP7o$fsz`zB8BK_~?y(HImW_g{!^jNlKWYMdJv6=8g@@B%(tA=42 z+3)SlD8?YU<|a38Ln!4K#+~>fHtr-)$}u!&R