2019-12-26 08:56:31 +00:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const { promisify } = require('util')
|
|
|
|
|
|
|
|
const request = require('request')
|
|
|
|
|
|
|
|
const logger = require('../../logger')
|
|
|
|
const config = require('../../config')
|
|
|
|
|
|
|
|
let lastCheckAt
|
|
|
|
|
|
|
|
const VERSION_CHECK_ENDPOINT = 'https://evangelion.codimd.dev/'
|
|
|
|
const CHECK_TIMEOUT = 1000 * 60 * 60 * 24 // 1 day
|
|
|
|
|
|
|
|
const rp = promisify(request)
|
|
|
|
|
2020-02-06 02:40:51 +00:00
|
|
|
exports.checkVersion = checkVersion
|
|
|
|
/**
|
|
|
|
* @param {Express.Application|Express.Request} ctx
|
|
|
|
*/
|
|
|
|
async function checkVersion (ctx) {
|
2019-12-26 08:56:31 +00:00
|
|
|
if (lastCheckAt && (lastCheckAt + CHECK_TIMEOUT > Date.now())) {
|
2020-02-06 02:40:51 +00:00
|
|
|
return
|
2019-12-26 08:56:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// update lastCheckAt whether the check would fail or not
|
|
|
|
lastCheckAt = Date.now()
|
|
|
|
|
|
|
|
try {
|
|
|
|
const { statusCode, body: data } = await rp({
|
|
|
|
url: `${VERSION_CHECK_ENDPOINT}?v=${config.version}`,
|
|
|
|
method: 'GET',
|
|
|
|
json: true
|
|
|
|
})
|
|
|
|
|
|
|
|
if (statusCode !== 200 || data.status === 'error') {
|
|
|
|
logger.error('Version check failed.')
|
2020-02-06 02:40:51 +00:00
|
|
|
return
|
2019-12-26 08:56:31 +00:00
|
|
|
}
|
|
|
|
|
2020-02-06 02:46:48 +00:00
|
|
|
const locals = ctx.locals ? ctx.locals : ctx.app.locals
|
2019-12-26 08:56:31 +00:00
|
|
|
|
2020-02-06 02:40:51 +00:00
|
|
|
locals.versionInfo.latest = data.latest
|
|
|
|
locals.versionInfo.versionItem = data.latest ? null : data.versionItem
|
|
|
|
|
|
|
|
if (!data.latest) {
|
|
|
|
const { version, link } = data.versionItem
|
|
|
|
|
|
|
|
logger.warn(`Your CodiMD version is out of date! The latest version is ${version}. Please see what's new on ${link}.`)
|
|
|
|
}
|
2019-12-26 08:56:31 +00:00
|
|
|
} catch (err) {
|
|
|
|
// ignore and skip version check
|
|
|
|
logger.error('Version check failed.')
|
|
|
|
logger.error(err)
|
|
|
|
}
|
|
|
|
}
|
2020-02-06 02:40:51 +00:00
|
|
|
|
|
|
|
exports.versionCheckMiddleware = function (req, res, next) {
|
|
|
|
checkVersion(req)
|
|
|
|
.then(() => {
|
|
|
|
next()
|
|
|
|
})
|
|
|
|
.catch((err) => {
|
2020-02-06 02:46:48 +00:00
|
|
|
logger.error(err)
|
2020-02-06 02:40:51 +00:00
|
|
|
next()
|
|
|
|
})
|
|
|
|
}
|