-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (88 loc) · 2.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var broadcast = require('broadcast-stream')
var ref = require('ssb-ref')
// local plugin
// broadcasts the address:port:pubkey triple of the ssb server
// on the LAN, using multicast UDP
function isEmpty (o) {
for(var k in o)
return false
return true
}
/*
idea: instead of broadcasting constantly,
broadcast at startup, or when ip address changes (change networks)
or when you receive a boardcast.
this should use network more efficiently.
*/
module.exports = {
name: 'local',
version: '2.0.0',
init: function init (ssbServer, config) {
if(config.gossip && config.gossip.local === false)
return {
init: function () {
delete this.init
init(ssbServer, config)
}
}
var local = broadcast(config.port)
var addrs = {}
var lastSeen = {}
// cleanup old local peers
var iv = setInterval(function () {
Object.keys(lastSeen).forEach((key) => {
if (Date.now() - lastSeen[key] > 10e3) {
ssbServer.gossip.remove(addrs[key])
delete lastSeen[key]
}
})
}, 5e3)
// discover new local peers
local.on('data', function (buf) {
if (buf.loopback) return
var data = buf.toString()
var peer = ref.parseAddress(data)
if (peer && peer.key !== ssbServer.id) {
addrs[peer.key] = peer
lastSeen[peer.key] = Date.now()
//note: add the raw data, not the parsed data.
//so we still have the whole address, including protocol (eg, websockets)
ssbServer.gossip.add(data, 'local')
}
})
if (ssbServer.status) {
ssbServer.status.hook(function (fn) {
var _status = fn()
if(!isEmpty(addrs)) {
_status.local = {}
for(var k in addrs)
_status.local[k] = {address: addrs[k], seen: lastSeen[k]}
}
return _status
})
}
var int
ssbServer.close.hook(function (fn, args) {
// shut down intervals + close socket
clearInterval(int)
clearInterval(iv)
local.close()
return fn.apply(this, args)
})
setImmediate(function () {
// broadcast self
int = setInterval(function () {
if(config.gossip && config.gossip.local === false)
return
// TODO: sign beacons, so that receipient can be confidant
// that is really your id.
// (which means they can update their peer table)
// Oh if this includes your local address,
// then it becomes unforgeable.
var addr = ssbServer.getAddress('private') || ssbServer.getAddress('local')
if(addr) local.write(addr)
}, 1000)
if(int.unref) int.unref()
})
}
}