Files: c042715aec13b2e61372d88ff17dea7e4cacecc1 / plugs / channel / obs / recent.js
1672 bytesRaw
1 | // uses lib/flumeview-channels |
2 | |
3 | var nest = require('depnest') |
4 | var pull = require('pull-stream') |
5 | |
6 | var { Value, Dict, Struct, computed, resolve, throttle } = require('mutant') |
7 | |
8 | exports.needs = nest({ |
9 | 'sbot.pull.stream': 'first' |
10 | }) |
11 | |
12 | exports.gives = nest({ |
13 | 'channel.obs.recent': true |
14 | }) |
15 | |
16 | exports.create = function (api) { |
17 | var recentChannels = null |
18 | var channelsLookup = null |
19 | |
20 | return nest({ |
21 | 'channel.obs.recent': function () { |
22 | load() |
23 | return recentChannels |
24 | } |
25 | }) |
26 | |
27 | function load () { |
28 | if (!recentChannels) { |
29 | var sync = Value(false) |
30 | channelsLookup = Dict() |
31 | |
32 | pull( |
33 | api.sbot.pull.stream(sbot => sbot.patchwork.channels({live: true})), |
34 | pull.drain(msg => { |
35 | channelsLookup.transaction(() => { |
36 | for (var channel in msg) { |
37 | var obs = channelsLookup.get(channel) |
38 | if (!obs) { |
39 | obs = ChannelRef(channel) |
40 | channelsLookup.put(channel, obs) |
41 | } |
42 | var count = msg.count != null ? msg.count : obs.count() + 1 |
43 | var updatedAt = msg[channel].timestamp |
44 | |
45 | obs.set({ id: channel, updatedAt, count }) |
46 | } |
47 | }) |
48 | if (!sync()) { |
49 | sync.set(true) |
50 | } |
51 | }) |
52 | ) |
53 | |
54 | recentChannels = computed(throttle(channelsLookup, 1000), (lookup) => { |
55 | var values = Object.keys(lookup).map(x => lookup[x]).sort((a, b) => b.updatedAt - a.updatedAt).map(x => x.id) |
56 | return values |
57 | }) |
58 | recentChannels.sync = sync |
59 | } |
60 | } |
61 | } |
62 | |
63 | function ChannelRef (id) { |
64 | return Struct({ |
65 | id, |
66 | updatedAt: Value(0), |
67 | count: Value(0) |
68 | }, {merge: true}) |
69 | } |
70 |
Built with git-ssb-web