summaryrefslogtreecommitdiff
path: root/lib/web/note
diff options
context:
space:
mode:
Diffstat (limited to 'lib/web/note')
-rw-r--r--lib/web/note/actions.js122
-rw-r--r--lib/web/note/controller.js147
-rw-r--r--lib/web/note/router.js30
-rw-r--r--lib/web/note/slide.js45
-rw-r--r--lib/web/note/util.js109
5 files changed, 453 insertions, 0 deletions
diff --git a/lib/web/note/actions.js b/lib/web/note/actions.js
new file mode 100644
index 00000000..9ff7fedb
--- /dev/null
+++ b/lib/web/note/actions.js
@@ -0,0 +1,122 @@
+const models = require('../../models')
+const logger = require('../../logger')
+const config = require('../../config')
+const errors = require('../../errors')
+const fs = require('fs')
+const shortId = require('shortid')
+const markdownpdf = require('markdown-pdf')
+const moment = require('moment')
+const querystring = require('querystring')
+
+exports.getInfo = function getInfo (req, res, note) {
+ const body = note.content
+ const extracted = models.Note.extractMeta(body)
+ const markdown = extracted.markdown
+ const meta = models.Note.parseMeta(extracted.meta)
+ const createtime = note.createdAt
+ const updatetime = note.lastchangeAt
+ const title = models.Note.decodeTitle(note.title)
+ const data = {
+ title: meta.title || title,
+ description: meta.description || (markdown ? models.Note.generateDescription(markdown) : null),
+ viewcount: note.viewcount,
+ createtime: createtime,
+ updatetime: updatetime
+ }
+ res.set({
+ 'Access-Control-Allow-Origin': '*', // allow CORS as API
+ 'Access-Control-Allow-Headers': 'Range',
+ 'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
+ 'Cache-Control': 'private', // only cache by client
+ 'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
+ })
+ res.send(data)
+}
+
+exports.createPDF = function createPDF (req, res, note) {
+ const url = config.serverURL || 'http://' + req.get('host')
+ const body = note.content
+ const extracted = models.Note.extractMeta(body)
+ let content = extracted.markdown
+ const title = models.Note.decodeTitle(note.title)
+
+ if (!fs.existsSync(config.tmpPath)) {
+ fs.mkdirSync(config.tmpPath)
+ }
+ const path = config.tmpPath + '/' + Date.now() + '.pdf'
+ content = content.replace(/\]\(\//g, '](' + url + '/')
+ markdownpdf().from.string(content).to(path, function () {
+ if (!fs.existsSync(path)) {
+ logger.error('PDF seems to not be generated as expected. File doesn\'t exist: ' + path)
+ return errors.errorInternalError(res)
+ }
+ const stream = fs.createReadStream(path)
+ let filename = title
+ // Be careful of special characters
+ filename = encodeURIComponent(filename)
+ // Ideally this should strip them
+ res.setHeader('Content-disposition', 'attachment; filename="' + filename + '.pdf"')
+ res.setHeader('Cache-Control', 'private')
+ res.setHeader('Content-Type', 'application/pdf; charset=UTF-8')
+ res.setHeader('X-Robots-Tag', 'noindex, nofollow') // prevent crawling
+ stream.pipe(res)
+ fs.unlinkSync(path)
+ })
+}
+
+exports.createGist = function createGist (req, res, note) {
+ const data = {
+ client_id: config.github.clientID,
+ redirect_uri: config.serverURL + '/auth/github/callback/' + models.Note.encodeNoteId(note.id) + '/gist',
+ scope: 'gist',
+ state: shortId.generate()
+ }
+ const query = querystring.stringify(data)
+ res.redirect('https://github.com/login/oauth/authorize?' + query)
+}
+
+exports.getRevision = function getRevision (req, res, note) {
+ const actionId = req.params.actionId
+ if (actionId) {
+ const time = moment(parseInt(actionId))
+ if (time.isValid()) {
+ models.Revision.getPatchedNoteRevisionByTime(note, time, function (err, content) {
+ if (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ }
+ if (!content) {
+ return errors.errorNotFound(res)
+ }
+ res.set({
+ 'Access-Control-Allow-Origin': '*', // allow CORS as API
+ 'Access-Control-Allow-Headers': 'Range',
+ 'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
+ 'Cache-Control': 'private', // only cache by client
+ 'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
+ })
+ res.send(content)
+ })
+ } else {
+ return errors.errorNotFound(res)
+ }
+ } else {
+ models.Revision.getNoteRevisions(note, function (err, data) {
+ if (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ }
+ const out = {
+ revision: data
+ }
+ res.set({
+ 'Access-Control-Allow-Origin': '*', // allow CORS as API
+ 'Access-Control-Allow-Headers': 'Range',
+ 'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
+ 'Cache-Control': 'private', // only cache by client
+ 'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
+ })
+ res.send(out)
+ })
+ }
+}
diff --git a/lib/web/note/controller.js b/lib/web/note/controller.js
new file mode 100644
index 00000000..e537fe08
--- /dev/null
+++ b/lib/web/note/controller.js
@@ -0,0 +1,147 @@
+'use strict'
+
+const models = require('../../models')
+const logger = require('../../logger')
+const config = require('../../config')
+const errors = require('../../errors')
+
+const noteUtil = require('./util')
+const noteActions = require('./actions')
+
+exports.publishNoteActions = function (req, res, next) {
+ noteUtil.findNote(req, res, function (note) {
+ const action = req.params.action
+ switch (action) {
+ case 'download':
+ exports.downloadMarkdown(req, res, note)
+ break
+ case 'edit':
+ res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(note.id)) + '?both')
+ break
+ default:
+ res.redirect(config.serverURL + '/s/' + note.shortid)
+ break
+ }
+ })
+}
+
+exports.showPublishNote = function (req, res, next) {
+ const include = [{
+ model: models.User,
+ as: 'owner'
+ }, {
+ model: models.User,
+ as: 'lastchangeuser'
+ }]
+ noteUtil.findNote(req, res, function (note) {
+ // force to use short id
+ const shortid = req.params.shortid
+ if ((note.alias && shortid !== note.alias) || (!note.alias && shortid !== note.shortid)) {
+ return res.redirect(config.serverURL + '/s/' + (note.alias || note.shortid))
+ }
+ note.increment('viewcount').then(function (note) {
+ if (!note) {
+ return errors.errorNotFound(res)
+ }
+ noteUtil.getPublishData(req, res, note, (data) => {
+ res.set({
+ 'Cache-Control': 'private' // only cache by client
+ })
+ return res.render('pretty.ejs', data)
+ })
+ }).catch(function (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ })
+ }, include)
+}
+
+exports.showNote = function (req, res, next) {
+ noteUtil.findNote(req, res, function (note) {
+ // force to use note id
+ const noteId = req.params.noteId
+ const id = models.Note.encodeNoteId(note.id)
+ if ((note.alias && noteId !== note.alias) || (!note.alias && noteId !== id)) {
+ return res.redirect(config.serverURL + '/' + (note.alias || id))
+ }
+ const body = note.content
+ const extracted = models.Note.extractMeta(body)
+ const meta = models.Note.parseMeta(extracted.meta)
+ let title = models.Note.decodeTitle(note.title)
+ title = models.Note.generateWebTitle(meta.title || title)
+ const opengraph = models.Note.parseOpengraph(meta, title)
+ res.set({
+ 'Cache-Control': 'private', // only cache by client
+ 'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
+ })
+ return res.render('codimd.ejs', {
+ title: title,
+ opengraph: opengraph
+ })
+ })
+}
+
+exports.createFromPOST = function (req, res, next) {
+ let body = ''
+ if (req.body && req.body.length > config.documentMaxLength) {
+ return errors.errorTooLong(res)
+ } else if (req.body) {
+ body = req.body
+ }
+ body = body.replace(/[\r]/g, '')
+ return noteUtil.newNote(req, res, body)
+}
+
+exports.doAction = function (req, res, next) {
+ const noteId = req.params.noteId
+ noteUtil.findNote(req, res, function (note) {
+ const action = req.params.action
+ switch (action) {
+ case 'publish':
+ case 'pretty': // pretty deprecated
+ res.redirect(config.serverURL + '/s/' + (note.alias || note.shortid))
+ break
+ case 'slide':
+ res.redirect(config.serverURL + '/p/' + (note.alias || note.shortid))
+ break
+ case 'download':
+ exports.downloadMarkdown(req, res, note)
+ break
+ case 'info':
+ noteActions.getInfo(req, res, note)
+ break
+ case 'pdf':
+ if (config.allowPDFExport) {
+ noteActions.createPDF(req, res, note)
+ } else {
+ logger.error('PDF export failed: Disabled by config. Set "allowPDFExport: true" to enable. Check the documentation for details')
+ errors.errorForbidden(res)
+ }
+ break
+ case 'gist':
+ noteActions.createGist(req, res, note)
+ break
+ case 'revision':
+ noteActions.getRevision(req, res, note)
+ break
+ default:
+ return res.redirect(config.serverURL + '/' + noteId)
+ }
+ })
+}
+
+exports.downloadMarkdown = function (req, res, note) {
+ const body = note.content
+ let filename = models.Note.decodeTitle(note.title)
+ filename = encodeURIComponent(filename)
+ res.set({
+ 'Access-Control-Allow-Origin': '*', // allow CORS as API
+ 'Access-Control-Allow-Headers': 'Range',
+ 'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
+ 'Content-Type': 'text/markdown; charset=UTF-8',
+ 'Cache-Control': 'private',
+ 'Content-disposition': 'attachment; filename=' + filename + '.md',
+ 'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
+ })
+ res.send(body)
+}
diff --git a/lib/web/note/router.js b/lib/web/note/router.js
new file mode 100644
index 00000000..cf6fdf43
--- /dev/null
+++ b/lib/web/note/router.js
@@ -0,0 +1,30 @@
+'use strict'
+
+const Router = require('express').Router
+const { markdownParser } = require('../utils')
+
+const router = module.exports = Router()
+
+const noteController = require('./controller')
+const slide = require('./slide')
+
+// get new note
+router.get('/new', noteController.createFromPOST)
+// post new note with content
+router.post('/new', markdownParser, noteController.createFromPOST)
+// post new note with content and alias
+router.post('/new/:noteId', markdownParser, noteController.createFromPOST)
+// get publish note
+router.get('/s/:shortid', noteController.showPublishNote)
+// publish note actions
+router.get('/s/:shortid/:action', noteController.publishNoteActions)
+// get publish slide
+router.get('/p/:shortid', slide.showPublishSlide)
+// publish slide actions
+router.get('/p/:shortid/:action', slide.publishSlideActions)
+// get note by id
+router.get('/:noteId', noteController.showNote)
+// note actions
+router.get('/:noteId/:action', noteController.doAction)
+// note actions with action id
+router.get('/:noteId/:action/:actionId', noteController.doAction)
diff --git a/lib/web/note/slide.js b/lib/web/note/slide.js
new file mode 100644
index 00000000..d2d2ccfc
--- /dev/null
+++ b/lib/web/note/slide.js
@@ -0,0 +1,45 @@
+const noteUtil = require('./util')
+const models = require('../../models')
+const errors = require('../../errors')
+const logger = require('../../logger')
+const config = require('../../config')
+
+exports.publishSlideActions = function (req, res, next) {
+ noteUtil.findNote(req, res, function (note) {
+ const action = req.params.action
+ if (action === 'edit') {
+ res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(note.id)) + '?both')
+ } else { res.redirect(config.serverURL + '/p/' + note.shortid) }
+ })
+}
+
+exports.showPublishSlide = function (req, res, next) {
+ const include = [{
+ model: models.User,
+ as: 'owner'
+ }, {
+ model: models.User,
+ as: 'lastchangeuser'
+ }]
+ noteUtil.findNote(req, res, function (note) {
+ // force to use short id
+ const shortid = req.params.shortid
+ if ((note.alias && shortid !== note.alias) || (!note.alias && shortid !== note.shortid)) {
+ return res.redirect(config.serverURL + '/p/' + (note.alias || note.shortid))
+ }
+ note.increment('viewcount').then(function (note) {
+ if (!note) {
+ return errors.errorNotFound(res)
+ }
+ noteUtil.getPublishData(req, res, note, (data) => {
+ res.set({
+ 'Cache-Control': 'private' // only cache by client
+ })
+ return res.render('slide.ejs', data)
+ })
+ }).catch(function (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ })
+ }, include)
+}
diff --git a/lib/web/note/util.js b/lib/web/note/util.js
new file mode 100644
index 00000000..eadfb1a3
--- /dev/null
+++ b/lib/web/note/util.js
@@ -0,0 +1,109 @@
+const models = require('../../models')
+const logger = require('../../logger')
+const config = require('../../config')
+const errors = require('../../errors')
+const fs = require('fs')
+const path = require('path')
+
+exports.findNote = function (req, res, callback, include) {
+ const id = req.params.noteId || req.params.shortid
+ models.Note.parseNoteId(id, function (err, _id) {
+ if (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ }
+ models.Note.findOne({
+ where: {
+ id: _id
+ },
+ include: include || null
+ }).then(function (note) {
+ if (!note) {
+ return exports.newNote(req, res, null)
+ }
+ if (!exports.checkViewPermission(req, note)) {
+ return errors.errorForbidden(res)
+ } else {
+ return callback(note)
+ }
+ }).catch(function (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ })
+ })
+}
+
+exports.checkViewPermission = function (req, note) {
+ if (note.permission === 'private') {
+ return !(!req.isAuthenticated() || note.ownerId !== req.user.id)
+ } else if (note.permission === 'limited' || note.permission === 'protected') {
+ return req.isAuthenticated()
+ } else {
+ return true
+ }
+}
+
+exports.newNote = function (req, res, body) {
+ let owner = null
+ const noteId = req.params.noteId ? req.params.noteId : null
+ if (req.isAuthenticated()) {
+ owner = req.user.id
+ } else if (!config.allowAnonymous) {
+ return errors.errorForbidden(res)
+ }
+ if (config.allowFreeURL && noteId && !config.forbiddenNoteIDs.includes(noteId)) {
+ req.alias = noteId
+ } else if (noteId) {
+ return req.method === 'POST' ? errors.errorForbidden(res) : errors.errorNotFound(res)
+ }
+ models.Note.create({
+ ownerId: owner,
+ alias: req.alias ? req.alias : null,
+ content: body
+ }).then(function (note) {
+ return res.redirect(config.serverURL + '/' + (note.alias ? note.alias : models.Note.encodeNoteId(note.id)))
+ }).catch(function (err) {
+ logger.error(err)
+ return errors.errorInternalError(res)
+ })
+}
+
+exports.getPublishData = function (req, res, note, callback) {
+ const body = note.content
+ const extracted = models.Note.extractMeta(body)
+ const markdown = extracted.markdown
+ const meta = models.Note.parseMeta(extracted.meta)
+ const createtime = note.createdAt
+ const updatetime = note.lastchangeAt
+ let title = models.Note.decodeTitle(note.title)
+ title = models.Note.generateWebTitle(meta.title || title)
+ const ogdata = models.Note.parseOpengraph(meta, title)
+ const data = {
+ title: title,
+ description: meta.description || (markdown ? models.Note.generateDescription(markdown) : null),
+ viewcount: note.viewcount,
+ createtime: createtime,
+ updatetime: updatetime,
+ body: markdown,
+ theme: meta.slideOptions && isRevealTheme(meta.slideOptions.theme),
+ meta: JSON.stringify(extracted.meta),
+ owner: note.owner ? note.owner.id : null,
+ ownerprofile: note.owner ? models.User.getProfile(note.owner) : null,
+ lastchangeuser: note.lastchangeuser ? note.lastchangeuser.id : null,
+ lastchangeuserprofile: note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null,
+ robots: meta.robots || false, // default allow robots
+ GA: meta.GA,
+ disqus: meta.disqus,
+ cspNonce: res.locals.nonce,
+ dnt: req.headers.dnt,
+ opengraph: ogdata
+ }
+ callback(data)
+}
+
+function isRevealTheme (theme) {
+ if (fs.existsSync(path.join(__dirname, '..', 'public', 'build', 'reveal.js', 'css', 'theme', theme + '.css'))) {
+ return theme
+ }
+ return undefined
+}