git ssb

2+

Dominic / ssb-client



Tree: c00eb7b5539d007fd4b13257e728664de6831106

Files: c00eb7b5539d007fd4b13257e728664de6831106 / index.js

2103 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 manifest = require('ssb-manifest')
8var createMsg = require('secure-scuttlebutt/message')(require('secure-scuttlebutt/defaults'))
9
10module.exports = function (keys, addr, cb) {
11 var client = muxrpc(manifest, false, serialize)()
12 client.keys = keys
13
14 var wsStream
15 var rpcStream
16
17 client.connect = function(addr, cb) {
18 addr = address(addr)
19 if (wsStream) {
20 wsStream.socket.close()
21 client._emit('reconnecting')
22 }
23
24 client.addr = addr
25 wsStream = ws.connect(addr)
26 rpcStream = client.createStream()
27 pull(wsStream, rpcStream, wsStream)
28
29 wsStream.socket.onopen = function() {
30 client._emit('connect')
31
32 client.auth(function (err) {
33 if (err)
34 client._emit('error', err)
35 else
36 client._emit('authed')
37 cb && cb(err)
38 })
39 }
40
41 wsStream.socket.onclose = function() {
42 rpcStream.close(new Error('broken link'), function(){})
43 client._emit('error', new Error('Close'))
44 }
45 }
46
47 client.close = function(cb) {
48 wsStream.socket.close()
49 rpcStream.close(function () {
50 cb && cb()
51 })
52 }
53
54 client.reconnect = function(opts) {
55 opts = opts || {}
56 client.close(function() {
57 if (opts.wait)
58 setTimeout(client.connect.bind(client, client.addr), opts.wait)
59 else
60 client.connect(client.addr)
61 })
62 }
63
64 client.publish = function (content, cb) {
65 rpc.getLatest(function (err, prev) {
66 var msg = createMsg(client.keys, null, content, prev||null)
67 rpc.add(msg, cb)
68 })
69 }
70
71 client.auth = function (cb) {
72 var authReq = ssbKeys.signObj(client.keys, {
73 role: 'client',
74 ts: Date.now(),
75 public: client.keys.public
76 })
77 rpc.auth(authReq, cb)
78 }
79
80 client.connect(addr, cb)
81 return client
82}
83
84function serialize (stream) {
85 return Serializer(stream, JSON, {split: '\n\n'})
86}

Built with git-ssb-web