network.js 13 KB

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