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',
|
2020-03-16 17:24:38 +00:00
|
|
|
json: true,
|
2020-03-16 18:23:25 +00:00
|
|
|
timeout: 3000
|
2019-12-26 08:56:31 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
if (statusCode !== 200 || data.status === 'error') {
|
2020-03-16 17:24:38 +00:00
|
|
|
logger.warn('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
|
|
|
|
|
2020-03-16 17:24:38 +00:00
|
|
|
logger.info(`Your CodiMD version is out of date! The latest version is ${version}. Please see what's new on ${link}.`)
|
2020-02-06 02:40:51 +00:00
|
|
|
}
|
2019-12-26 08:56:31 +00:00
|
|
|
} catch (err) {
|
|
|
|
// ignore and skip version check
|
2020-03-16 17:24:38 +00:00
|
|
|
logger.warn('Version check failed.')
|
|
|
|
logger.warn(err)
|
2019-12-26 08:56:31 +00:00
|
|
|
}
|
|
|
|
}
|
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()
|
|
|
|
})
|
|
|
|
}
|