git ssb

0+

alanz / patchwork



forked from Matt McKegg / patchwork

Tree: b2f193dcfd24e9aae4e6ce5010c909b026e2e662

Files: b2f193dcfd24e9aae4e6ce5010c909b026e2e662 / modules / channel / obs / subscribed.js

1528 bytesRaw
1var pull = require('pull-stream')
2var computed = require('mutant/computed')
3var MutantPullReduce = require('mutant-pull-reduce')
4var nest = require('depnest')
5
6var throttle = require('mutant/throttle')
7
8exports.needs = nest({
9 'sbot.pull.userFeed': 'first'
10})
11
12exports.gives = nest({
13 'channel.obs': ['subscribed']
14})
15
16exports.create = function (api) {
17 var cache = {}
18
19 return nest({
20 'channel.obs': {subscribed}
21 })
22
23 function subscribed (userId) {
24 if (cache[userId]) {
25 return cache[userId]
26 } else {
27 var stream = pull(
28 api.sbot.pull.userFeed({id: userId, live: true}),
29 pull.filter((msg) => {
30 return !msg.value || msg.value.content.type === 'channel'
31 })
32 )
33
34 var result = MutantPullReduce(stream, (result, msg) => {
35 var c = msg.value.content
36 if (typeof c.channel === 'string' && c.channel) {
37 var channel = c.channel.trim()
38 if (channel) {
39 if (typeof c.subscribed === 'boolean') {
40 if (c.subscribed) {
41 result.add(channel)
42 } else {
43 result.delete(channel)
44 }
45 }
46 }
47 }
48 return result
49 }, {
50 startValue: new Set(),
51 nextTick: true
52 })
53
54 var instance = throttle(result, 2000)
55 instance.sync = result.sync
56
57 instance.has = function (value) {
58 return computed(instance, x => x.has(value))
59 }
60
61 cache[userId] = instance
62 return instance
63 }
64 }
65}
66

Built with git-ssb-web