Explorar o código

Allow discovery

Michelle Bu %!s(int64=11) %!d(string=hai) anos
pai
achega
8c1eb5d978
Modificáronse 2 ficheiros con 32 adicións e 3 borrados
  1. 7 1
      bin/peerjs
  2. 25 2
      lib/server.js

+ 7 - 1
bin/peerjs

@@ -54,8 +54,14 @@ var path = require('path')
       path: {
         demand: false,
         description: 'custom path'
+      },
+      allow_discovery: {
+        demand: false,
+        description: 'allow discovery of peers'
       }
-    }).argv;
+    })
+    .boolean('allow_discovery')
+    .argv;
 
 opts.version = version;
 

+ 25 - 2
lib/server.js

@@ -16,7 +16,8 @@ function PeerServer(options) {
     ip_limit: 5000,
     concurrent_limit: 5000,
     ssl: {},
-    path: '/'
+    path: '/',
+    allow_discovery: false
   }, options);
 
   util.debug = this._options.debug;
@@ -153,6 +154,9 @@ PeerServer.prototype._configureWS = function(socket, key, id, token) {
   this.emit('connection', id);
 };
 
+PeerServer.prototype._checkAllowsDiscovery = function(key, cb) {
+  cb(this._options.allow_discovery);
+};
 
 PeerServer.prototype._checkKey = function(key, ip, cb) {
   if (key == this._options.key) {
@@ -218,6 +222,24 @@ PeerServer.prototype._initializeHTTP = function() {
     return next();
   });
 
+  // Get a list of all peers for a key, enabled by the `allowDiscovery` flag.
+  this._app.get(this._options.path + ':key/peers', function(req, res, next) {
+    var key = req.params.key;
+    if (self._clients[key]) {
+      self._checkAllowsDiscovery(key, function(isAllowed) {
+        if (isAllowed) {
+          res.send(JSON.stringify(Object.keys(self._clients[key])));
+        } else {
+          res.send(401);
+        }
+        return next();
+      });
+    } else {
+      res.send(404);
+      return next();
+    }
+  });
+
   var handle = function(req, res, next) {
     var key = req.params.key;
     var id = req.params.id;
@@ -226,12 +248,13 @@ PeerServer.prototype._initializeHTTP = function() {
     if (!self._clients[key] || !(client = self._clients[key][id])) {
       if (req.params.retry) {
         res.send(401);
+        return next();
       } else {
         // Retry this request
         req.params.retry = true;
         setTimeout(handle, 25, req, res);
+        return;
       }
-      return;
     }
 
     // Auth the req