network.js 15 KB

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