|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const { promisify } = require('util') |
| 4 | + |
| 5 | +const request = require('request') |
| 6 | + |
| 7 | +const logger = require('../../logger') |
| 8 | +const config = require('../../config') |
| 9 | + |
| 10 | +let lastCheckAt |
| 11 | + |
| 12 | +const VERSION_CHECK_ENDPOINT = 'https://evangelion.codimd.dev/' |
| 13 | +const CHECK_TIMEOUT = 1000 * 60 * 60 * 24 // 1 day |
| 14 | + |
| 15 | +const rp = promisify(request) |
| 16 | + |
| 17 | +exports.checkVersion = checkVersion |
| 18 | +/** |
| 19 | + * @param {Express.Application|Express.Request} ctx |
| 20 | + */ |
| 21 | +async function checkVersion (ctx) { |
| 22 | + if (lastCheckAt && (lastCheckAt + CHECK_TIMEOUT > Date.now())) { |
| 23 | + return |
| 24 | + } |
| 25 | + |
| 26 | + // update lastCheckAt whether the check would fail or not |
| 27 | + lastCheckAt = Date.now() |
| 28 | + |
| 29 | + try { |
| 30 | + const { statusCode, body: data } = await rp({ |
| 31 | + url: `${VERSION_CHECK_ENDPOINT}?v=${config.version}`, |
| 32 | + method: 'GET', |
| 33 | + json: true |
| 34 | + }) |
| 35 | + |
| 36 | + if (statusCode !== 200 || data.status === 'error') { |
| 37 | + logger.error('Version check failed.') |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + const locals = ctx.locals ? ctx.locals : ctx.app.locals |
| 42 | + |
| 43 | + locals.versionInfo.latest = data.latest |
| 44 | + locals.versionInfo.versionItem = data.latest ? null : data.versionItem |
| 45 | + |
| 46 | + if (!data.latest) { |
| 47 | + const { version, link } = data.versionItem |
| 48 | + |
| 49 | + logger.warn(`Your CodiMD version is out of date! The latest version is ${version}. Please see what's new on ${link}.`) |
| 50 | + } |
| 51 | + } catch (err) { |
| 52 | + // ignore and skip version check |
| 53 | + logger.error('Version check failed.') |
| 54 | + logger.error(err) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +exports.versionCheckMiddleware = function (req, res, next) { |
| 59 | + checkVersion(req) |
| 60 | + .then(() => { |
| 61 | + next() |
| 62 | + }) |
| 63 | + .catch((err) => { |
| 64 | + logger.error(err) |
| 65 | + next() |
| 66 | + }) |
| 67 | +} |
0 commit comments