git ssb

2+

Dominic / ssb-client



Tree: 4062644a7f2a55d2f9039f4151d26d2d30c06bcf

Files: 4062644a7f2a55d2f9039f4151d26d2d30c06bcf / index.js

2900 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 createMsg = require('secure-scuttlebutt/message')(require('secure-scuttlebutt/defaults'))
9
10function isFunction (f) {
11 return 'function' === typeof f
12}
13
14module.exports = function (keys, config, readyCb) {
15 var manifest
16 //if we are in the browser
17 config.host = config.host || 'localhost'
18 var client = muxrpc(loadManf(config), false, serialize)()
19 client.keys = keys
20
21 var wsStream
22 var rpcStream
23
24 client.connect = function(addr, cb) {
25 if(isFunction(addr))
26 cb = addr, addr = null
27
28 addr = address(config || addr)
29 if (wsStream) {
30 wsStream.socket.close()
31 client._emit('reconnecting')
32 }
33
34 client.addr = addr
35 wsStream = ws.connect(addr)
36 rpcStream = client.createStream()
37 pull(wsStream, rpcStream, wsStream)
38
39 var onopen_ = wsStream.socket.onopen
40 wsStream.socket.onopen = function() {
41 onopen_()
42 client._emit('connect')
43
44 client.auth(function (err, authed) {
45 if (err)
46 client._emit('error', err)
47 else
48 client._emit('authed', authed)
49 cb && cb(err, authed)
50 })
51 }
52
53 var onclose_ = wsStream.socket.onclose
54 wsStream.socket.onclose = function() {
55 onclose_ && onclose_()
56 rpcStream.close(function(){})
57 client._emit('close')
58 }
59
60 return client
61 }
62
63 client.close = function(cb) {
64 wsStream.socket.close()
65 rpcStream.close(function () {
66 cb && cb()
67 })
68 return client
69 }
70
71 client.reconnect = function(opts) {
72 opts = opts || {}
73 client.close(function() {
74 if (opts.wait)
75 setTimeout(client.connect.bind(client, client.addr), opts.wait)
76 else
77 client.connect(client.addr)
78 })
79 return client
80 }
81
82 client.publish = function (content, cb) {
83 client.getLatest(client.keys.id, function (err, prev) {
84 if (!prev) {
85 var init = createMsg(client.keys, null, { type: 'init', public: client.keys.public }, null)
86 client.add(init, function (err, res) {
87 if (err)
88 return cb(err)
89 prev = res.value
90 next()
91 })
92 } else
93 next()
94
95 function next () {
96 var msg = createMsg(client.keys, null, content, prev||null)
97 client.add(msg, cb)
98 }
99 })
100 return client
101 }
102
103 var auth_ = client.auth
104 client.auth = function (cb) {
105 var authReq = ssbKeys.signObj(client.keys, {
106 role: 'client',
107 ts: Date.now(),
108 public: client.keys.public
109 })
110 auth_.call(client, authReq, cb)
111 return client
112 }
113
114 return client
115}
116
117function serialize (stream) {
118 return Serializer(stream, JSON, {split: '\n\n'})
119}
120

Built with git-ssb-web