Skip to content

Node.js based forum software built for the modern web

4.2 KB
Raw Blame

'use strict';

const validator = require('validator');
const _ = require('lodash');
const nconf = require('nconf');

const topics = require('../topics');
const user = require('../user');
const plugins = require('../plugins');
const categories = require('../categories');
const utils = require('../utils');

module.exports = function (Posts) {
	Posts.getPostSummaryByPids = async function (pids, uid, options) {
		if (!Array.isArray(pids) || !pids.length) {
			return [];
		}

		options.stripTags = options.hasOwnProperty('stripTags') ? options.stripTags : false;
		options.parse = options.hasOwnProperty('parse') ? options.parse : true;
		options.escape = options.hasOwnProperty('escape') ? options.escape : false;
		options.extraFields = options.hasOwnProperty('extraFields') ? options.extraFields : [];

		// `uploads` is selected so parsing can size images without a second lookup,
		// and is dropped again below to keep the summary payload unchanged
		const fields = ['pid', 'tid', 'toPid', 'url', 'content', 'sourceContent', 'uid', 'timestamp', 'deleted', 'upvotes', 'downvotes', 'replies', 'handle', 'uploads'].concat(options.extraFields);

		let posts = await Posts.getPostsFields(pids, fields);
		posts = posts.filter(Boolean);
		posts = await user.blocks.filter(uid, posts);

		const uids = _.uniq(posts.map(p => p && p.uid));
		const tids = _.uniq(posts.map(p => p && p.tid));

		const [users, topicsAndCategories] = await Promise.all([
			user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture', 'status', 'fullnameEmoji']),
			getTopicAndCategories(tids),
		]);

		const uidToUser = toObject('uid', users);
		const tidToTopic = toObject('tid', topicsAndCategories.topics);
		const cidToCategory = toObject('cid', topicsAndCategories.categories);

		posts.forEach((post) => {
			// If the post author isn't represented in the retrieved users' data,
			// then it means they were deleted, assume guest.
			if (!uidToUser.hasOwnProperty(post.uid)) {
				post.uid = 0;
			}

			// toPid is nullable so it is casted separately
			post.toPid = utils.isNumber(post.toPid) ? parseInt(post.toPid, 10) : post.toPid;

			post.user = uidToUser[post.uid];
			Posts.overrideGuestHandle(post, post.handle);
			post.handle = undefined;
			post.topic = tidToTopic[post.tid];
			post.category = post.topic && cidToCategory[post.topic.cid];
			post.isMainPost = post.topic && post.pid === post.topic.mainPid;
			post.deleted = post.deleted === 1;
			post.timestampISO = utils.toISOString(post.timestamp);

			// url only applies to remote posts; assume permalink otherwise
			if (utils.isNumber(post.pid)) {
				post.url = `${nconf.get('url')}/post/${post.pid}`;
			}
		});

		posts = posts.filter(post => tidToTopic[post.tid]);

		posts = await parsePosts(posts, options);
		if (!options.extraFields.includes('uploads')) {
			posts.forEach((post) => { post.uploads = undefined; });
		}
		const result = await plugins.hooks.fire('filter:post.getPostSummaryByPids', { posts: posts, uid: uid });
		return result.posts;
	};

	async function parsePosts(posts, options) {
		return await Promise.all(posts.map(async (post) => {
			if (!post.content && !post.sourceContent) {
				return post;
			}
			if (options.parse) {
				post = await Posts.parsePost(post);
			}
			if (options.stripTags) {
				post.content = stripTags(post.content);
			}
			if (options.escape) {
				post.content = post.content ? validator.escape(String(post.content)) : post.content;
			}
			return post;
		}));
	}

	async function getTopicAndCategories(tids) {
		const topicsData = await topics.getTopicsFields(tids, [
			'uid', 'tid', 'title', 'generatedTitle', 'cid', 'tags', 'slug',
			'deleted', 'scheduled', 'postcount', 'mainPid', 'teaserPid',
		]);

		const cids = _.uniq(topicsData.map(topic => topic && topic.cid));
		const categoriesData = await categories.getCategoriesFields(cids, [
			'cid', 'name', 'icon', 'slug', 'parentCid',
			'bgColor', 'color', 'backgroundImage', 'imageClass',
		]);

		return { topics: topicsData, categories: categoriesData };
	}

	function toObject(key, data) {
		const obj = {};
		for (let i = 0; i < data.length; i += 1) {
			obj[data[i][key]] = data[i];
		}
		return obj;
	}

	function stripTags(content) {
		if (content) {
			return utils.stripHTMLTags(content, utils.stripTags);
		}
		return content;
	}
};