-
Notifications
You must be signed in to change notification settings - Fork 635
/
web-rtc.js
319 lines (262 loc) · 8.57 KB
/
web-rtc.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// TODO:
// - provide TURN server config once it's possible to create rooms with custom names
// - use Ember.Object.extend()
import $ from 'jquery';
import File from './file';
const WebRTC = function (id, options) {
const defaults = {
config: { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] },
debug: 3,
};
this.conn = new window.Peer(id, $.extend(defaults, options));
this.files = {
outgoing: {},
incoming: {},
};
// Listen for incoming connections
this.conn.on('connection', (connection) => {
$.publish('incoming_peer_connection.p2p', { connection });
connection.on('open', () => {
console.log('Peer:\t Data channel connection opened: ', connection);
$.publish('incoming_dc_connection.p2p', { connection });
});
connection.on('error', (error) => {
console.log('Peer:\t Data channel connection error', error);
$.publish('incoming_dc_connection_error.p2p', {
connection,
error,
});
});
this._onConnection(connection);
});
this.conn.on('close', () => {
console.log('Peer:\t Connection to server closed.');
});
this.conn.on('error', (error) => {
console.log('Peer:\t Error while connecting to server: ', error);
});
};
WebRTC.CHUNK_MTU = 16000;
WebRTC.CHUNKS_PER_ACK = 64;
WebRTC.prototype.connect = function (id) {
const connection = this.conn.connect(id, {
label: 'file',
reliable: true,
serialization: 'none', // we handle serialization ourselves
});
connection.on('open', () => {
console.log('Peer:\t Data channel connection opened: ', connection);
$.publish('outgoing_dc_connection.p2p', { connection });
});
connection.on('error', (error) => {
console.log('Peer:\t Data channel connection error', error);
$.publish('outgoing_dc_connection_error.p2p', {
connection,
error,
});
});
$.publish('outgoing_peer_connection.p2p', { connection });
this._onConnection(connection);
};
WebRTC.prototype._onConnection = function (connection) {
const self = this;
console.log('Peer:\t Opening data channel connection...', connection);
connection.on('data', (data) => {
// Lame type check
if (data.byteLength !== undefined) {
// ArrayBuffer
self._onBinaryData(data, connection);
} else {
// JSON string
self._onJSONData(JSON.parse(data), connection);
}
});
connection.on('close', () => {
$.publish('disconnected.p2p', { connection });
console.log('Peer:\t P2P connection closed: ', connection);
});
};
WebRTC.prototype._onBinaryData = function (data, connection) {
const self = this;
const incoming = this.files.incoming[connection.peer];
const { info, file, block, receivedChunkNum } = incoming;
const chunksPerAck = WebRTC.CHUNKS_PER_ACK;
// TODO move it after requesting a new block to speed things up
connection.emit(
'receiving_progress',
(receivedChunkNum + 1) / info.chunksTotal,
);
// console.log('Got chunk no ' + (receivedChunkNum + 1) + ' out of ' + info.chunksTotal);
block.push(data);
incoming.receivedChunkNum = receivedChunkNum + 1;
const nextChunkNum = incoming.receivedChunkNum;
const lastChunkInFile = receivedChunkNum === info.chunksTotal - 1;
const lastChunkInBlock =
receivedChunkNum > 0 && (receivedChunkNum + 1) % chunksPerAck === 0;
if (lastChunkInFile || lastChunkInBlock) {
file.append(block).then(() => {
if (lastChunkInFile) {
file.save();
$.publish('file_received.p2p', {
blob: file,
info,
connection,
});
} else {
// console.log('Requesting block starting at: ' + (nextChunkNum));
incoming.block = [];
self._requestFileBlock(connection, nextChunkNum);
}
});
}
};
WebRTC.prototype._onJSONData = function (data, connection) {
switch (data.type) {
case 'info': {
const info = data.payload;
$.publish('info.p2p', {
connection,
info,
});
// Store incoming file info for later
this.files.incoming[connection.peer] = {
info,
file: null,
block: [],
receivedChunkNum: 0,
};
console.log('Peer:\t File info: ', data);
break;
}
case 'cancel': {
$.publish('file_canceled.p2p', {
connection,
});
console.log('Peer:\t Sender canceled file transfer');
break;
}
case 'response': {
const response = data.payload;
// If recipient rejected the file, delete stored file
if (!response) {
delete this.files.outgoing[connection.peer];
}
$.publish('response.p2p', {
connection,
response,
});
console.log('Peer:\t File response: ', data);
break;
}
case 'block_request': {
const { file } = this.files.outgoing[connection.peer];
// console.log('Peer:\t Block request: ', data.payload);
this._sendBlock(connection, file, data.payload);
break;
}
default:
console.log('Peer:\t Unknown message: ', data);
}
};
WebRTC.prototype.getFileInfo = function (file) {
return {
lastModifiedDate: file.lastModifiedDate,
name: file.name,
size: file.size,
type: file.type,
chunksTotal: Math.ceil(file.size / WebRTC.CHUNK_MTU),
};
};
WebRTC.prototype.sendFileInfo = function (connection, info) {
const message = {
type: 'info',
payload: info,
};
connection.send(JSON.stringify(message));
};
WebRTC.prototype.sendCancelRequest = function (connection) {
const message = {
type: 'cancel',
};
connection.send(JSON.stringify(message));
};
WebRTC.prototype.sendFileResponse = function (connection, response) {
const message = {
type: 'response',
payload: response,
};
if (response) {
// If recipient accepted the file, request required space to store the file on HTML5 filesystem
const incoming = this.files.incoming[connection.peer];
const { info } = incoming;
new File({ name: info.name, size: info.size, type: info.type }).then(
(file) => {
incoming.file = file;
connection.send(JSON.stringify(message));
},
);
} else {
// Otherwise, delete stored file info
delete this.files.incoming[connection.peer];
connection.send(JSON.stringify(message));
}
};
WebRTC.prototype.sendFile = function (connection, file) {
// Save the file for later
this.files.outgoing[connection.peer] = {
file,
info: this.getFileInfo(file),
};
// Send the first block. Next ones will be requested by recipient.
this._sendBlock(connection, file, 0);
};
WebRTC.prototype._requestFileBlock = function (connection, chunkNum) {
const message = {
type: 'block_request',
payload: chunkNum,
};
connection.send(JSON.stringify(message));
};
WebRTC.prototype._sendBlock = function (connection, file, beginChunkNum) {
const { info } = this.files.outgoing[connection.peer];
const chunkSize = WebRTC.CHUNK_MTU;
const chunksPerAck = WebRTC.CHUNKS_PER_ACK;
const remainingChunks = info.chunksTotal - beginChunkNum;
const chunksToSend = Math.min(remainingChunks, chunksPerAck);
const endChunkNum = beginChunkNum + chunksToSend - 1;
const blockBegin = beginChunkNum * chunkSize;
const blockEnd = endChunkNum * chunkSize + chunkSize;
const reader = new FileReader();
let chunkNum;
// Read the whole block from file
const blockBlob = file.slice(blockBegin, blockEnd);
// console.log('Sending block: start chunk: ' + beginChunkNum + ' end chunk: ' + endChunkNum);
// console.log('Sending block: start byte : ' + begin + ' end byte : ' + end);
reader.onload = function (event) {
if (reader.readyState === FileReader.DONE) {
const blockBuffer = event.target.result;
for (
chunkNum = beginChunkNum;
chunkNum < endChunkNum + 1;
chunkNum += 1
) {
// Send each chunk (begin index is inclusive, end index is exclusive)
const bufferBegin = (chunkNum % chunksPerAck) * chunkSize;
const bufferEnd = Math.min(
bufferBegin + chunkSize,
blockBuffer.byteLength,
);
const chunkBuffer = blockBuffer.slice(bufferBegin, bufferEnd);
connection.send(chunkBuffer);
// console.log('Sent chunk: start byte: ' + begin + ' end byte: ' + end + ' length: ' + chunkBuffer.byteLength);
// console.log('Sent chunk no ' + (chunkNum + 1) + ' out of ' + info.chunksTotal);
connection.emit('sending_progress', (chunkNum + 1) / info.chunksTotal);
}
if (endChunkNum === info.chunksTotal - 1) {
$.publish('file_sent.p2p', { connection });
}
}
};
reader.readAsArrayBuffer(blockBlob);
};
export default WebRTC;