-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
101 lines (85 loc) · 2.4 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
99
100
101
var debug = require('debug')('meta-swarm')
var events = require('events')
var inherits = require('inherits')
var signalhub = require('signalhub')
inherits(Meta, events.EventEmitter)
module.exports = Meta
function Meta (swarm, urls, opts) {
if (!swarm) throw new Error('Need a `webrtc-swarm`-like function.')
if (!(this instanceof Meta)) return new Meta(opts)
if (!opts) opts = {}
this.events = opts.events || []
this.urls = urls || []
this.namespace = opts.namespace || 'meta-swarm'
this.opts = opts || {}
this.swarm = swarm
this.peers = {}
this.swarms = {}
if (this.urls.length !== 0) {
this._init()
}
}
Meta.prototype._init = function () {
var self = this
self.urls.forEach(function (url) {
debug('connecting to signalhub', url)
self._connect(url)
})
}
Meta.prototype._connect = function (url) {
var self = this
var hub = signalhub(self.namespace, [url])
var sw
if (this.opts.keyPair) sw = self.swarm(hub, this.opts.keyPair, this.opts)
else sw = self.swarm(hub, this.opts)
this.events.forEach(function (event) {
sw.on(event, function () {
var args = Array.prototype.slice.call(arguments)
args.unshift(event)
debug(args)
self.emit.apply(null, args)
})
})
sw.on('accept', function (id, sharedSignPubKey) {
self.emit('accept', id, sharedSignPubKey)
})
sw.on('connect', function (peer, id) {
self.emit('connect', peer, id)
self.on('send', function (data) {
peer.send(data)
})
peer.on('data', function (data) {
self.emit('data', data, id)
})
self.peers[id] = peer
})
sw.on('disconnect', function (peer, id) {
self.emit('disconnect', peer, id)
delete self.peers[id]
})
this.swarms[url] = sw
return sw
}
Meta.prototype.addPeer = function (peerId) {
Object.keys(this.swarms).forEach((hubUrl) => {
var swarm = this.swarms[hubUrl]
if (swarm.whitelist.indexOf(peerId) !== -1) return
swarm.whitelist.push(peerId)
})
}
Meta.prototype.removePeer = function (peerId) {
Object.keys(this.swarms).forEach((hubUrl) => {
var swarm = this.swarms[hubUrl]
var index = swarm.whitelist.indexOf(peerId)
if (index === -1) return
swarm.whitelist.splice(index, 1)
})
}
Meta.prototype.addHub = function (url) {
if (this.swarms[url]) return
this._connect(url)
}
Meta.prototype.send = function (data, id) {
if (id) this.peers[id].send(data)
else this.emit('send', data)
}