-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathbookmarks.js
More file actions
89 lines (72 loc) · 2.51 KB
/
Copy pathbookmarks.js
File metadata and controls
89 lines (72 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict';
const async = require('async');
const db = require('../database');
const user = require('../user');
// ---- implementations moved out of the exports wrapper ----
async function getUserBookmark(tid, uid) {
// TEMP: log for manual verification; remove before final commit
//console.log('NOOR_NIKNAM:getUserBookmark', { tid, uid });
// Or, if you prefer winston:
// require.main.require('winston').info('NOOR_NIKNAM:getUserBookmark', { tid, uid });
if (Number.parseInt(uid, 10) <= 0) {
return null;
}
return db.sortedSetScore(`tid:${tid}:bookmarks`, uid);
}
async function getUserBookmarks(tids, uid) {
if (Number.parseInt(uid, 10) <= 0) {
return tids.map(() => null);
}
return db.sortedSetsScore(
tids.map(tid => `tid:${tid}:bookmarks`),
uid
);
}
async function setUserBookmark(tid, uid, index) {
// TEMP: log for manual verification; remove before final commit
//console.log('NOOR_NIKNAM:setUserBookmark', { tid, uid, index });
if (Number.parseInt(uid, 10) <= 0) {
return;
}
await db.sortedSetAdd(`tid:${tid}:bookmarks`, index, uid);
}
async function getTopicBookmarks(tid) {
return db.getSortedSetRangeWithScores(`tid:${tid}:bookmarks`, 0, -1);
}
async function updateTopicBookmarks(Topics, tid, pids) {
const maxIndex = await Topics.getPostCount(tid);
const indices = await db.sortedSetRanks(`tid:${tid}:posts`, pids);
const postIndices = indices.map(i => (i === null ? 0 : i + 1));
const minIndex = Math.min(...postIndices);
const bookmarks = await getTopicBookmarks(tid);
const uidData = bookmarks
.map(b => ({ uid: b.value, bookmark: Number.parseInt(b.score, 10) }))
.filter(data => data.bookmark >= minIndex);
await async.eachLimit(uidData, 50, async (data) => {
let bookmark = Math.min(data.bookmark, maxIndex);
postIndices.forEach((i) => {
if (i < data.bookmark) {
bookmark -= 1;
}
});
// ensure valid bookmark if last post(s) were removed
bookmark = Math.min(bookmark, maxIndex - pids.length);
if (bookmark === data.bookmark) {
return;
}
const settings = await user.getSettings(data.uid);
if (settings.topicPostSort === 'most_votes') {
return;
}
await setUserBookmark(tid, data.uid, bookmark);
});
}
// ---- export wrapper with no returns ----
module.exports = function (Topics) {
Topics.getUserBookmark = getUserBookmark;
Topics.getUserBookmarks = getUserBookmarks;
Topics.setUserBookmark = setUserBookmark;
Topics.getTopicBookmarks = getTopicBookmarks;
Topics.updateTopicBookmarks = (tid, pids) =>
updateTopicBookmarks(Topics, tid, pids);
};