git ssb

1+

punkmonk.termux / mvd



forked from ev / mvd

Tree: d2b5693b01842e3376dae3c3cf5c579e03e490c4

Files: d2b5693b01842e3376dae3c3cf5c579e03e490c4 / plugins / local.js

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

Built with git-ssb-web