You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nodebb/src/search.js

374 lines
10 KiB
JavaScript

11 years ago
'use strict';
9 years ago
var async = require('async');
8 years ago
var _ = require('lodash');
9 years ago
var db = require('./database');
var posts = require('./posts');
var topics = require('./topics');
var categories = require('./categories');
var user = require('./user');
var plugins = require('./plugins');
var privileges = require('./privileges');
var utils = require('./utils');
11 years ago
8 years ago
var search = module.exports;
11 years ago
search.search = function (data, callback) {
11 years ago
var start = process.hrtime();
6 years ago
data.searchIn = data.searchIn || 'titlesposts';
data.sortBy = data.sortBy || 'relevance';
9 years ago
async.waterfall([
function (next) {
6 years ago
if (data.searchIn === 'posts' || data.searchIn === 'titles' || data.searchIn === 'titlesposts') {
9 years ago
searchInContent(data, next);
6 years ago
} else if (data.searchIn === 'users') {
9 years ago
user.search(data, next);
6 years ago
} else if (data.searchIn === 'tags') {
9 years ago
topics.searchAndLoadTags(data, next);
} else {
next(new Error('[[error:unknown-search-filter]]'));
}
},
function (result, next) {
result.time = (process.elapsedTimeSince(start) / 1000).toFixed(2);
next(null, result);
},
9 years ago
], callback);
10 years ago
};
function searchInContent(data, callback) {
data.uid = data.uid || 0;
8 years ago
var pids;
var metadata;
6 years ago
var itemsPerPage = Math.min(data.itemsPerPage || 10, 100);
const returnData = {
posts: [],
matchCount: 0,
pageCount: 1,
};
8 years ago
async.waterfall([
function (next) {
async.parallel({
6 years ago
searchCids: async.apply(getSearchCids, data),
searchUids: async.apply(getSearchUids, data),
8 years ago
}, next);
},
8 years ago
function (results, next) {
function doSearch(type, searchIn, next) {
if (searchIn.includes(data.searchIn)) {
plugins.fireHook('filter:search.query', {
index: type,
content: data.query,
matchWords: data.matchWords || 'all',
cid: results.searchCids,
uid: results.searchUids,
7 years ago
searchData: data,
}, next);
} else {
next(null, []);
}
}
8 years ago
async.parallel({
6 years ago
pids: async.apply(doSearch, 'post', ['posts', 'titlesposts']),
tids: async.apply(doSearch, 'topic', ['titles', 'titlesposts']),
8 years ago
}, next);
},
function (results, next) {
pids = results.pids;
if (data.returnIds) {
return callback(null, results);
}
6 years ago
if (!results.pids.length && !results.tids.length) {
return callback(null, returnData);
10 years ago
}
8 years ago
topics.getMainPids(results.tids, next);
},
function (mainPids, next) {
pids = mainPids.concat(pids).filter(Boolean);
privileges.posts.filter('topics:read', pids, data.uid, next);
8 years ago
},
function (pids, next) {
filterAndSort(pids, data, next);
},
function (pids, next) {
plugins.fireHook('filter:search.inContent', {
pids: pids,
}, next);
},
function (_metadata, next) {
metadata = _metadata;
returnData.matchCount = metadata.pids.length;
returnData.pageCount = Math.max(1, Math.ceil(parseInt(returnData.matchCount, 10) / itemsPerPage));
8 years ago
if (data.page) {
const start = Math.max(0, (data.page - 1)) * itemsPerPage;
metadata.pids = metadata.pids.slice(start, start + itemsPerPage);
8 years ago
}
posts.getPostSummaryByPids(metadata.pids, data.uid, {}, next);
8 years ago
},
function (posts, next) {
returnData.posts = posts;
// Append metadata to returned payload (without pids)
delete metadata.pids;
next(null, Object.assign(returnData, metadata));
8 years ago
},
], callback);
10 years ago
}
11 years ago
function filterAndSort(pids, data, callback) {
if (data.sortBy === 'relevance' && !data.replies && !data.timeRange && !data.hasTags) {
return setImmediate(callback, null, pids);
}
8 years ago
async.waterfall([
function (next) {
getMatchedPosts(pids, data, next);
},
function (posts, next) {
if (!posts.length) {
8 years ago
return callback(null, pids);
}
posts = posts.filter(Boolean);
8 years ago
posts = filterByPostcount(posts, data.replies, data.repliesFilter);
posts = filterByTimerange(posts, data.timeRange, data.timeFilter);
posts = filterByTags(posts, data.hasTags);
8 years ago
sortPosts(posts, data);
plugins.fireHook('filter:search.filterAndSort', { pids: pids, posts: posts, data: data }, next);
},
function (result, next) {
pids = result.posts.map(post => post && post.pid);
8 years ago
next(null, pids);
},
], callback);
}
function getMatchedPosts(pids, data, callback) {
6 years ago
var postFields = ['pid', 'uid', 'tid', 'timestamp', 'deleted', 'upvotes', 'downvotes'];
var categoryFields = [];
if (data.sortBy.startsWith('category.')) {
6 years ago
categoryFields.push(data.sortBy.split('.')[1]);
}
var postsData;
6 years ago
let tids;
let uids;
async.waterfall([
function (next) {
posts.getPostsFields(pids, postFields, next);
},
function (_postsData, next) {
postsData = _postsData.filter(post => post && !post.deleted);
async.parallel({
users: function (next) {
if (data.sortBy.startsWith('user')) {
6 years ago
uids = _.uniq(postsData.map(post => post.uid));
9 years ago
user.getUsersFields(uids, ['username'], next);
} else {
next();
}
},
topics: function (next) {
var topicsData;
6 years ago
tids = _.uniq(postsData.map(post => post.tid));
let cids;
async.waterfall([
function (next) {
topics.getTopicsData(tids, next);
},
function (_topics, next) {
topicsData = _topics;
async.parallel({
categories: function (next) {
if (!categoryFields.length) {
return next();
}
6 years ago
cids = _.uniq(topicsData.map(topic => topic && topic.cid));
db.getObjectsFields(cids.map(cid => 'category:' + cid), categoryFields, next);
},
tags: function (next) {
7 years ago
if (Array.isArray(data.hasTags) && data.hasTags.length) {
topics.getTopicsTags(tids, next);
} else {
setImmediate(next);
}
},
}, next);
},
8 years ago
function (results, next) {
6 years ago
const cidToCategory = _.zipObject(cids, results.categories);
8 years ago
topicsData.forEach(function (topic, index) {
6 years ago
if (topic && results.categories && cidToCategory[topic.cid]) {
topic.category = cidToCategory[topic.cid];
8 years ago
}
if (topic && results.tags && results.tags[index]) {
topic.tags = results.tags[index];
}
});
8 years ago
next(null, topicsData);
},
], next);
},
}, next);
},
function (results, next) {
6 years ago
const tidToTopic = _.zipObject(tids, results.topics);
const uidToUser = _.zipObject(uids, results.users);
postsData.forEach(function (post) {
if (results.topics && tidToTopic[post.tid]) {
post.topic = tidToTopic[post.tid];
if (post.topic && post.topic.category) {
post.category = post.topic.category;
}
}
6 years ago
if (uidToUser[post.uid]) {
post.user = uidToUser[post.uid];
}
});
postsData = postsData.filter(post => post && post.topic && !post.topic.deleted);
next(null, postsData);
},
], callback);
}
function filterByPostcount(posts, postCount, repliesFilter) {
postCount = parseInt(postCount, 10);
if (postCount) {
if (repliesFilter === 'atleast') {
6 years ago
posts = posts.filter(post => post.topic && post.topic.postcount >= postCount);
} else {
6 years ago
posts = posts.filter(post => post.topic && post.topic.postcount <= postCount);
}
}
return posts;
}
function filterByTimerange(posts, timeRange, timeFilter) {
8 years ago
timeRange = parseInt(timeRange, 10) * 1000;
if (timeRange) {
6 years ago
const time = Date.now() - timeRange;
if (timeFilter === 'newer') {
6 years ago
posts = posts.filter(post => post.timestamp >= time);
} else {
6 years ago
posts = posts.filter(post => post.timestamp <= time);
}
}
return posts;
}
function filterByTags(posts, hasTags) {
7 years ago
if (Array.isArray(hasTags) && hasTags.length) {
posts = posts.filter(function (post) {
var hasAllTags = false;
7 years ago
if (post && post.topic && Array.isArray(post.topic.tags) && post.topic.tags.length) {
6 years ago
hasAllTags = hasTags.every(tag => post.topic.tags.includes(tag));
}
return hasAllTags;
});
}
return posts;
}
function sortPosts(posts, data) {
if (!posts.length || data.sortBy === 'relevance') {
return;
}
data.sortDirection = data.sortDirection || 'desc';
var direction = data.sortDirection === 'desc' ? 1 : -1;
6 years ago
const fields = data.sortBy.split('.');
if (fields.length === 1) {
return posts.sort((p1, p2) => direction * (p2[fields[0]] - p1[fields[0]]));
}
var firstPost = posts[0];
if (!fields || fields.length !== 2 || !firstPost[fields[0]] || !firstPost[fields[0]][fields[1]]) {
return;
}
var isNumeric = utils.isNumber(firstPost[fields[0]][fields[1]]);
if (isNumeric) {
6 years ago
posts.sort((p1, p2) => direction * (p2[fields[0]][fields[1]] - p1[fields[0]][fields[1]]));
} else {
posts.sort(function (p1, p2) {
9 years ago
if (p1[fields[0]][fields[1]] > p2[fields[0]][fields[1]]) {
return direction;
} else if (p1[fields[0]][fields[1]] < p2[fields[0]][fields[1]]) {
return -direction;
}
return 0;
});
}
}
function getSearchCids(data, callback) {
if (!Array.isArray(data.categories) || !data.categories.length) {
return callback(null, []);
}
if (data.categories.includes('all')) {
return categories.getCidsByPrivilege('categories:cid', data.uid, 'read', callback);
}
8 years ago
async.waterfall([
function (next) {
async.parallel({
watchedCids: function (next) {
if (data.categories.includes('watched')) {
user.getCategoriesByStates(data.uid, [categories.watchStates.watching], next);
8 years ago
} else {
setImmediate(next, null, []);
8 years ago
}
},
childrenCids: function (next) {
if (data.searchChildren) {
getChildrenCids(data.categories, data.uid, next);
} else {
setImmediate(next, null, []);
8 years ago
}
},
}, next);
},
8 years ago
function (results, next) {
6 years ago
const cids = _.uniq(results.watchedCids.concat(results.childrenCids).concat(data.categories).filter(Boolean));
8 years ago
next(null, cids);
},
8 years ago
], callback);
}
function getChildrenCids(cids, uid, callback) {
8 years ago
async.waterfall([
function (next) {
6 years ago
async.map(cids, categories.getChildrenCids, next);
8 years ago
},
6 years ago
function (childrenCids, next) {
privileges.categories.filterCids('find', _.uniq(_.flatten(childrenCids)), uid, next);
8 years ago
},
], callback);
}
function getSearchUids(data, callback) {
if (data.postedBy) {
user.getUidsByUsernames(Array.isArray(data.postedBy) ? data.postedBy : [data.postedBy], callback);
} else {
setImmediate(callback, null, []);
}
}
Async refactor in place (#7736) * feat: allow both callback&and await * feat: ignore async key * feat: callbackify and promisify in same file * Revert "feat: callbackify and promisify in same file" This reverts commit cea206a9b8e6d8295310074b18cc82a504487862. * feat: no need to store .callbackify * feat: change getTopics to async * feat: remove .async * fix: byScore * feat: rewrite topics/index and social with async/await * fix: rewrite topics/data.js fix issue with async.waterfall, only pass result if its not undefined * feat: add callbackify to redis/psql * feat: psql use await * fix: redis :volcano: * feat: less returns * feat: more await rewrite * fix: redis tests * feat: convert sortedSetAdd rewrite psql transaction to async/await * feat: :dog: * feat: test * feat: log client and query * feat: log bind * feat: more logs * feat: more logs * feat: check perform * feat: dont callbackify transaction * feat: remove logs * fix: main functions * feat: more logs * fix: increment * fix: rename * feat: remove cls * fix: remove console.log * feat: add deprecation message to .async usage * feat: update more dbal methods * fix: redis :voodoo: * feat: fix redis zrem, convert setObject * feat: upgrade getObject methods * fix: psql getObjectField * fix: redis tests * feat: getObjectKeys * feat: getObjectValues * feat: isObjectField * fix: add missing return * feat: delObjectField * feat: incrObjectField * fix: add missing await * feat: remove exposed helpers * feat: list methods * feat: flush/empty * feat: delete * fix: redis delete all * feat: get/set * feat: incr/rename * feat: type * feat: expire * feat: setAdd * feat: setRemove * feat: isSetMember * feat: getSetMembers * feat: setCount, setRemoveRandom * feat: zcard,zcount * feat: sortedSetRank * feat: isSortedSetMember * feat: zincrby * feat: sortedSetLex * feat: processSortedSet * fix: add mising await * feat: debug psql * fix: psql test * fix: test * fix: another test * fix: test fix * fix: psql tests * feat: remove logs * feat: user arrow func use builtin async promises * feat: topic bookmarks * feat: topic.delete * feat: topic.restore * feat: topics.purge * feat: merge * feat: suggested * feat: topics/user.js * feat: topics modules * feat: topics/follow * fix: deprecation msg * feat: fork * feat: topics/posts * feat: sorted/recent * feat: topic/teaser * feat: topics/tools * feat: topics/unread * feat: add back node versions disable deprecation notice wrap async controllers in try/catch * feat: use db directly * feat: promisify in place * fix: redis/psql * feat: deprecation message logs for psql * feat: more logs * feat: more logs * feat: logs again * feat: more logs * fix: call release * feat: restore travis, remove logs * fix: loops * feat: remove .async. usage
6 years ago
search.async = require('./promisify')(search);