srd/plugins/srd-router/route.js

79 lines
2.8 KiB
JavaScript

const router = require('express').Router()
const mcache = require('memory-cache')
const md = require('markdown-it')({ typographer: true })
md.use(require('markdown-it-anchor'), {permalink: true, level: 2, permalinkBefore: true, permalinkSymbol: "§"})
md.use(require('markdown-it-title'), 0)
const fs = require('fs')
const path = require('path')
module.exports = (plugin, app) => {
const cache = function(duration) {
return function(req, res, next) {
let key = '__'+app.live.conf['shortname']+'__' + req.originalUrl || req.url
let cached = mcache.get(key)
if (cached) {
res.send(cached)
return
} else {
res.sendResponse = res.send
res.send = function(body) {
mcache.put(key, body, duration * 60 * 1000 )
res.sendResponse(body)
}
next()
}
}
}
router.get('*', cache(1), function(req, res) {
let target = req.path
if (target === "/") { // Root
target = '/index'
} else if (target.charAt(target.length-1) == '/') { // Directory Index
target = target.substring(0, target.length-1)
}
let file = path.join(app.config.srd, target+'.md')
let crumbs = target.split('/')
fs.readFile(file, (err, data) => {
if (err) {
res.render('index', {content: '404', menu: app.live.menu, location: '404', title: '404', www_name: app.live.conf.www_name, www_copyright: app.live.conf.www_copyright })
return
//throw err
}
// make a local copy of our dictionary and remove the current page, if existing
let local_dictionary = Object.assign({}, app.dictionary)
delete local_dictionary[crumbs[crumbs.length-1]]
let text
if (Object.keys(local_dictionary).length !== 0) {
// replace words using our local dictionary
let regexp = RegExp ('[^\[(]\\b(' + Object.keys (local_dictionary).join ('|') + ')\\b', 'g')
text = data.toString().replace(regexp, function (_, word) { return _.charAt(0)+local_dictionary[word] })
} else {
text = data.toString()
}
// render out the md
let env = {}
let rendered = md.render(text, env)
// build the location
let loc = '<a href="/">'+app.live.conf['shortname']+'</a>'
for (let i = 1; i < crumbs.length; i++) {
if (crumbs[i] == '') continue
loc += ' &#8594 <a href="'+crumbs.slice(0,i).join('/')+'/'+crumbs[i]+'">'+(i == crumbs.length-1 ? env.title : crumbs[i].replace('-', ' '))+'</a>'
}
let title = env.title
// render with the engine
res.render('index', {content: rendered, menu: app.live.menu, location: loc, title: (title != 'index' ? title : ''), www_name: app.live.conf.www_name, www_copyright: app.live.conf.www_copyright })
})
})
return router
}