2019-02-05 16:27:36 +00:00
|
|
|
const express = require('express')
|
|
|
|
const path = require('path')
|
|
|
|
const fs = require('fs')
|
|
|
|
const fsp = fs.promises
|
|
|
|
|
|
|
|
const router = express.Router()
|
|
|
|
const cfgLoader = require(path.join('..', '..', 'config-loader'))(path.join(__dirname, 'config.json'), {
|
|
|
|
root: path.join(process.cwd(), '..', 'fiche', 'code'),
|
2019-02-26 09:52:23 +00:00
|
|
|
style: 'tomorrow-night',
|
|
|
|
index: 'index.html'
|
2019-02-05 16:27:36 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
async function init () {
|
|
|
|
let config = await cfgLoader
|
|
|
|
let root = path.resolve(config.root)
|
|
|
|
|
|
|
|
await fsp.access(root, fs.constants.F_OK)
|
|
|
|
|
|
|
|
router.get('/:name', async (req, res, next) => {
|
|
|
|
let name = req.params.name
|
2019-02-05 16:47:08 +00:00
|
|
|
if (name.length > 5) {
|
2019-02-05 16:27:36 +00:00
|
|
|
try {
|
|
|
|
let text = await fsp.readFile(path.join(root, 'index.html'))
|
|
|
|
res.send(text)
|
|
|
|
} catch (e) {
|
|
|
|
res.status(403)
|
|
|
|
}
|
|
|
|
return res.end()
|
|
|
|
}
|
|
|
|
|
|
|
|
let fichePath = path.join(root, name, 'index.txt')
|
|
|
|
let reqRaw = req.query.raw != null
|
|
|
|
|
|
|
|
let text
|
|
|
|
try {
|
|
|
|
text = await fsp.readFile(fichePath, {encoding: 'utf8'})
|
|
|
|
} catch (e) {
|
|
|
|
return res.status(404).end()
|
|
|
|
}
|
|
|
|
|
2019-02-05 17:15:00 +00:00
|
|
|
res.header('Cache-Control', 'max-age=' + 7 * 24 * 60 * 60 * 1000)
|
|
|
|
|
2019-02-05 16:27:36 +00:00
|
|
|
if (reqRaw) {
|
|
|
|
return res.set('Content-Type', 'text/plain').send(text)
|
|
|
|
}
|
|
|
|
|
|
|
|
let etext = text.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
|
|
|
let payload =
|
|
|
|
'<?xml version="1.0" encoding="UTF-8"?>' +
|
|
|
|
'<html xmlns="http://www.w3.org/1999/xhtml" class="hljs">' +
|
|
|
|
'<head>' +
|
|
|
|
'<link rel="stylesheet" href="/assets/css/t.css" />' +
|
|
|
|
'<link rel="stylesheet" href="/assets/css/t-styles/' + config.style + '.css" />' +
|
|
|
|
'<script src="/assets/js/highlight.min.js"></script>' +
|
|
|
|
'</head>' +
|
|
|
|
'<body>' +
|
|
|
|
'<pre><code>' + etext + '</code></pre>' +
|
|
|
|
'<script>hljs.initHighlightingOnLoad();</script>' +
|
|
|
|
'</body>' +
|
|
|
|
'</html>'
|
|
|
|
|
|
|
|
res.set('Content-Type', 'application/xhtml+xml').send(payload)
|
|
|
|
})
|
|
|
|
|
2019-02-26 09:52:23 +00:00
|
|
|
router.get('/', (req, res, next) => {
|
|
|
|
if (!config.index) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2019-02-26 10:06:47 +00:00
|
|
|
let inp = config.index
|
|
|
|
if (inp.indexOf('/') !== 0) {
|
|
|
|
inp = path.join(__dirname, inp)
|
2019-02-26 09:52:23 +00:00
|
|
|
} else {
|
2019-02-26 10:06:47 +00:00
|
|
|
inp = path.resolve(inp)
|
2019-02-26 09:52:23 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 10:06:47 +00:00
|
|
|
res.sendFile(inp)
|
2019-02-26 09:52:23 +00:00
|
|
|
})
|
|
|
|
|
2019-02-05 16:27:36 +00:00
|
|
|
return router
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = init
|