Files: 86661677a7623472280bc05e563bb733054a0f01 / scuttlebot.js
2445 bytesRaw
1 | var pull = require('pull-stream') |
2 | var ssbKeys = require('ssb-keys') |
3 | var ref = require('ssb-ref') |
4 | var reconnect = require('pull-reconnect') |
5 | |
6 | var config = require('./config')() |
7 | var createClient = require('ssb-client') |
8 | var createFeed = require('ssb-feed') |
9 | |
10 | var keys = require('./keys') |
11 | |
12 | var CACHE = {} |
13 | |
14 | var rec = reconnect(function (isConn) { |
15 | function notify (value) { |
16 | isConn(value) |
17 | } |
18 | |
19 | createClient(keys, { |
20 | manifest: require('./manifest.json'), |
21 | remote: config.remote, |
22 | caps: config.caps |
23 | }, function (err, _sbot) { |
24 | if(err) |
25 | return notify(err) |
26 | |
27 | sbot = _sbot |
28 | sbot.on('closed', function () { |
29 | sbot = null |
30 | notify(new Error('closed')) |
31 | }) |
32 | |
33 | notify() |
34 | }) |
35 | }) |
36 | |
37 | var internal = { |
38 | getLatest: rec.async(function (id, cb) { |
39 | sbot.getLatest(id, cb) |
40 | }), |
41 | add: rec.async(function (msg, cb) { |
42 | sbot.add(msg, cb) |
43 | }) |
44 | } |
45 | |
46 | var feed = createFeed(internal, keys, {remote: true}) |
47 | |
48 | module.exports = { |
49 | createLogStream: rec.source(function (opts) { |
50 | return pull( |
51 | sbot.createLogStream(opts), |
52 | pull.through(function (e) { |
53 | CACHE[e.key] = CACHE[e.key] || e.value |
54 | }) |
55 | ) |
56 | }), |
57 | userStream: rec.source(function (config) { |
58 | return pull( |
59 | sbot.createUserStream(config), |
60 | pull.through(function (e) { |
61 | CACHE[e.key] = CACHE[e.key] || e.value |
62 | }) |
63 | ) |
64 | }), |
65 | query: rec.source(function (query) { |
66 | return sbot.query.read(query) |
67 | }), |
68 | get: rec.async(function (key, cb) { |
69 | if('function' !== typeof cb) |
70 | throw new Error('cb must be function') |
71 | if(CACHE[key]) cb(null, CACHE[key]) |
72 | else sbot.get(key, function (err, value) { |
73 | if(err) return cb(err) |
74 | cb(null, CACHE[key] = value) |
75 | }) |
76 | }), |
77 | links: rec.source(function (query) { |
78 | return sbot.links(query) |
79 | }), |
80 | addblob: rec.sink(function (cb) { |
81 | return sbot.blobs.add(cb) |
82 | }), |
83 | publish: rec.async(function (content, cb) { |
84 | if(content.recps) |
85 | content = ssbKeys.box(content, content.recps.map(function (e) { |
86 | return ref.isFeed(e) ? e : e.link |
87 | })) |
88 | else if(content.mentions) |
89 | content.mentions.forEach(function (mention) { |
90 | if(ref.isBlob(mention.link)) { |
91 | sbot.blobs.push(mention.link, function (err) { |
92 | if(err) console.error(err) |
93 | }) |
94 | } |
95 | }) |
96 | feed.add(content, function (err, msg) { |
97 | if(err) console.error(err) |
98 | else if(!cb) console.log(msg) |
99 | cb && cb(err, msg) |
100 | }) |
101 | }) |
102 | |
103 | } |
104 | |
105 |
Built with git-ssb-web