index.js 6.6 KB

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