git ssb

30+

cel / git-ssb-web



Tree: 8599df15928f4db206734f0d4ed00429e6b36a86

Files: 8599df15928f4db206734f0d4ed00429e6b36a86 / lib / about.js

2776 bytesRaw
1var pull = require('pull-stream')
2var cat = require('pull-cat')
3var u = require('./util')
4var ref = require('ssb-ref')
5var asyncMemo = require('asyncmemo')
6
7function mixin(a, b) {
8 if (b) for (var k in b) a[k] = b[k]
9}
10
11module.exports = function (sbot, source) {
12 var abouts = {/* link: {feed: name} */}
13 var msgs = {/* key: content */}
14
15 pull(
16 sbot.createLogStream({old: false}),
17 u.decryptMessages(sbot),
18 u.readableMessages(),
19 pull.drain(processMsg, function (err) {
20 if (err) console.error('about', err)
21 })
22 )
23
24 var getAboutInfo = asyncMemo(function (id, cb) {
25 var abt = abouts[id] = {}
26 var _err
27 var w = 1
28 if (ref.isMsg(id)) {
29 w++
30 sbot.get(id, function (err, value) {
31 if (err) {
32 console.error('about: missing message', id, err)
33 if (!--w) next()
34 return
35 }
36 u.decryptMessage(sbot, {key: id, value: value}, function (err, msg) {
37 if (err) console.error('decrypt failed', id, err)
38 else if (u.isMessageReadable(msg)) {
39 msgs[id] = msg && msg.value && msg.value.content
40 }
41 if (!--w) next()
42 })
43 })
44 }
45 pull(
46 sbot.links({
47 rel: 'about',
48 values: true,
49 dest: id
50 }),
51 u.decryptMessages(sbot),
52 u.readableMessages(),
53 pull.drain(processMsg, function (err) {
54 _err = err
55 if (!--w) next()
56 })
57 )
58 function next() {
59 cb(_err, abt)
60 }
61 })
62
63 function processMsg(msg) {
64 var c = msg.value.content
65 if (!c) return
66
67 // handle receiving a message after receiving a link to it
68 if (msg.key in abouts) msgs[msg.key] = c
69
70 var target = c.about
71 if (!target) return
72 var abt = abouts[target]
73 if (!abt) return
74 var ab = abt[msg.value.author] || (abt[msg.value.author] = {})
75 for (var key in c) {
76 if (key === 'about' || key === 'type') continue
77 var val = c[key]
78 if (!val) delete ab[key]
79 else {
80 if (key === 'image' && typeof val === 'object' && val.link) {
81 val = val.link
82 }
83 ab[key] = val
84 }
85 }
86 }
87
88 function getAbout(dest, cb) {
89 if (!dest) return cb(null, {})
90 var target = dest.target || dest
91 getAboutInfo(target, function (err, info) {
92 if (err) return cb(err)
93 // order of preference: source, owner, any, msg
94 var ab = {}
95 mixin(ab, msgs[target])
96 for (var feed in info) mixin(ab, info[feed])
97 mixin(ab, info[dest.owner || dest])
98 mixin(ab, info[source])
99 if (!ab.name) ab.name = u.truncate(target, 20)
100 cb(null, ab)
101 })
102 }
103
104 getAbout.getName = function (id, cb) {
105 getAbout(id, function (err, about) {
106 cb(err, about && about.name)
107 })
108 }
109
110 return getAbout
111}
112

Built with git-ssb-web