| 2 | window.isRtcSupported = !!(window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection); |
| 3 | |
| 4 | class ServerConnection { |
| 5 | |
| 6 | constructor() { |
| 7 | this._connect(); |
| 8 | Events.on('beforeunload', e => this._disconnect()); |
| 9 | Events.on('pagehide', e => this._disconnect()); |
| 10 | document.addEventListener('visibilitychange', e => this._onVisibilityChange()); |
| 11 | } |
| 12 | |
| 13 | _connect() { |
| 14 | clearTimeout(this._reconnectTimer); |
| 15 | if (this._isConnected() || this._isConnecting()) return; |
| 16 | const ws = new WebSocket(this._endpoint()); |
| 17 | ws.binaryType = 'arraybuffer'; |
| 18 | ws.onopen = e => console.log('WS: server connected'); |
| 19 | ws.onmessage = e => this._onMessage(e.data); |
| 20 | ws.onclose = e => this._onDisconnect(); |
| 21 | ws.onerror = e => console.error(e); |
| 22 | this._socket = ws; |
| 23 | } |
| 24 | |
| 25 | _onMessage(msg) { |
| 26 | msg = JSON.parse(msg); |
| 27 | console.log('WS:', msg); |
| 28 | switch (msg.type) { |
| 29 | case 'peers': |
| 30 | Events.fire('peers', msg.peers); |
| 31 | break; |
| 32 | case 'peer-joined': |
| 33 | Events.fire('peer-joined', msg.peer); |
| 34 | break; |
| 35 | case 'peer-left': |
| 36 | Events.fire('peer-left', msg.peerId); |
| 37 | break; |
| 38 | case 'signal': |
| 39 | Events.fire('signal', msg); |
| 40 | break; |
| 41 | case 'ping': |
| 42 | this.send({ type: 'pong' }); |
| 43 | break; |
| 44 | case 'display-name': |
| 45 | Events.fire('display-name', msg); |
| 46 | break; |
| 47 | default: |
| 48 | console.error('WS: unkown message type', msg); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | send(message) { |
| 53 | if (!this._isConnected()) return; |
| 54 | this._socket.send(JSON.stringify(message)); |
| 55 | } |
| 56 | |
| 57 | _endpoint() { |
| 58 | // hack to detect if deployment or development environment |
| 59 | const protocol = location.protocol.startsWith('https') ? 'wss' : 'ws'; |
| 60 | const webrtc = window.isRtcSupported ? '/webrtc' : '/fallback'; |
| 61 | const url = protocol + '://' + location.host + location.pathname + 'server' + webrtc; |
nothing calls this directly
no outgoing calls
no test coverage detected