index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. const parser = require('ua-parser-js');
  2. class SnapdropServer {
  3. constructor(port) {
  4. const WebSocket = require('ws');
  5. this._wss = new WebSocket.Server({
  6. port: port
  7. });
  8. this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request)));
  9. this._wss.on('headers', (headers, response) => this._onHeaders(headers, response));
  10. this._rooms = {};
  11. console.log('Snapdrop is running on port', port);
  12. }
  13. _onConnection(peer) {
  14. this._joinRoom(peer);
  15. peer.socket.on('message', message => this._onMessage(peer, message));
  16. this._keepAlive(peer);
  17. }
  18. _onHeaders(headers, response) {
  19. if (response.headers.cookie && response.headers.cookie.indexOf('peerid=') > -1) return;
  20. response.peerId = Peer.uuid();
  21. headers.push('Set-Cookie: peerid=' + response.peerId);
  22. }
  23. _onMessage(sender, message) {
  24. message = JSON.parse(message);
  25. switch (message.type) {
  26. case 'disconnect':
  27. this._leaveRoom(sender);
  28. break;
  29. case 'pong':
  30. sender.lastBeat = Date.now();
  31. break;
  32. }
  33. // relay message to recipient
  34. if (message.to && this._rooms[sender.ip]) {
  35. const recipientId = message.to; // TODO: sanitize
  36. const recipient = this._rooms[sender.ip][recipientId];
  37. delete message.to;
  38. // add sender id
  39. message.sender = sender.id;
  40. this._send(recipient, message);
  41. return;
  42. }
  43. }
  44. _joinRoom(peer) {
  45. // if room doesn't exist, create it
  46. if (!this._rooms[peer.ip]) {
  47. this._rooms[peer.ip] = {};
  48. }
  49. // console.log(peer.id, ' joined the room', peer.ip);
  50. // notify all other peers
  51. for (const otherPeerId in this._rooms[peer.ip]) {
  52. const otherPeer = this._rooms[peer.ip][otherPeerId];
  53. this._send(otherPeer, {
  54. type: 'peer-joined',
  55. peer: peer.getInfo()
  56. });
  57. }
  58. // notify peer about the other peers
  59. const otherPeers = [];
  60. for (const otherPeerId in this._rooms[peer.ip]) {
  61. otherPeers.push(this._rooms[peer.ip][otherPeerId].getInfo());
  62. }
  63. this._send(peer, {
  64. type: 'peers',
  65. peers: otherPeers
  66. });
  67. // add peer to room
  68. this._rooms[peer.ip][peer.id] = peer;
  69. }
  70. _leaveRoom(peer) {
  71. if (!this._rooms[peer.ip] || !this._rooms[peer.ip][peer.id]) return;
  72. this._cancelKeepAlive(this._rooms[peer.ip][peer.id]);
  73. // delete the peer
  74. delete this._rooms[peer.ip][peer.id];
  75. peer.socket.terminate();
  76. //if room is empty, delete the room
  77. if (!Object.keys(this._rooms[peer.ip]).length) {
  78. delete this._rooms[peer.ip];
  79. } else {
  80. // notify all other peers
  81. for (const otherPeerId in this._rooms[peer.ip]) {
  82. const otherPeer = this._rooms[peer.ip][otherPeerId];
  83. this._send(otherPeer, {
  84. type: 'peer-left',
  85. peerId: peer.id
  86. });
  87. }
  88. }
  89. }
  90. _send(peer, message) {
  91. if (!peer) return console.error('undefined peer');
  92. if (this._wss.readyState !== this._wss.OPEN) return console.error('Socket is closed');
  93. message = JSON.stringify(message);
  94. peer.socket.send(message, error => console.log(error));
  95. }
  96. _keepAlive(peer) {
  97. this._cancelKeepAlive(peer);
  98. var timeout = 10000;
  99. if (!peer.lastBeat) {
  100. peer.lastBeat = Date.now();
  101. }
  102. if (Date.now() - peer.lastBeat > 2 * timeout) {
  103. this._leaveRoom(peer);
  104. return;
  105. }
  106. this._send(peer, { type: 'ping' });
  107. peer.timerId = setTimeout(() => this._keepAlive(peer), timeout);
  108. }
  109. _cancelKeepAlive(peer) {
  110. if (peer && peer.timerId) {
  111. clearTimeout(peer.timerId);
  112. }
  113. }
  114. }
  115. class Peer {
  116. constructor(socket, request) {
  117. // set socket
  118. this.socket = socket;
  119. // set remote ip
  120. if (request.headers['x-forwarded-for'])
  121. this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
  122. else
  123. this.ip = request.connection.remoteAddress;
  124. if (request.peerId) {
  125. this.id = request.peerId;
  126. } else {
  127. this.id = request.headers.cookie.replace('peerid=', '');
  128. }
  129. // set peer id
  130. // is WebRTC supported ?
  131. this.rtcSupported = request.url.indexOf('webrtc') > -1;
  132. // set name
  133. this.setName(request);
  134. // for keepalive
  135. this.timerId = 0;
  136. this.lastBeat = Date.now();
  137. }
  138. // return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  139. static uuid() {
  140. let uuid = '',
  141. ii;
  142. for (ii = 0; ii < 32; ii += 1) {
  143. switch (ii) {
  144. case 8:
  145. case 20:
  146. uuid += '-';
  147. uuid += (Math.random() * 16 | 0).toString(16);
  148. break;
  149. case 12:
  150. uuid += '-';
  151. uuid += '4';
  152. break;
  153. case 16:
  154. uuid += '-';
  155. uuid += (Math.random() * 4 | 8).toString(16);
  156. break;
  157. default:
  158. uuid += (Math.random() * 16 | 0).toString(16);
  159. }
  160. }
  161. return uuid;
  162. };
  163. toString() {
  164. return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
  165. }
  166. setName(req) {
  167. var ua = parser(req.headers['user-agent']);
  168. this.name = {
  169. model: ua.device.model,
  170. os: ua.os.name,
  171. browser: ua.browser.name,
  172. type: ua.device.type
  173. };
  174. }
  175. getInfo() {
  176. return {
  177. id: this.id,
  178. name: this.name,
  179. rtcSupported: this.rtcSupported
  180. }
  181. }
  182. }
  183. const server = new SnapdropServer(process.env.PORT || 3000);