git ssb

7+

dinoworm ๐Ÿ› / patchcore



Tree: 0baf5414ce7a4d8be1f75148ec7dce869d876d66

Files: 0baf5414ce7a4d8be1f75148ec7dce869d876d66 / sbot.js

3120 bytesRaw
1var pull = require('pull-stream')
2var ref = require('ssb-ref')
3var Reconnect = require('pull-reconnect')
4var createClient = require('ssb-client')
5var createFeed = require('ssb-feed')
6
7var cache = CACHE = {}
8
9exports.needs = nest({
10 'config.sync.load': 'first',
11 'keys.sync.load': 'first',
12 'sbot.obs.connectionStatus': 'first'
13})
14
15exports.gives = {
16 sbot: {
17 pull: {
18 log: true,
19 get: true,
20 userFeed: true,
21 query: true,
22 publish: true,
23 },
24 obs: {
25 connectionStatus: true
26 }
27 }
28}
29
30exports.create = function (api) {
31 const config = api.config.sync.load()
32 const keys = api.keys.sync.load()
33
34 var sbot = null
35 var connectionStatus = Value()
36
37 var rec = {
38 sync: () => {},
39 async: () => {},
40 source: () => {}
41 }
42
43 var rec = Reconnect(function (isConn) {
44 function notify (value) {
45 isConn(value); connectionStatus.set(value)
46 }
47
48 createClient(keys, {
49 manifest: require('./manifest.json'),
50 remote: config.remote,
51 caps: config.caps
52 }, function (err, _sbot) {
53 if (err) {
54 return notify(err)
55 }
56
57 sbot = _sbot
58 sbot.on('closed', function () {
59 sbot = null
60 notify(new Error('closed'))
61 })
62
63 notify()
64 })
65 })
66
67 var internal = {
68 getLatest: rec.async(function (id, cb) {
69 sbot.getLatest(id, cb)
70 }),
71 add: rec.async(function (msg, cb) {
72 sbot.add(msg, cb)
73 })
74 }
75
76 var feed = createFeed(internal, keys, {remote: true})
77
78 return {
79 sbot: {
80 pull: {
81 query: rec.source(query => {
82 return sbot.query.read(query)
83 }),
84 userFeed: rec.source(opts => {
85 return sbot.createUserStream(opts)
86 }),
87 get: rec.async(function (key, cb) {
88 if (typeof cb !== 'function') {
89 throw new Error('cb must be function')
90 }
91 if (CACHE[key]) cb(null, CACHE[key])
92 else {
93 sbot.get(key, function (err, value) {
94 if (err) return cb(err)
95 cb(null, CACHE[key] = value)
96 })
97 }
98 }),
99 publish: rec.async((content, cb) => {
100 if (content.recps) {
101 content = ssbKeys.box(content, content.recps.map(e => {
102 return ref.isFeed(e) ? e : e.link
103 }))
104 } else if (content.mentions) {
105 content.mentions.forEach(mention => {
106 if (ref.isBlob(mention.link)) {
107 sbot.blobs.push(mention.link, err => {
108 if (err) console.error(err)
109 })
110 }
111 })
112 }
113
114 feed.add(content, (err, msg) => {
115 if (err) console.error(err)
116 else if (!cb) console.log(msg)
117 cb && cb(err, msg)
118 })
119 }),
120 log: rec.source(opts => {
121 return pull(
122 sbot.createLogStream(opts),
123 pull.through(e => {
124 CACHE[e.key] = CACHE[e.key] || e.value
125 })
126 )
127 })
128 },
129 obs: {
130 connectionStatus: (listener) => connectionStatus(listener)
131 }
132 }
133 }
134}
135

Built with git-ssb-web