1 | const FlatMap = require('pull-flatmap')
|
2 | const pull = require('pull-stream')
|
3 | const Notify = require('pull-notify')
|
4 |
|
5 | function createLog (message) {
|
6 | let logged = false
|
7 | return function () {
|
8 | if (logged) return
|
9 | logged = true
|
10 | console.error(message)
|
11 | }
|
12 | }
|
13 |
|
14 | module.exports = function setupLegacy(layered) {
|
15 | function mapGraph (g, fn) {
|
16 | const _g = {}
|
17 | for (const j in g) {
|
18 | for (const k in g[j]) {
|
19 | _g[j] = _g[j] || {}
|
20 | _g[j][k] = fn(g[j][k])
|
21 | }
|
22 | }
|
23 | return _g
|
24 | }
|
25 |
|
26 | function map (o, fn) {
|
27 | const _o = {}
|
28 | for (const k in o) _o[k] = fn(o[k])
|
29 | return _o
|
30 | }
|
31 |
|
32 | function toLegacyValue (v) {
|
33 |
|
34 |
|
35 | return v >= 0 ? true : v === -2 ? null : v === -1 ? false : null
|
36 | }
|
37 |
|
38 | const logLegacy1 = createLog('ssb-friends: createFriendStream legacy api used')
|
39 | const logLegacy2 = createLog('ssb-friends: get legacy api used')
|
40 | const logLegacy3 = createLog('ssb-friends: stream legacy api used')
|
41 |
|
42 | return {
|
43 | createFriendStream: function (opts) {
|
44 | logLegacy1()
|
45 | let first = true
|
46 | return pull(
|
47 | layered.hopStream(opts),
|
48 | FlatMap(function (change) {
|
49 | const a = []
|
50 | for (const k in change) {
|
51 | if (!first || change[k] >= 0) {
|
52 | if (opts && opts.meta) {
|
53 | a.push({ id: k, hops: change[k] })
|
54 | } else {
|
55 | a.push(k)
|
56 | }
|
57 | }
|
58 | }
|
59 | first = false
|
60 | return a
|
61 | })
|
62 | )
|
63 | },
|
64 | get: function (opts, cb) {
|
65 | logLegacy2()
|
66 | if (!cb) {
|
67 | cb = opts
|
68 | opts = {}
|
69 | }
|
70 | layered.onReady(function () {
|
71 | let value = layered.getGraph()
|
72 |
|
73 | if (opts && opts.source) {
|
74 | value = value[opts.source]
|
75 | if (value && opts.dest) {
|
76 | cb(null, toLegacyValue(value[opts.dest]))
|
77 | } else {
|
78 | cb(null, map(value, toLegacyValue))
|
79 | }
|
80 | } else if (opts && opts.dest) {
|
81 | const _value = {}
|
82 | for (const k in value) {
|
83 | if (typeof value[k][opts.dest] !== 'undefined') {
|
84 | _value[k] = value[k][opts.dest]
|
85 | }
|
86 | }
|
87 | cb(null, map(_value, toLegacyValue))
|
88 | } else { cb(null, mapGraph(value, toLegacyValue)) }
|
89 | })
|
90 | },
|
91 | stream: function () {
|
92 | logLegacy3()
|
93 | const streamNotify = Notify()
|
94 | const source = streamNotify.listen()
|
95 | layered.onReady(function () {
|
96 | streamNotify(mapGraph(layered.getGraph(), toLegacyValue))
|
97 | layered.onEdge(function (j, k, v) {
|
98 | streamNotify({ from: j, to: k, value: toLegacyValue(v) })
|
99 | })
|
100 | })
|
101 | return source
|
102 | }
|
103 | }
|
104 | }
|