Skip to content

Commit 82cade2

Browse files
committed
refactor: noteActions
Signed-off-by: BoHong Li <[email protected]>
1 parent 7f99704 commit 82cade2

File tree

4 files changed

+210
-4
lines changed

4 files changed

+210
-4
lines changed

lib/note/index.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
'use strict'
22

33
const config = require('../config')
4+
const logger = require('../logger')
5+
46
const { Note, User } = require('../models')
57

68
const { newCheckViewPermission, errorForbidden, responseCodiMD, errorNotFound } = require('../response')
79
const { updateHistory } = require('../history')
10+
const { actionPublish, actionSlide, actionInfo, actionDownload, actionPDF, actionGist, actionRevision } = require('./noteActions')
811

912
async function getNoteById (noteId, { includeUser } = { includeUser: false }) {
1013
const id = await Note.parseNoteIdAsync(noteId)
@@ -123,5 +126,46 @@ async function showPublishNote (req, res) {
123126
res.render('pretty.ejs', data)
124127
}
125128

129+
async function noteActions (req, res) {
130+
const noteId = req.params.noteId
131+
132+
const note = await getNoteById(noteId)
133+
if (!note) {
134+
return errorNotFound(res)
135+
}
136+
137+
const action = req.params.action
138+
switch (action) {
139+
case 'publish':
140+
case 'pretty': // pretty deprecated
141+
return actionPublish(req, res, note)
142+
case 'slide':
143+
return actionSlide(req, res, note)
144+
case 'download':
145+
actionDownload(req, res, note)
146+
break
147+
case 'info':
148+
actionInfo(req, res, note)
149+
break
150+
case 'pdf':
151+
if (config.allowPDFExport) {
152+
actionPDF(req, res, note)
153+
} else {
154+
logger.error('PDF export failed: Disabled by config. Set "allowPDFExport: true" to enable. Check the documentation for details')
155+
errorForbidden(res)
156+
}
157+
break
158+
case 'gist':
159+
actionGist(req, res, note)
160+
break
161+
case 'revision':
162+
actionRevision(req, res, note)
163+
break
164+
default:
165+
return res.redirect(config.serverURL + '/' + noteId)
166+
}
167+
}
168+
126169
exports.showNote = showNote
127170
exports.showPublishNote = showPublishNote
171+
exports.noteActions = noteActions

lib/note/noteActions.js

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
'use strict'
2+
3+
const fs = require('fs')
4+
const path = require('path')
5+
const markdownpdf = require('markdown-pdf')
6+
const shortId = require('shortid')
7+
const querystring = require('querystring')
8+
const moment = require('moment')
9+
10+
const config = require('../config')
11+
const logger = require('../logger')
12+
const { Note, Revision } = require('../models')
13+
const { errorInternalError, errorNotFound } = require('../response')
14+
15+
function actionPublish (req, res, note) {
16+
res.redirect(config.serverURL + '/s/' + (note.alias || note.shortid))
17+
}
18+
19+
function actionSlide (req, res, note) {
20+
res.redirect(config.serverURL + '/p/' + (note.alias || note.shortid))
21+
}
22+
23+
function actionDownload (req, res, note) {
24+
const body = note.content
25+
const title = Note.decodeTitle(note.title)
26+
const filename = encodeURIComponent(title)
27+
res.set({
28+
'Access-Control-Allow-Origin': '*', // allow CORS as API
29+
'Access-Control-Allow-Headers': 'Range',
30+
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
31+
'Content-Type': 'text/markdown; charset=UTF-8',
32+
'Cache-Control': 'private',
33+
'Content-disposition': 'attachment; filename=' + filename + '.md',
34+
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
35+
})
36+
res.send(body)
37+
}
38+
39+
function actionInfo (req, res, note) {
40+
const body = note.content
41+
const extracted = Note.extractMeta(body)
42+
const markdown = extracted.markdown
43+
const meta = Note.parseMeta(extracted.meta)
44+
const createtime = note.createdAt
45+
const updatetime = note.lastchangeAt
46+
const title = Note.decodeTitle(note.title)
47+
48+
const data = {
49+
title: meta.title || title,
50+
description: meta.description || (markdown ? Note.generateDescription(markdown) : null),
51+
viewcount: note.viewcount,
52+
createtime: createtime,
53+
updatetime: updatetime
54+
}
55+
56+
res.set({
57+
'Access-Control-Allow-Origin': '*', // allow CORS as API
58+
'Access-Control-Allow-Headers': 'Range',
59+
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
60+
'Cache-Control': 'private', // only cache by client
61+
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
62+
})
63+
res.send(data)
64+
}
65+
66+
function actionPDF (req, res, note) {
67+
const url = config.serverURL || 'http://' + req.get('host')
68+
const body = note.content
69+
const extracted = Note.extractMeta(body)
70+
let content = extracted.markdown
71+
const title = Note.decodeTitle(note.title)
72+
73+
const highlightCssPath = path.join(config.appRootPath, '/node_modules/highlight.js/styles/github-gist.css')
74+
75+
if (!fs.existsSync(config.tmpPath)) {
76+
fs.mkdirSync(config.tmpPath)
77+
}
78+
const pdfPath = config.tmpPath + '/' + Date.now() + '.pdf'
79+
content = content.replace(/\]\(\//g, '](' + url + '/')
80+
const markdownpdfOptions = {
81+
highlightCssPath: highlightCssPath
82+
}
83+
markdownpdf(markdownpdfOptions).from.string(content).to(pdfPath, function () {
84+
if (!fs.existsSync(pdfPath)) {
85+
logger.error('PDF seems to not be generated as expected. File doesn\'t exist: ' + pdfPath)
86+
return errorInternalError(res)
87+
}
88+
const stream = fs.createReadStream(pdfPath)
89+
let filename = title
90+
// Be careful of special characters
91+
filename = encodeURIComponent(filename)
92+
// Ideally this should strip them
93+
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '.pdf"')
94+
res.setHeader('Cache-Control', 'private')
95+
res.setHeader('Content-Type', 'application/pdf; charset=UTF-8')
96+
res.setHeader('X-Robots-Tag', 'noindex, nofollow') // prevent crawling
97+
stream.pipe(res)
98+
fs.unlinkSync(pdfPath)
99+
})
100+
}
101+
102+
function actionGist (req, res, note) {
103+
const data = {
104+
client_id: config.github.clientID,
105+
redirect_uri: config.serverURL + '/auth/github/callback/' + Note.encodeNoteId(note.id) + '/gist',
106+
scope: 'gist',
107+
state: shortId.generate()
108+
}
109+
const query = querystring.stringify(data)
110+
res.redirect('https://github.com/login/oauth/authorize?' + query)
111+
}
112+
113+
function actionRevision (req, res, note) {
114+
const actionId = req.params.actionId
115+
if (actionId) {
116+
const time = moment(parseInt(actionId))
117+
if (!time.isValid()) {
118+
return errorNotFound(res)
119+
}
120+
Revision.getPatchedNoteRevisionByTime(note, time, function (err, content) {
121+
if (err) {
122+
logger.error(err)
123+
return errorInternalError(res)
124+
}
125+
if (!content) {
126+
return errorNotFound(res)
127+
}
128+
res.set({
129+
'Access-Control-Allow-Origin': '*', // allow CORS as API
130+
'Access-Control-Allow-Headers': 'Range',
131+
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
132+
'Cache-Control': 'private', // only cache by client
133+
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
134+
})
135+
res.send(content)
136+
})
137+
} else {
138+
Revision.getNoteRevisions(note, function (err, data) {
139+
if (err) {
140+
logger.error(err)
141+
return errorInternalError(res)
142+
}
143+
const result = {
144+
revision: data
145+
}
146+
res.set({
147+
'Access-Control-Allow-Origin': '*', // allow CORS as API
148+
'Access-Control-Allow-Headers': 'Range',
149+
'Access-Control-Expose-Headers': 'Cache-Control, Content-Encoding, Content-Range',
150+
'Cache-Control': 'private', // only cache by client
151+
'X-Robots-Tag': 'noindex, nofollow' // prevent crawling
152+
})
153+
res.send(result)
154+
})
155+
}
156+
}
157+
158+
exports.actionPublish = actionPublish
159+
exports.actionSlide = actionSlide
160+
exports.actionDownload = actionDownload
161+
exports.actionInfo = actionInfo
162+
exports.actionPDF = actionPDF
163+
exports.actionGist = actionGist
164+
exports.actionRevision = actionRevision

lib/response.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,6 @@ exports.errorInternalError = errorInternalError
2626
exports.errorServiceUnavailable = errorServiceUnavailable
2727
exports.newNote = newNote
2828
exports.showPublishSlide = showPublishSlide
29-
exports.showIndex = showIndex
30-
exports.noteActions = noteActions
3129
exports.publishNoteActions = publishNoteActions
3230
exports.publishSlideActions = publishSlideActions
3331
exports.githubActions = githubActions

lib/routes.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@ appRouter.get('/p/:shortid/:action', response.publishSlideActions)
7474
// get note by id
7575
appRouter.get('/:noteId', wrap(noteController.showNote))
7676
// note actions
77-
appRouter.get('/:noteId/:action', response.noteActions)
77+
appRouter.get('/:noteId/:action', noteController.noteActions)
7878
// note actions with action id
79-
appRouter.get('/:noteId/:action/:actionId', response.noteActions)
79+
appRouter.get('/:noteId/:action/:actionId', noteController.noteActions)
8080

8181
exports.router = appRouter

0 commit comments

Comments
 (0)