Files
NodeBB/src/posts/parse.js

78 lines
2.0 KiB
JavaScript
Raw Normal View History

'use strict';
2016-06-03 11:20:53 +03:00
var nconf = require('nconf');
var url = require('url');
var winston = require('winston');
2016-05-16 08:22:23 -04:00
2016-02-23 13:08:38 +02:00
var cache = require('./cache');
var plugins = require('../plugins');
2016-03-17 11:38:21 +02:00
var translator = require('../../public/src/modules/translator');
2016-05-16 08:22:23 -04:00
var urlRegex = /href="([^"]+)"/g;
module.exports = function(Posts) {
Posts.parsePost = function(postData, callback) {
postData.content = postData.content || '';
2015-11-26 23:34:55 -05:00
if (postData.pid && cache.has(postData.pid)) {
postData.content = cache.get(postData.pid);
return callback(null, postData);
}
// Casting post content into a string, just in case
if (typeof postData.content !== 'string') {
postData.content = postData.content.toString();
}
plugins.fireHook('filter:parse.post', {postData: postData}, function(err, data) {
if (err) {
return callback(err);
}
2015-11-16 16:51:19 -05:00
2016-03-17 11:38:21 +02:00
data.postData.content = translator.escape(data.postData.content);
2016-05-16 08:22:23 -04:00
data.postData.content = Posts.relativeToAbsolute(data.postData.content);
2016-03-17 11:38:21 +02:00
2015-11-25 12:30:43 -05:00
if (global.env === 'production' && data.postData.pid) {
2015-11-16 16:51:19 -05:00
cache.set(data.postData.pid, data.postData.content);
}
callback(null, data.postData);
});
};
Posts.parseSignature = function(userData, uid, callback) {
userData.signature = userData.signature || '';
plugins.fireHook('filter:parse.signature', {userData: userData, uid: uid}, callback);
};
2016-05-16 08:22:23 -04:00
Posts.relativeToAbsolute = function(content) {
// Turns relative links in post body to absolute urls
var parsed, current, absolute;
2016-06-03 11:20:53 +03:00
while ((current = urlRegex.exec(content)) !== null) {
2016-05-16 08:22:23 -04:00
if (current[1]) {
2016-06-03 11:20:53 +03:00
try {
parsed = url.parse(current[1]);
if (!parsed.protocol) {
if (current[1].startsWith('/')) {
// Internal link
absolute = nconf.get('url') + current[1];
} else {
// External link
absolute = '//' + current[1];
}
content = content.slice(0, current.index + 6) + absolute + content.slice(current.index + 6 + current[1].length);
2016-05-16 08:22:23 -04:00
}
2016-06-03 11:20:53 +03:00
} catch(err) {
winston.verbose(err.messsage);
}
2016-05-16 08:22:23 -04:00
}
}
return content;
};
2015-11-26 23:34:55 -05:00
};