Files: 2a20acf33d2e0b90142c3b19c1a1fa74d59d32da / plugs / channel / obs.js
2083 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, 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 | 'channel.obs.mostActive': true |
15 | }) |
16 | |
17 | exports.create = function (api) { |
18 | var recentChannels = null |
19 | var mostActiveChannels = null |
20 | var channelsLookup = null |
21 | |
22 | return nest({ |
23 | 'channel.obs.recent': function () { |
24 | load() |
25 | return recentChannels |
26 | }, |
27 | 'channel.obs.mostActive': function () { |
28 | load() |
29 | return mostActiveChannels |
30 | } |
31 | }) |
32 | |
33 | function load () { |
34 | if (!recentChannels) { |
35 | var sync = Value(false) |
36 | channelsLookup = Dict() |
37 | |
38 | pull( |
39 | api.sbot.pull.stream(sbot => sbot.patchwork.channels({live: true})), |
40 | pull.drain(data => { |
41 | channelsLookup.transaction(() => { |
42 | for (var channel in data) { |
43 | var obs = channelsLookup.get(channel) |
44 | if (!obs) { |
45 | obs = ChannelRef(channel) |
46 | channelsLookup.put(channel, obs) |
47 | } |
48 | var count = data[channel].count != null ? data[channel].count : obs.count() + 1 |
49 | var updatedAt = data[channel].timestamp |
50 | obs.set({ id: channel, updatedAt, count }) |
51 | } |
52 | }) |
53 | if (!sync()) { |
54 | sync.set(true) |
55 | } |
56 | }) |
57 | ) |
58 | |
59 | recentChannels = computed(throttle(channelsLookup, 1000), (lookup) => { |
60 | var values = Object.keys(lookup).map(x => lookup[x]).sort((a, b) => b.updatedAt - a.updatedAt).map(x => x.id) |
61 | return values |
62 | }) |
63 | |
64 | mostActiveChannels = computed(throttle(channelsLookup, 1000), (lookup) => { |
65 | var values = Object.keys(lookup).map(x => lookup[x]).sort((a, b) => b.count - a.count).map(x => [x.id, x.count]) |
66 | return values |
67 | }) |
68 | |
69 | recentChannels.sync = sync |
70 | } |
71 | } |
72 | } |
73 | |
74 | function ChannelRef (id) { |
75 | return Struct({ |
76 | id, |
77 | updatedAt: Value(0), |
78 | count: Value(0) |
79 | }, {merge: true}) |
80 | } |
81 |
Built with git-ssb-web