network.js 14 KB

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