network.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. window.URL = window.URL || window.webkitURL;
  2. window.isRtcSupported = !!(window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection);
  3. class ServerConnection {
  4. constructor() {
  5. this._connect();
  6. Events.on('beforeunload', e => this._disconnect());
  7. Events.on('pagehide', e => this._disconnect());
  8. document.addEventListener('visibilitychange', e => this._onVisibilityChange());
  9. }
  10. _connect() {
  11. clearTimeout(this._reconnectTimer);
  12. if (this._isConnected() || this._isConnecting()) return;
  13. const ws = new WebSocket(this._endpoint());
  14. ws.binaryType = 'arraybuffer';
  15. ws.onopen = e => console.log('WS: server connected');
  16. ws.onmessage = e => this._onMessage(e.data);
  17. ws.onclose = e => this._onDisconnect();
  18. ws.onerror = e => console.error(e);
  19. this._socket = ws;
  20. }
  21. _onMessage(msg) {
  22. msg = JSON.parse(msg);
  23. console.log('WS:', msg);
  24. switch (msg.type) {
  25. case 'peers':
  26. Events.fire('peers', msg.peers);
  27. break;
  28. case 'peer-joined':
  29. Events.fire('peer-joined', msg.peer);
  30. break;
  31. case 'peer-left':
  32. Events.fire('peer-left', msg.peerId);
  33. break;
  34. case 'signal':
  35. Events.fire('signal', msg);
  36. break;
  37. case 'ping':
  38. this.send({ type: 'pong' });
  39. break;
  40. default:
  41. console.error('WS: unkown message type', msg);
  42. }
  43. }
  44. send(message) {
  45. if (!this._isConnected()) return;
  46. this._socket.send(JSON.stringify(message));
  47. }
  48. _endpoint() {
  49. // hack to detect if deployment or development environment
  50. const protocol = location.protocol.startsWith('https') ? 'wss' : 'ws';
  51. const webrtc = window.isRtcSupported ? '/webrtc' : '/fallback';
  52. const url = protocol + '://' + location.host + '/server' + webrtc;
  53. return url;
  54. }
  55. _disconnect() {
  56. this.send({ type: 'disconnect' });
  57. this._socket.onclose = null;
  58. this._socket.close();
  59. }
  60. _onDisconnect() {
  61. console.log('WS: server disconnected');
  62. Events.fire('notify-user', 'Connection lost. Retry in 5 seconds...');
  63. clearTimeout(this._reconnectTimer);
  64. this._reconnectTimer = setTimeout(_ => this._connect(), 5000);
  65. }
  66. _onVisibilityChange() {
  67. if (document.hidden) return;
  68. this._connect();
  69. }
  70. _isConnected() {
  71. return this._socket && this._socket.readyState === this._socket.OPEN;
  72. }
  73. _isConnecting() {
  74. return this._socket && this._socket.readyState === this._socket.CONNECTING;
  75. }
  76. }
  77. class Peer {
  78. constructor(serverConnection, peerId) {
  79. this._server = serverConnection;
  80. this._peerId = peerId;
  81. this._filesQueue = [];
  82. this._busy = false;
  83. }
  84. sendJSON(message) {
  85. this._send(JSON.stringify(message));
  86. }
  87. sendFiles(files) {
  88. for (let i = 0; i < files.length; i++) {
  89. this._filesQueue.push(files[i]);
  90. }
  91. if (this._busy) return;
  92. this._dequeueFile();
  93. }
  94. _dequeueFile() {
  95. if (!this._filesQueue.length) return;
  96. this._busy = true;
  97. const file = this._filesQueue.shift();
  98. this._sendFile(file);
  99. }
  100. _sendFile(file) {
  101. this.sendJSON({
  102. type: 'header',
  103. name: file.name,
  104. mime: file.type,
  105. size: file.size
  106. });
  107. this._chunker = new FileChunker(file,
  108. chunk => this._send(chunk),
  109. offset => this._onPartitionEnd(offset));
  110. this._chunker.nextPartition();
  111. }
  112. _onPartitionEnd(offset) {
  113. this.sendJSON({ type: 'partition', offset: offset });
  114. }
  115. _onReceivedPartitionEnd(offset) {
  116. this.sendJSON({ type: 'partition-received', offset: offset });
  117. }
  118. _sendNextPartition() {
  119. if (!this._chunker || this._chunker.isFileEnd()) return;
  120. this._chunker.nextPartition();
  121. }
  122. _sendProgress(progress) {
  123. this.sendJSON({ type: 'progress', progress: progress });
  124. }
  125. _onMessage(message) {
  126. if (typeof message !== 'string') {
  127. this._onChunkReceived(message);
  128. return;
  129. }
  130. message = JSON.parse(message);
  131. console.log('RTC:', message);
  132. switch (message.type) {
  133. case 'header':
  134. this._onFileHeader(message);
  135. break;
  136. case 'partition':
  137. this._onReceivedPartitionEnd(message);
  138. break;
  139. case 'partition-received':
  140. this._sendNextPartition();
  141. break;
  142. case 'progress':
  143. this._onDownloadProgress(message.progress);
  144. break;
  145. case 'transfer-complete':
  146. this._onTransferCompleted();
  147. break;
  148. case 'text':
  149. this._onTextReceived(message);
  150. break;
  151. }
  152. }
  153. _onFileHeader(header) {
  154. this._lastProgress = 0;
  155. this._digester = new FileDigester({
  156. name: header.name,
  157. mime: header.mime,
  158. size: header.size
  159. }, file => this._onFileReceived(file));
  160. }
  161. _onChunkReceived(chunk) {
  162. this._digester.unchunk(chunk);
  163. const progress = this._digester.progress;
  164. this._onDownloadProgress(progress);
  165. // occasionally notify sender about our progress
  166. if (progress - this._lastProgress < 0.01) return;
  167. this._lastProgress = progress;
  168. this._sendProgress(progress);
  169. }
  170. _onDownloadProgress(progress) {
  171. Events.fire('file-progress', { sender: this._peerId, progress: progress });
  172. }
  173. _onFileReceived(proxyFile) {
  174. Events.fire('file-received', proxyFile);
  175. this.sendJSON({ type: 'transfer-complete' });
  176. }
  177. _onTransferCompleted() {
  178. this._onDownloadProgress(1);
  179. this._reader = null;
  180. this._busy = false;
  181. this._dequeueFile();
  182. Events.fire('notify-user', 'File transfer completed.');
  183. }
  184. sendText(text) {
  185. const unescaped = btoa(unescape(encodeURIComponent(text)));
  186. this.sendJSON({ type: 'text', text: unescaped });
  187. }
  188. _onTextReceived(message) {
  189. const escaped = decodeURIComponent(escape(atob(message.text)));
  190. Events.fire('text-received', { text: escaped, sender: this._peerId });
  191. }
  192. }
  193. class RTCPeer extends Peer {
  194. constructor(serverConnection, peerId) {
  195. super(serverConnection, peerId);
  196. if (!peerId) return; // we will listen for a caller
  197. this._connect(peerId, true);
  198. }
  199. _connect(peerId, isCaller) {
  200. if (!this._conn) this._openConnection(peerId, isCaller);
  201. if (isCaller) {
  202. this._openChannel();
  203. } else {
  204. this._conn.ondatachannel = e => this._onChannelOpened(e);
  205. }
  206. }
  207. _openConnection(peerId, isCaller) {
  208. this._isCaller = isCaller;
  209. this._peerId = peerId;
  210. this._conn = new RTCPeerConnection(RTCPeer.config);
  211. this._conn.onicecandidate = e => this._onIceCandidate(e);
  212. this._conn.onconnectionstatechange = e => this._onConnectionStateChange(e);
  213. this._conn.oniceconnectionstatechange = e => this._onIceConnectionStateChange(e);
  214. }
  215. _openChannel() {
  216. const channel = this._conn.createDataChannel('data-channel', { reliable: true });
  217. channel.binaryType = 'arraybuffer';
  218. channel.onopen = e => this._onChannelOpened(e);
  219. this._conn.createOffer().then(d => this._onDescription(d)).catch(e => this._onError(e));
  220. }
  221. _onDescription(description) {
  222. // description.sdp = description.sdp.replace('b=AS:30', 'b=AS:1638400');
  223. this._conn.setLocalDescription(description)
  224. .then(_ => this._sendSignal({ sdp: description }))
  225. .catch(e => this._onError(e));
  226. }
  227. _onIceCandidate(event) {
  228. if (!event.candidate) return;
  229. this._sendSignal({ ice: event.candidate });
  230. }
  231. onServerMessage(message) {
  232. if (!this._conn) this._connect(message.sender, false);
  233. if (message.sdp) {
  234. this._conn.setRemoteDescription(new RTCSessionDescription(message.sdp))
  235. .then( _ => {
  236. if (message.sdp.type === 'offer') {
  237. return this._conn.createAnswer()
  238. .then(d => this._onDescription(d));
  239. }
  240. })
  241. .catch(e => this._onError(e));
  242. } else if (message.ice) {
  243. this._conn.addIceCandidate(new RTCIceCandidate(message.ice));
  244. }
  245. }
  246. _onChannelOpened(event) {
  247. console.log('RTC: channel opened with', this._peerId);
  248. const channel = event.channel || event.target;
  249. channel.onmessage = e => this._onMessage(e.data);
  250. channel.onclose = e => this._onChannelClosed();
  251. this._channel = channel;
  252. }
  253. _onChannelClosed() {
  254. console.log('RTC: channel closed', this._peerId);
  255. if (!this.isCaller) return;
  256. this._connect(this._peerId, true); // reopen the channel
  257. }
  258. _onConnectionStateChange(e) {
  259. console.log('RTC: state changed:', this._conn.connectionState);
  260. switch (this._conn.connectionState) {
  261. case 'disconnected':
  262. this._onChannelClosed();
  263. break;
  264. case 'failed':
  265. this._conn = null;
  266. this._onChannelClosed();
  267. break;
  268. }
  269. }
  270. _onIceConnectionStateChange() {
  271. switch (this._conn.iceConnectionState) {
  272. case 'failed':
  273. console.error('ICE Gathering failed');
  274. break;
  275. default:
  276. console.log('ICE Gathering', this._conn.iceConnectionState);
  277. }
  278. }
  279. _onError(error) {
  280. console.error(error);
  281. }
  282. _send(message) {
  283. if (!this._channel) return this.refresh();
  284. this._channel.send(message);
  285. }
  286. _sendSignal(signal) {
  287. signal.type = 'signal';
  288. signal.to = this._peerId;
  289. this._server.send(signal);
  290. }
  291. refresh() {
  292. // check if channel is open. otherwise create one
  293. if (this._isConnected() || this._isConnecting()) return;
  294. this._connect(this._peerId, this._isCaller);
  295. }
  296. _isConnected() {
  297. return this._channel && this._channel.readyState === 'open';
  298. }
  299. _isConnecting() {
  300. return this._channel && this._channel.readyState === 'connecting';
  301. }
  302. }
  303. class PeersManager {
  304. constructor(serverConnection) {
  305. this.peers = {};
  306. this._server = serverConnection;
  307. Events.on('signal', e => this._onMessage(e.detail));
  308. Events.on('peers', e => this._onPeers(e.detail));
  309. Events.on('files-selected', e => this._onFilesSelected(e.detail));
  310. Events.on('send-text', e => this._onSendText(e.detail));
  311. Events.on('peer-left', e => this._onPeerLeft(e.detail));
  312. }
  313. _onMessage(message) {
  314. if (!this.peers[message.sender]) {
  315. this.peers[message.sender] = new RTCPeer(this._server);
  316. }
  317. this.peers[message.sender].onServerMessage(message);
  318. }
  319. _onPeers(peers) {
  320. peers.forEach(peer => {
  321. if (this.peers[peer.id]) {
  322. this.peers[peer.id].refresh();
  323. return;
  324. }
  325. if (window.isRtcSupported && peer.rtcSupported) {
  326. this.peers[peer.id] = new RTCPeer(this._server, peer.id);
  327. } else {
  328. this.peers[peer.id] = new WSPeer(this._server, peer.id);
  329. }
  330. })
  331. }
  332. sendTo(peerId, message) {
  333. this.peers[peerId].send(message);
  334. }
  335. _onFilesSelected(message) {
  336. this.peers[message.to].sendFiles(message.files);
  337. }
  338. _onSendText(message) {
  339. this.peers[message.to].sendText(message.text);
  340. }
  341. _onPeerLeft(peerId) {
  342. const peer = this.peers[peerId];
  343. delete this.peers[peerId];
  344. if (!peer || !peer._peer) return;
  345. peer._peer.close();
  346. }
  347. }
  348. class WSPeer {
  349. _send(message) {
  350. message.to = this._peerId;
  351. this._server.send(message);
  352. }
  353. }
  354. class FileChunker {
  355. constructor(file, onChunk, onPartitionEnd) {
  356. this._chunkSize = 64000; // 64 KB
  357. this._maxPartitionSize = 1e6; // 1 MB
  358. this._offset = 0;
  359. this._partitionSize = 0;
  360. this._file = file;
  361. this._onChunk = onChunk;
  362. this._onPartitionEnd = onPartitionEnd;
  363. this._reader = new FileReader();
  364. this._reader.addEventListener('load', e => this._onChunkRead(e.target.result));
  365. }
  366. nextPartition() {
  367. this._partitionSize = 0;
  368. this._readChunk();
  369. }
  370. _readChunk() {
  371. const chunk = this._file.slice(this._offset, this._offset + this._chunkSize);
  372. this._reader.readAsArrayBuffer(chunk);
  373. }
  374. _onChunkRead(chunk) {
  375. this._offset += chunk.byteLength;
  376. this._partitionSize += chunk.byteLength;
  377. this._onChunk(chunk);
  378. if (this._isPartitionEnd() || this.isFileEnd()) {
  379. this._onPartitionEnd(this._offset);
  380. return;
  381. }
  382. this._readChunk();
  383. }
  384. repeatPartition() {
  385. this._offset -= this._partitionSize;
  386. this._nextPartition();
  387. }
  388. _isPartitionEnd() {
  389. return this._partitionSize >= this._maxPartitionSize;
  390. }
  391. isFileEnd() {
  392. return this._offset > this._file.size;
  393. }
  394. get progress() {
  395. return this._offset / this._file.size;
  396. }
  397. }
  398. class FileDigester {
  399. constructor(meta, callback) {
  400. this._buffer = [];
  401. this._bytesReceived = 0;
  402. this._size = meta.size;
  403. this._mime = meta.mime || 'application/octet-stream';
  404. this._name = meta.name;
  405. this._callback = callback;
  406. }
  407. unchunk(chunk) {
  408. this._buffer.push(chunk);
  409. this._bytesReceived += chunk.byteLength || chunk.size;
  410. const totalChunks = this._buffer.length;
  411. this.progress = this._bytesReceived / this._size;
  412. if (this._bytesReceived < this._size) return;
  413. // we are done
  414. let blob = new Blob(this._buffer, { type: this._mime });
  415. this._callback({
  416. name: this._name,
  417. mime: this._mime,
  418. size: this._size,
  419. blob: blob
  420. });
  421. }
  422. }
  423. class Events {
  424. static fire(type, detail) {
  425. window.dispatchEvent(new CustomEvent(type, { detail: detail }));
  426. }
  427. static on(type, callback) {
  428. return window.addEventListener(type, callback, false);
  429. }
  430. }
  431. RTCPeer.config = {
  432. 'iceServers': [{
  433. urls: 'stun:stun.l.google.com:19302'
  434. }, {
  435. urls: 'turn:192.158.29.39:3478?transport=tcp',
  436. credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
  437. username: '28224511:1379330808'
  438. }]
  439. }