index.js 6.3 KB

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