-
Notifications
You must be signed in to change notification settings - Fork 178
/
index.js
257 lines (227 loc) · 6.75 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
window.myDebug = require('debug')
var Peer = require('simple-peer')
var Emitter = require('component-emitter')
var parser = require('socket.io-p2p-parser')
var toArray = require('to-array')
var hasBin = require('has-binary')
var bind = require('component-bind')
var debug = require('debug')('socket')
var hat = require('hat')
var extend = require('extend.js')
var rtcSupport = require('webrtcsupport')
var emitfn = Emitter.prototype.emit
function Socketiop2p (socket, opts, cb) {
var self = this
self.useSockets = true
self.usePeerConnection = false
self.decoder = new parser.Decoder(this)
self.decoder.on('decoded', bind(this, this.ondecoded))
self.socket = socket
self.cb = cb
self._peers = {}
self.readyPeers = 0
self.ready = false
self._peerEvents = {
upgrade: 1,
error: 1,
peer_signal: 1,
peer_ready: 1,
stream: 1
}
var defaultOpts = {
autoUpgrade: true,
numClients: 5
}
self.opts = extend(defaultOpts, (opts || {}))
self.peerOpts = self.opts.peerOpts || {}
self.numConnectedClients
socket.on('numClients', function (numClients) {
self.peerId = socket.io.engine.id
self.numConnectedClients = numClients
if (rtcSupport.supportDataChannel) {
generateOffers(function (offers) {
var offerObj = {
offers: offers,
fromPeerId: self.peerId
}
socket.emit('offers', offerObj)
})
}
function generateOffers (cb) {
var offers = []
for (var i = 0; i < self.opts.numClients; ++i) {
generateOffer()
}
function generateOffer () {
var offerId = hat(160)
var peerOpts = extend(self.peerOpts, {initiator: true})
var peer = self._peers[offerId] = new Peer(peerOpts)
peer.setMaxListeners(50)
self.setupPeerEvents(peer)
peer.on('signal', function (offer) {
offers.push({
offer: offer,
offerId: offerId
})
checkDone()
})
peer.on('error', function (err) {
emitfn.call(this, 'peer-error', err)
debug('Error in peer %s', err)
})
}
function checkDone () {
if (offers.length === self.opts.numClients) {
debug('generated %s offers', self.opts.numClients)
cb(offers)
}
}
}
})
socket.on('offer', function (data) {
var peerOpts = extend(self.peerOpts, {initiator: false})
var peer = self._peers[data.fromPeerId] = new Peer(peerOpts)
self.numConnectedClients++
peer.setMaxListeners(50)
self.setupPeerEvents(peer)
peer.on('signal', function (signalData) {
var signalObj = {
signal: signalData,
offerId: data.offerId,
fromPeerId: self.peerId,
toPeerId: data.fromPeerId
}
socket.emit('peer-signal', signalObj)
})
peer.on('error', function (err) {
emitfn.call(this, 'peer-error', err)
debug('Error in peer %s', err)
})
peer.signal(data.offer)
})
socket.on('peer-signal', function (data) {
// Select peer from offerId if exists
var peer = self._peers[data.offerId] || self._peers[data.fromPeerId]
if (peer !== undefined) {
peer.on('signal', function signal (signalData) {
var signalObj = {
signal: signalData,
offerId: data.offerId,
fromPeerId: self.peerId,
toPeerId: data.fromPeerId
}
socket.emit('peer-signal', signalObj)
})
peer.signal(data.signal)
}
})
self.on('peer_ready', function (peer) {
self.readyPeers++
if (self.readyPeers >= self.numConnectedClients && !self.ready) {
self.ready = true
self.emit('upgrade')
}
})
self.on('upgrade', function () {
if (self.opts.autoUpgrade) self.usePeerConnection = true
if (typeof self.cb === 'function') self.cb()
})
}
Emitter(Socketiop2p.prototype)
Socketiop2p.prototype.setupPeerEvents = function (peer) {
var self = this
peer.on('connect', function (peer) {
self.emit('peer_ready', peer)
})
peer.on('data', function (data) {
if (this.destroyed) return
self.decoder.add(data)
})
peer.on('stream', function (stream) {
self.emit('stream', stream)
})
}
/**
* Overwride the inheritted 'on' method to add a listener to the socket instance
* that emits the event on the Socketio event loop
**/
Socketiop2p.prototype.on = function (type, listener) {
var self = this
this.socket.addEventListener(type, function (data) {
emitfn.call(self, type, data)
})
this.addEventListener(type, listener)
}
Socketiop2p.prototype.emit = function (data, cb) {
var self = this
var argsObj = cb || {}
var encoder = new parser.Encoder()
if (this._peerEvents.hasOwnProperty(data) || argsObj.fromSocket) {
emitfn.apply(this, arguments)
} else if (this.usePeerConnection || !this.useSockets) {
var args = toArray(arguments)
var parserType = parser.EVENT // default
if (hasBin(args)) { parserType = parser.BINARY_EVENT } // binary
var packet = { type: parserType, data: args }
encoder.encode(packet, function (encodedPackets) {
if (encodedPackets[1] instanceof ArrayBuffer) {
self._sendArray(encodedPackets)
} else if (encodedPackets) {
for (var i = 0; i < encodedPackets.length; i++) {
self._send(encodedPackets[i])
}
} else {
throw new Error('Encoding error')
}
})
} else {
this.socket.emit(data, cb)
}
}
/**
* If the second packet is a binary attachment,
* swap out the attachment number for the number of chunks in the array
* before sending the new packet and chunks
**/
Socketiop2p.prototype._sendArray = function (arr) {
var firstPacket = arr[0]
var interval = 5000
var arrLength = arr[1].byteLength
var nChunks = Math.ceil(arrLength / interval)
var packetData = firstPacket.substr(0, 1) + nChunks + firstPacket.substr(firstPacket.indexOf('-'))
this._send(packetData)
this.binarySlice(arr[1], interval, this._send)
}
Socketiop2p.prototype._send = function (data) {
var self = this
for (var peerId in self._peers) {
var peer = self._peers[peerId]
if (peer._channelReady) {
peer.send(data)
}
}
}
Socketiop2p.prototype.binarySlice = function (arr, interval, callback) {
for (var start = 0; start < arr.byteLength; start += interval) {
var chunk = arr.slice(start, start + interval)
callback.call(this, chunk)
}
}
Socketiop2p.prototype.ondecoded = function (packet) {
var args = packet.data || []
emitfn.apply(this, args)
}
Socketiop2p.prototype.disconnect = function () {
for (var peerId in this._peers) {
var peer = this._peers[peerId]
peer.destroy()
this.socket.disconnect()
}
}
/**
* Use peerConnection instead of socket.io one.
**/
Socketiop2p.prototype.upgrade = function () {
this.usePeerConnection = true
}
module.exports = Socketiop2p