git ssb

2+

Dominic / ssb-client



Tree: 0a0f0519d65854f70324178bc08739658ca3a62e

Files: 0a0f0519d65854f70324178bc08739658ca3a62e / index.js

2421 bytesRaw
1var pull = require('pull-stream')
2var muxrpc = require('muxrpc')
3var address = require('ssb-address')
4var ws = require('pull-ws-server')
5var Serializer = require('pull-serializer')
6var ssbKeys = require('ssb-keys')
7var loadManf = require('ssb-manifest/load')
8var ssbFeed = require('secure-scuttlebutt/feed')
9var ssbDefaults = require('secure-scuttlebutt/defaults')
10
11function isFunction (f) {
12 return 'function' === typeof f
13}
14
15function throwIfError(err) {
16 if(err) throw err
17}
18
19module.exports = function (keys, config) {
20 var manifest
21 //if we are in the browser
22 config = config || {}
23 config.host = config.host || 'localhost'
24
25 var client = muxrpc(loadManf(config), { auth: 'async' }, serialize)({
26 auth: function (req, cb) {
27 // when this connects to a server, the server auths
28 // back to see who this is. we don't have any apis
29 // for the server to call (yet) so this doesn't do anything.
30 // however, if we don't just let this go through, the server
31 // log shows a nasty error log.
32 cb()
33 }
34 })
35 client.keys = keys
36
37 var wsStream
38 var rpcStream
39
40 client.connect = function(addr, cb) {
41 if(isFunction(addr))
42 cb = addr, addr = null
43
44 addr = address(addr || config)
45 client.addr = addr
46 if (wsStream) {
47 wsStream.close()
48 client._emit('reconnecting')
49 }
50
51 var called = false
52 wsStream = ws.connect(addr, {
53 onOpen: function() {
54 client._emit('connect')
55 if(called) return
56 called = true; cb && cb()
57 },
58 onClose: function() {
59 client._emit('close')
60 //rpcStream will detect close on it's own.
61 if(called) return
62 called = true; cb && cb()
63 }
64 })
65
66 rpcStream = client.createStream()
67 pull(wsStream, rpcStream, wsStream)
68
69 return client
70 }
71
72 client.close = function(cb) {
73 wsStream.close()
74 rpcStream.close(cb ? cb : throwIfError)
75 return client
76 }
77
78 client.reconnect = function(opts) {
79 opts = opts || {}
80 client.close(function() {
81 if (opts.wait)
82 setTimeout(client.connect.bind(client, client.addr), opts.wait)
83 else
84 client.connect(client.addr)
85 })
86 return client
87 }
88
89 client.createFeed = function (keys) {
90 return ssbFeed(this, keys, ssbDefaults)
91 }
92
93 return client
94}
95
96function serialize (stream) {
97 return Serializer(stream, JSON, {split: '\n\n'})
98}
99

Built with git-ssb-web