index.js 6.2 KB

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