aboutsummaryrefslogtreecommitdiff
path: root/lib/follows.js
blob: e1febc702cbf85e87800e9a2e1d3e2462850a91a (plain)
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
var pull = require('pull-stream')
var memo = require('asyncmemo')
var lru = require('hashlru')

module.exports = Follows

function Follows(sbot, contacts) {
  if (!(this instanceof Follows)) return new Follows(sbot)

  this.sbot = sbot
  this.contacts = contacts
  var followsCache = lru(100)
  this.getFollows = memo({cache: followsCache}, this.getFollows)

  if (!sbot.messagesByType) console.error('missing messagesByType')
  else pull(
    sbot.messagesByType({type: 'contact', old: false}),
    pull.drain(function (msg) {
      var author = msg && msg.value && msg.value.author
      var c = msg && msg.value && msg.value.content
      var follows = author && followsCache.get(author)
      if (follows && c && c.contact) follows[c.contact] = c.following
    }, function (err) {
      if (err) console.trace(err)
    })
  )
}

Follows.prototype.getFollows = function (id, cb) {
  var follows = {}
  pull(
    this.contacts.createFollowsStream(id),
    pull.drain(function (feed) {
      follows[feed] = true
    }, function (err) {
      if (err) return cb(err)
      cb(null, follows)
    })
  )
}

Follows.prototype.close = function (cb) {
  this.sbot.close(cb)
}