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({
  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. this._cancelKeepAlive(peer);
  76. // delete the peer
  77. if (!this._rooms[peer.ip] || !this._rooms[peer.ip][peer.id]) return;
  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. peer.lastBeat = null;
  119. }
  120. }
  121. }
  122. class Peer {
  123. constructor(socket, request) {
  124. // set socket
  125. this.socket = socket;
  126. // set remote ip
  127. if (request.headers['x-forwarded-for'])
  128. this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
  129. else
  130. this.ip = request.connection.remoteAddress;
  131. if (request.peerId) {
  132. this.id = request.peerId;
  133. } else {
  134. this.id = request.headers.cookie.replace('peerid=', '');
  135. }
  136. // set peer id
  137. // is WebRTC supported ?
  138. this.rtcSupported = request.url.indexOf('webrtc') > -1;
  139. // set name
  140. this.setName(request);
  141. // for keepalive
  142. this.timerId = 0;
  143. this.lastBeat = Date.now();
  144. }
  145. // return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  146. static uuid() {
  147. let uuid = '',
  148. ii;
  149. for (ii = 0; ii < 32; ii += 1) {
  150. switch (ii) {
  151. case 8:
  152. case 20:
  153. uuid += '-';
  154. uuid += (Math.random() * 16 | 0).toString(16);
  155. break;
  156. case 12:
  157. uuid += '-';
  158. uuid += '4';
  159. break;
  160. case 16:
  161. uuid += '-';
  162. uuid += (Math.random() * 4 | 8).toString(16);
  163. break;
  164. default:
  165. uuid += (Math.random() * 16 | 0).toString(16);
  166. }
  167. }
  168. return uuid;
  169. };
  170. toString() {
  171. return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
  172. }
  173. setName(req) {
  174. var ua = parser(req.headers['user-agent']);
  175. this.name = {
  176. model: ua.device.model,
  177. os: ua.os.name,
  178. browser: ua.browser.name,
  179. type: ua.device.type
  180. };
  181. }
  182. getInfo() {
  183. return {
  184. id: this.id,
  185. name: this.name,
  186. rtcSupported: this.rtcSupported
  187. }
  188. }
  189. }
  190. const server = new SnapdropServer(process.env.PORT || 3000);