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. 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 + '/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', { reliable: true });
  220. channel.binaryType = 'arraybuffer';
  221. channel.onopen = e => this._onChannelOpened(e);
  222. this._conn.createOffer().then(d => this._onDescription(d)).catch(e => this._onError(e));
  223. }
  224. _onDescription(description) {
  225. // description.sdp = description.sdp.replace('b=AS:30', 'b=AS:1638400');
  226. this._conn.setLocalDescription(description)
  227. .then(_ => this._sendSignal({ sdp: description }))
  228. .catch(e => this._onError(e));
  229. }
  230. _onIceCandidate(event) {
  231. if (!event.candidate) return;
  232. this._sendSignal({ ice: event.candidate });
  233. }
  234. onServerMessage(message) {
  235. if (!this._conn) this._connect(message.sender, false);
  236. if (message.sdp) {
  237. this._conn.setRemoteDescription(new RTCSessionDescription(message.sdp))
  238. .then( _ => {
  239. if (message.sdp.type === 'offer') {
  240. return this._conn.createAnswer()
  241. .then(d => this._onDescription(d));
  242. }
  243. })
  244. .catch(e => this._onError(e));
  245. } else if (message.ice) {
  246. this._conn.addIceCandidate(new RTCIceCandidate(message.ice));
  247. }
  248. }
  249. _onChannelOpened(event) {
  250. console.log('RTC: channel opened with', this._peerId);
  251. const channel = event.channel || event.target;
  252. channel.onmessage = e => this._onMessage(e.data);
  253. channel.onclose = e => this._onChannelClosed();
  254. this._channel = channel;
  255. }
  256. _onChannelClosed() {
  257. console.log('RTC: channel closed', this._peerId);
  258. if (!this.isCaller) return;
  259. this._connect(this._peerId, true); // reopen the channel
  260. }
  261. _onConnectionStateChange(e) {
  262. console.log('RTC: state changed:', this._conn.connectionState);
  263. switch (this._conn.connectionState) {
  264. case 'disconnected':
  265. this._onChannelClosed();
  266. break;
  267. case 'failed':
  268. this._conn = null;
  269. this._onChannelClosed();
  270. break;
  271. }
  272. }
  273. _onIceConnectionStateChange() {
  274. switch (this._conn.iceConnectionState) {
  275. case 'failed':
  276. console.error('ICE Gathering failed');
  277. break;
  278. default:
  279. console.log('ICE Gathering', this._conn.iceConnectionState);
  280. }
  281. }
  282. _onError(error) {
  283. console.error(error);
  284. }
  285. _send(message) {
  286. if (!this._channel) return this.refresh();
  287. this._channel.send(message);
  288. }
  289. _sendSignal(signal) {
  290. signal.type = 'signal';
  291. signal.to = this._peerId;
  292. this._server.send(signal);
  293. }
  294. refresh() {
  295. // check if channel is open. otherwise create one
  296. if (this._isConnected() || this._isConnecting()) return;
  297. this._connect(this._peerId, this._isCaller);
  298. }
  299. _isConnected() {
  300. return this._channel && this._channel.readyState === 'open';
  301. }
  302. _isConnecting() {
  303. return this._channel && this._channel.readyState === 'connecting';
  304. }
  305. }
  306. class PeersManager {
  307. constructor(serverConnection) {
  308. this.peers = {};
  309. this._server = serverConnection;
  310. Events.on('signal', e => this._onMessage(e.detail));
  311. Events.on('peers', e => this._onPeers(e.detail));
  312. Events.on('files-selected', e => this._onFilesSelected(e.detail));
  313. Events.on('send-text', e => this._onSendText(e.detail));
  314. Events.on('peer-left', e => this._onPeerLeft(e.detail));
  315. }
  316. _onMessage(message) {
  317. if (!this.peers[message.sender]) {
  318. this.peers[message.sender] = new RTCPeer(this._server);
  319. }
  320. this.peers[message.sender].onServerMessage(message);
  321. }
  322. _onPeers(peers) {
  323. peers.forEach(peer => {
  324. if (this.peers[peer.id]) {
  325. this.peers[peer.id].refresh();
  326. return;
  327. }
  328. if (window.isRtcSupported && peer.rtcSupported) {
  329. this.peers[peer.id] = new RTCPeer(this._server, peer.id);
  330. } else {
  331. this.peers[peer.id] = new WSPeer(this._server, peer.id);
  332. }
  333. })
  334. }
  335. sendTo(peerId, message) {
  336. this.peers[peerId].send(message);
  337. }
  338. _onFilesSelected(message) {
  339. this.peers[message.to].sendFiles(message.files);
  340. }
  341. _onSendText(message) {
  342. this.peers[message.to].sendText(message.text);
  343. }
  344. _onPeerLeft(peerId) {
  345. const peer = this.peers[peerId];
  346. delete this.peers[peerId];
  347. if (!peer || !peer._peer) return;
  348. peer._peer.close();
  349. }
  350. }
  351. class WSPeer {
  352. _send(message) {
  353. message.to = this._peerId;
  354. this._server.send(message);
  355. }
  356. }
  357. class FileChunker {
  358. constructor(file, onChunk, onPartitionEnd) {
  359. this._chunkSize = 64000; // 64 KB
  360. this._maxPartitionSize = 1e6; // 1 MB
  361. this._offset = 0;
  362. this._partitionSize = 0;
  363. this._file = file;
  364. this._onChunk = onChunk;
  365. this._onPartitionEnd = onPartitionEnd;
  366. this._reader = new FileReader();
  367. this._reader.addEventListener('load', e => this._onChunkRead(e.target.result));
  368. }
  369. nextPartition() {
  370. this._partitionSize = 0;
  371. this._readChunk();
  372. }
  373. _readChunk() {
  374. const chunk = this._file.slice(this._offset, this._offset + this._chunkSize);
  375. this._reader.readAsArrayBuffer(chunk);
  376. }
  377. _onChunkRead(chunk) {
  378. this._offset += chunk.byteLength;
  379. this._partitionSize += chunk.byteLength;
  380. this._onChunk(chunk);
  381. if (this._isPartitionEnd() || this.isFileEnd()) {
  382. this._onPartitionEnd(this._offset);
  383. return;
  384. }
  385. this._readChunk();
  386. }
  387. repeatPartition() {
  388. this._offset -= this._partitionSize;
  389. this._nextPartition();
  390. }
  391. _isPartitionEnd() {
  392. return this._partitionSize >= this._maxPartitionSize;
  393. }
  394. isFileEnd() {
  395. return this._offset > this._file.size;
  396. }
  397. get progress() {
  398. return this._offset / this._file.size;
  399. }
  400. }
  401. class FileDigester {
  402. constructor(meta, callback) {
  403. this._buffer = [];
  404. this._bytesReceived = 0;
  405. this._size = meta.size;
  406. this._mime = meta.mime || 'application/octet-stream';
  407. this._name = meta.name;
  408. this._callback = callback;
  409. }
  410. unchunk(chunk) {
  411. this._buffer.push(chunk);
  412. this._bytesReceived += chunk.byteLength || chunk.size;
  413. const totalChunks = this._buffer.length;
  414. this.progress = this._bytesReceived / this._size;
  415. if (this._bytesReceived < this._size) return;
  416. // we are done
  417. let blob = new Blob(this._buffer, { type: this._mime });
  418. this._callback({
  419. name: this._name,
  420. mime: this._mime,
  421. size: this._size,
  422. blob: blob
  423. });
  424. }
  425. }
  426. class Events {
  427. static fire(type, detail) {
  428. window.dispatchEvent(new CustomEvent(type, { detail: detail }));
  429. }
  430. static on(type, callback) {
  431. return window.addEventListener(type, callback, false);
  432. }
  433. }
  434. RTCPeer.config = {
  435. 'sdpSemantics': 'unified-plan',
  436. 'iceServers': [{
  437. urls: 'stun:stun.l.google.com:19302'
  438. }]
  439. }