index.js 6.0 KB

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