git ssb

2+

Dominic / ssb-client



Tree: 2432ab835f42ded3c3a546abecd81a12a8de3d44

Files: 2432ab835f42ded3c3a546abecd81a12a8de3d44 / index.js

2611 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, readyCb) {
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 var onopen_ = wsStream.socket.onopen
30 wsStream.socket.onopen = function() {
31 onopen_()
32 client._emit('connect')
33
34 client.auth(function (err, authed) {
35 if (err)
36 client._emit('error', err)
37 else
38 client._emit('authed', authed)
39 cb && cb(err, authed)
40 })
41 }
42
43 var onclose_ = wsStream.socket.onclose
44 wsStream.socket.onclose = function() {
45 onclose_ && onclose_()
46 rpcStream.close(function(){})
47 client._emit('close')
48 }
49 }
50
51 client.close = function(cb) {
52 wsStream.socket.close()
53 rpcStream.close(function () {
54 cb && cb()
55 })
56 }
57
58 client.reconnect = function(opts) {
59 opts = opts || {}
60 client.close(function() {
61 if (opts.wait)
62 setTimeout(client.connect.bind(client, client.addr), opts.wait)
63 else
64 client.connect(client.addr)
65 })
66 }
67
68 client.publish = function (content, cb) {
69 client.getLatest(client.keys.id, function (err, prev) {
70 if (!prev) {
71 var init = createMsg(client.keys, null, { type: 'init', public: client.keys.public }, null)
72 client.add(init, function (err, res) {
73 if (err)
74 return cb(err)
75 prev = res.value
76 next()
77 })
78 } else
79 next()
80
81 function next () {
82 var msg = createMsg(client.keys, null, content, prev||null)
83 client.add(msg, cb)
84 }
85 })
86 }
87
88 var auth_ = client.auth
89 client.auth = function (cb) {
90 var authReq = ssbKeys.signObj(client.keys, {
91 role: 'client',
92 ts: Date.now(),
93 public: client.keys.public
94 })
95 auth_.call(client, authReq, cb)
96 }
97
98 client.connect(addr, readyCb)
99 return client
100}
101
102function serialize (stream) {
103 return Serializer(stream, JSON, {split: '\n\n'})
104}

Built with git-ssb-web