forked from hyperswarm/replicator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
78 lines (63 loc) · 1.75 KB
/
index.js
File metadata and controls
78 lines (63 loc) · 1.75 KB
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
const dswarm = require('dswarm')
const pump = require('pump')
class Event {
constructor () {
this.triggered = false
this.fns = new Set()
}
on (fn) {
if (this.triggered) return fn()
this.fns.add(fn)
}
emit () {
this.triggered = true
for (const fn of this.fns) fn()
}
}
module.exports = replicator
function replicator (r, opts, cb) {
if (typeof opts === 'function') return replicator(r, null, opts)
if (!opts) opts = {}
const swarm = dswarm({
announceLocalAddress: !!opts.announceLocalAddress,
preferredPort: 49737,
bootstrap: opts.bootstrap
})
const oneConnection = new Event()
const allConnections = new Event()
swarm.on('connection', function (connection, info) {
const stream = r.replicate({
initiator: info.client,
live: opts.live,
upload: opts.upload,
download: opts.download,
encrypt: opts.encrypt,
keyPair: opts.keyPair,
onauthenticate: opts.onauthenticate
})
pump(connection, stream, connection)
if (opts.onstream) opts.onstream(stream, info)
oneConnection.emit()
})
if (r.timeouts) {
const { update, get } = r.timeouts
if (update) r.timeouts.update = (cb) => oneConnection.on(() => update(cb))
if (get) r.timeouts.get = (cb) => allConnections.on(() => get(cb))
}
if (r.opened === true) onready(null)
else if (typeof r.ready === 'function') r.ready(onready)
else onready(null)
return swarm
function onready (err) {
if (swarm.destroyed) return
if (err) return swarm.destroy(err)
swarm.join(opts.discoveryKey || r.discoveryKey, {
announce: opts.announce !== false,
lookup: opts.lookup !== false
}, cb)
swarm.flush(() => {
allConnections.emit()
oneConnection.emit()
})
}
}