index.js 6.4 KB

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