git ssb

30+

cel / git-ssb-web



Tree: 923b006ef1f00967247a9178711ebccebf8785c8

Files: 923b006ef1f00967247a9178711ebccebf8785c8 / lib / votes.js

1630 bytesRaw
1var pull = require('pull-stream')
2var asyncMemo = require('asyncmemo')
3var u = require('./util')
4
5module.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.backlinks ? sbot.backlinks.read({
27 reverse: true,
28 query: [{$filter: {
29 dest: id,
30 value: {
31 content: {
32 type: 'vote'
33 }
34 }
35 }}]
36 }) : sbot.links({dest: id, rel: 'vote', values: true}),
37 u.decryptMessages(sbot),
38 u.readableMessages(),
39 pull.drain(processMsg, function (err) {
40 cb(err, result)
41 })
42 )
43 })
44
45 function processMsg(msg) {
46 var c = msg.value.content
47 if (!c || !c.vote) return
48 var result = votes[c.vote.link]
49 if (!result) return
50 var vote = c.vote.value
51 var author = msg.value.author
52
53 // remove old vote, if any
54 if (author in result.upvoters) {
55 result.upvotes--
56 delete result.upvoters[author]
57 } else if (author in result.downvoters) {
58 result.downvotes--
59 delete result.downvoters[author]
60 }
61
62 // add new vote
63 if (vote > 0) {
64 result.upvoters[author] = vote
65 result.upvotes++
66 } else if (vote < 0) {
67 result.downvoters[author] = vote
68 result.downvotes++
69 }
70 }
71}
72

Built with git-ssb-web