network.js 14 KB

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