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