Files: 9a8720ca9018b2b2fb70a0c670cdaf5de4069fb0 / lib / votes.js
1402 bytesRaw
1 | var pull = require('pull-stream') |
2 | var asyncMemo = require('asyncmemo') |
3 | var u = require('./util') |
4 | |
5 | module.exports = function (sbot) { |
6 | var votes = {} |
7 | |
8 | pull( |
9 | sbot.links({rel: 'vote', values: true, old: false}), |
10 | u.decryptMessages(sbot), |
11 | u.readableMessages(), |
12 | pull.drain(processMsg, function (err) { |
13 | if (err) console.error('vote', err) |
14 | }) |
15 | ) |
16 | |
17 | return asyncMemo(function (id, cb) { |
18 | var result = votes[id] = { |
19 | upvoters: {}, |
20 | downvoters: {}, |
21 | upvotes: 0, |
22 | downvotes: 0 |
23 | } |
24 | |
25 | pull( |
26 | sbot.links({dest: id, rel: 'vote', values: true}), |
27 | u.decryptMessages(sbot), |
28 | u.readableMessages(), |
29 | pull.drain(processMsg, function (err) { |
30 | cb(err, result) |
31 | }) |
32 | ) |
33 | }) |
34 | |
35 | function processMsg(msg) { |
36 | var c = msg.value.content |
37 | if (!c || !c.vote) return |
38 | var result = votes[c.vote.link] |
39 | if (!result) return |
40 | var vote = c.vote.value |
41 | var author = msg.value.author |
42 | |
43 | // remove old vote, if any |
44 | if (author in result.upvoters) { |
45 | result.upvotes-- |
46 | delete result.upvoters[author] |
47 | } else if (author in result.downvoters) { |
48 | result.downvotes-- |
49 | delete result.downvoters[author] |
50 | } |
51 | |
52 | // add new vote |
53 | if (vote > 0) { |
54 | result.upvoters[author] = vote |
55 | result.upvotes++ |
56 | } else if (vote < 0) { |
57 | result.downvoters[author] = vote |
58 | result.downvotes++ |
59 | } |
60 | } |
61 | } |
62 |
Built with git-ssb-web