diff --git a/helpers/markdown.js b/helpers/markdown.js index ad436888..7a3d5f43 100644 --- a/helpers/markdown.js +++ b/helpers/markdown.js @@ -1,7 +1,6 @@ 'use strict'; const Posts = require(__dirname+'/../db-models/posts.js') - , quoteRegex = /^>>\d+/gm , greentextRegex = /^>[^>].+/gm , redtextRegex = /^<[^<].+/gm , boldRegex = /==.+==/gm @@ -28,12 +27,6 @@ module.exports = (board, thread, text) => { return `${match}`; }); - //quotes - text = text.replace(quoteRegex, (match) => { - const quotenum = match.substring(2); - return `>>${quotenum}`; - }); - //bold text = text.replace(boldRegex, (match) => { const bold = match.substring(2, match.length-2); diff --git a/helpers/quotes.js b/helpers/quotes.js new file mode 100644 index 00000000..0d022ddf --- /dev/null +++ b/helpers/quotes.js @@ -0,0 +1,46 @@ +'use strict'; + +const Posts = require(__dirname+'/../db-models/posts.js') + , quoteRegex = /^>>\d+/gm; + +module.exports = async (board, text) => { + + //get the matches + const matches = text.match(quoteRegex); + if (!matches) { + return text; + } + + //get all the Ids + const quoteIds = matches.map(x => +x.substring(2)); + + //get all posts with those Ids + const posts = await Posts.getPosts(board, quoteIds, false); + + //turn the result into a map of postId => threadId/postId + const postThreadObject = {}; + let validQuotes = 0; + for (let i = 0; i < posts.length; i++) { + const post = posts[i]; + postThreadObject[post.postId] = post.thread || post.postId; + validQuotes++; + } + + console.log(validQuotes); + //if none of the quotes were real, dont do a replace + if (validQuotes === 0) { + return text; + } + + //then replace the quotes with only ones that exist + text = text.replace(quoteRegex, (match) => { + const quotenum = +match.substring(2); + if (postThreadObject[quotenum]) { + return `>>${quotenum}`; + } + return match; + }); + + return text; + +} diff --git a/models/forms/make-post.js b/models/forms/make-post.js index 359399a0..10cf8950 100644 --- a/models/forms/make-post.js +++ b/models/forms/make-post.js @@ -8,6 +8,7 @@ const uuidv4 = require('uuid/v4') , uploadDirectory = require(__dirname+'/../../helpers/uploadDirectory.js') , Posts = require(__dirname+'/../../db-models/posts.js') , getTripCode = require(__dirname+'/../../helpers/tripcode.js') + , getQuotes = require(__dirname+'/../../helpers/quotes.js') , simpleMarkdown = require(__dirname+'/../../helpers/markdown.js') , sanitize = require('sanitize-html') , sanitizeOptions = { @@ -147,7 +148,9 @@ module.exports = async (req, res, next, numFiles) => { //simple markdown and sanitize let message = req.body.message; if (message && message.length > 0) { - message = sanitize(simpleMarkdown(req.params.board, req.body.thread, message), sanitizeOptions); + message = simpleMarkdown(req.params.board, req.body.thread, message); + message = await getQuotes(req.params.board, message); + message = sanitize(message, sanitizeOptions); } //add post to DB