index.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. if (this._rooms[peer.ip][peer.id]) {
  50. this._cancelKeepAlive(this._rooms[peer.ip][peer.id]);
  51. }
  52. // console.log(peer.id, ' joined the room', peer.ip);
  53. // notify all other peers
  54. for (const otherPeerId in this._rooms[peer.ip]) {
  55. const otherPeer = this._rooms[peer.ip][otherPeerId];
  56. this._send(otherPeer, {
  57. type: 'peer-joined',
  58. peer: peer.getInfo()
  59. });
  60. }
  61. // notify peer about the other peers
  62. const otherPeers = [];
  63. for (const otherPeerId in this._rooms[peer.ip]) {
  64. otherPeers.push(this._rooms[peer.ip][otherPeerId].getInfo());
  65. }
  66. this._send(peer, {
  67. type: 'peers',
  68. peers: otherPeers
  69. });
  70. // add peer to room
  71. this._rooms[peer.ip][peer.id] = peer;
  72. }
  73. _leaveRoom(peer) {
  74. if (!this._rooms[peer.ip] || !this._rooms[peer.ip][peer.id]) return;
  75. this._cancelKeepAlive(peer);
  76. // delete the peer
  77. delete this._rooms[peer.ip][peer.id];
  78. peer.socket.terminate();
  79. //if room is empty, delete the room
  80. if (!Object.keys(this._rooms[peer.ip]).length) {
  81. delete this._rooms[peer.ip];
  82. } else {
  83. // notify all other peers
  84. for (const otherPeerId in this._rooms[peer.ip]) {
  85. const otherPeer = this._rooms[peer.ip][otherPeerId];
  86. this._send(otherPeer, {
  87. type: 'peer-left',
  88. peerId: peer.id
  89. });
  90. }
  91. }
  92. }
  93. _send(peer, message) {
  94. if (!peer) return console.error('undefined peer');
  95. if (this._wss.readyState !== this._wss.OPEN) return console.error('Socket is closed');
  96. message = JSON.stringify(message);
  97. peer.socket.send(message, error => {
  98. if (error) this._leaveRoom(peer);
  99. });
  100. }
  101. _keepAlive(peer) {
  102. this._cancelKeepAlive(peer);
  103. var timeout = 10000;
  104. if (!peer.lastBeat) {
  105. peer.lastBeat = Date.now();
  106. }
  107. if (Date.now() - peer.lastBeat > 2 * timeout) {
  108. this._leaveRoom(peer);
  109. return;
  110. }
  111. this._send(peer, { type: 'ping' });
  112. peer.timerId = setTimeout(() => this._keepAlive(peer), timeout);
  113. }
  114. _cancelKeepAlive(peer) {
  115. if (peer.timerId) {
  116. clearTimeout(peer.timerId);
  117. }
  118. }
  119. }
  120. class Peer {
  121. constructor(socket, request) {
  122. // set socket
  123. this.socket = socket;
  124. // set remote ip
  125. if (request.headers['x-forwarded-for'])
  126. this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
  127. else
  128. this.ip = request.connection.remoteAddress;
  129. if (request.peerId) {
  130. this.id = request.peerId;
  131. } else {
  132. this.id = request.headers.cookie.replace('peerid=', '');
  133. }
  134. // set peer id
  135. // is WebRTC supported ?
  136. this.rtcSupported = request.url.indexOf('webrtc') > -1;
  137. // set name
  138. this.setName(request);
  139. // for keepalive
  140. this.timerId = 0;
  141. this.lastBeat = Date.now();
  142. }
  143. // return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  144. static uuid() {
  145. let uuid = '',
  146. ii;
  147. for (ii = 0; ii < 32; ii += 1) {
  148. switch (ii) {
  149. case 8:
  150. case 20:
  151. uuid += '-';
  152. uuid += (Math.random() * 16 | 0).toString(16);
  153. break;
  154. case 12:
  155. uuid += '-';
  156. uuid += '4';
  157. break;
  158. case 16:
  159. uuid += '-';
  160. uuid += (Math.random() * 4 | 8).toString(16);
  161. break;
  162. default:
  163. uuid += (Math.random() * 16 | 0).toString(16);
  164. }
  165. }
  166. return uuid;
  167. };
  168. toString() {
  169. return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
  170. }
  171. setName(req) {
  172. var ua = parser(req.headers['user-agent']);
  173. this.name = {
  174. model: ua.device.model,
  175. os: ua.os.name,
  176. browser: ua.browser.name,
  177. type: ua.device.type
  178. };
  179. }
  180. getInfo() {
  181. return {
  182. id: this.id,
  183. name: this.name,
  184. rtcSupported: this.rtcSupported
  185. }
  186. }
  187. }
  188. const server = new SnapdropServer(process.env.PORT || 3000);