| 15 | const { uniqueNamesGenerator, animals, colors } = require('unique-names-generator'); |
| 16 | |
| 17 | class SnapdropServer { |
| 18 | |
| 19 | constructor(port) { |
| 20 | const WebSocket = require('ws'); |
| 21 | this._wss = new WebSocket.Server({ port: port }); |
| 22 | this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request))); |
| 23 | this._wss.on('headers', (headers, response) => this._onHeaders(headers, response)); |
| 24 | |
| 25 | this._rooms = {}; |
| 26 | |
| 27 | console.log('Snapdrop is running on port', port); |
| 28 | } |
| 29 | |
| 30 | _onConnection(peer) { |
| 31 | this._joinRoom(peer); |
| 32 | peer.socket.on('message', message => this._onMessage(peer, message)); |
| 33 | peer.socket.on('error', console.error); |
| 34 | this._keepAlive(peer); |
| 35 | |
| 36 | // send displayName |
| 37 | this._send(peer, { |
| 38 | type: 'display-name', |
| 39 | message: { |
| 40 | displayName: peer.name.displayName, |
| 41 | deviceName: peer.name.deviceName |
| 42 | } |
| 43 | }); |
| 44 | } |
| 45 | |
| 46 | _onHeaders(headers, response) { |
| 47 | if (response.headers.cookie && response.headers.cookie.indexOf('peerid=') > -1) return; |
| 48 | response.peerId = Peer.uuid(); |
| 49 | headers.push('Set-Cookie: peerid=' + response.peerId + "; SameSite=Strict; Secure"); |
| 50 | } |
| 51 | |
| 52 | _onMessage(sender, message) { |
| 53 | // Try to parse message |
| 54 | try { |
| 55 | message = JSON.parse(message); |
| 56 | } catch (e) { |
| 57 | return; // TODO: handle malformed JSON |
| 58 | } |
| 59 | |
| 60 | switch (message.type) { |
| 61 | case 'disconnect': |
| 62 | this._leaveRoom(sender); |
| 63 | break; |
| 64 | case 'pong': |
| 65 | sender.lastBeat = Date.now(); |
| 66 | break; |
| 67 | } |
| 68 | |
| 69 | // relay message to recipient |
| 70 | if (message.to && this._rooms[sender.ip]) { |
| 71 | const recipientId = message.to; // TODO: sanitize |
| 72 | const recipient = this._rooms[sender.ip][recipientId]; |
| 73 | delete message.to; |
| 74 | // add sender id |
nothing calls this directly
no outgoing calls
no test coverage detected