From 44d88352242350cd440e7592b89a759f2863e2e1 Mon Sep 17 00:00:00 2001 From: Erke Xia Date: Wed, 25 Sep 2024 02:17:19 +0000 Subject: [PATCH 1/3] Adding logic to sort the posts by popularity. Still need to be tested --- src/categories/topics.js | 33 ++++++++++++++++++++++++++++++- src/controllers/category.js | 2 +- src/views/admin/settings/post.tpl | 1 + 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/categories/topics.js b/src/categories/topics.js index 1a2a259f3d..76b22b59d4 100644 --- a/src/categories/topics.js +++ b/src/categories/topics.js @@ -98,8 +98,39 @@ module.exports = function (Categories) { most_votes: `cid:${cid}:tids:votes`, most_views: `cid:${cid}:tids:views`, }; + let set; + if (sort === 'popularity') { + const voteSortedSet = `cid:${cid}:tids:votes`; + const createSortedSet = `cid:${cid}:tids:create`; + const postIdsWithScores = await db.getSortedSetRangeWithScores(voteSortedSet, 0, -1); + const tempSortedSet = `cid:${cid}:tids:popular`; + await db.delete(tempSortedSet); + const recentIdsWithScores = await db.getSortedSetRangeWithScores(createSortedSet, 0, -1); - let set = sortToSet.hasOwnProperty(sort) ? sortToSet[sort] : `cid:${cid}:tids`; + const currentTime = Date.now(); + for (let i = 0; i < postIdsWithScores.length; i += 1) { + const postId = postIdsWithScores[i]; + const votes = postIdsWithScores[i]; + + const result = recentIdsWithScores.find(item => item.value === postId['value']); + const postCreationTime = result ? result.score : null; + if (!postCreationTime) { + continue; + } + + const timeSinceCreation = (currentTime - postCreationTime) /3600000; + const votes_num = votes['score'] + 1; + const time = Math.pow(timeSinceCreation+2,1.8) + const score = votes_num / time; + + await db.sortedSetAdd(tempSortedSet, score, postId['value']); + } + + + set = tempSortedSet; + }else{ + set = sortToSet.hasOwnProperty(sort) ? sortToSet[sort] : `cid:${cid}:tids`; + } if (data.tag) { if (Array.isArray(data.tag)) { diff --git a/src/controllers/category.js b/src/controllers/category.js index 487ea21cce..726b5a6e27 100644 --- a/src/controllers/category.js +++ b/src/controllers/category.js @@ -21,7 +21,7 @@ const categoryController = module.exports; const url = nconf.get('url'); const relative_path = nconf.get('relative_path'); const validSorts = [ - 'recently_replied', 'recently_created', 'most_posts', 'most_votes', 'most_views', + 'recently_replied', 'recently_created', 'most_posts', 'most_votes', 'most_views', 'popularity', ]; categoryController.get = async function (req, res, next) { diff --git a/src/views/admin/settings/post.tpl b/src/views/admin/settings/post.tpl index d361597946..686412a4dc 100644 --- a/src/views/admin/settings/post.tpl +++ b/src/views/admin/settings/post.tpl @@ -20,6 +20,7 @@