<commit_before>/* Approximation of Retro UI */
(function() {
  "use strict";
  var selector = window.huesConfig["uiSelector"];
  var autoPlay = window.huesConfig["autoPlay"];
  if (typeof(selector) === 'undefined') {
    selector = 'body';
  }
  if (typeof(autoPlay) === 'undefined') {
    autoPlay = false;
  }

  var HuesUI = {};

  var setupRootElement = function() {
    var rootElement = document.querySelector(selector);
    if (!rootElement) {
      return Promise.reject(Error("Cannot find requested root element " +
            rootElement + " on page."));
    }
    /*while (rootElement.firstChild) {
      rootElement.removeChild(rootElement.firstChild);
    }*/
    return Promise.resolve(rootElement);
  }

  var setupStatusMode = function(statusDiv) {
    var modeDiv = document.createElement("div");
    statusDiv.appendChild(modeDiv);
    var modeLabel = document.createElement("span");
    modeLabel.textContent = "M=";
    modeDiv.appendChild(modeLabel);
    var modeField = document.createElement("span");
    modeField.textContent = "undefined";
    modeDiv.appendChild(modeField);

    var updateModeField = function(autoMode) {
      modeField.textContent = autoMode.toUpperCase();
    };
    updateModeField(Hues.getAutoMode());
    Hues.addEventListener("automodechange", updateModeField);
  }

  var setupStatusImage = function(statusDiv) {
    var imageDiv = document.createElement("div");
    statusDiv.appendChild(imageDiv);
    var imageLabel = document.createElement("span");
    imageLabel.textContent = "I=";
    imageDiv.appendChild(imageLabel);
    var imageField = document.createElement("span");
    imageField.textContent = "undefined";
    imageDiv.appendChild(imageField);

    var updateImageField = function(imageInfo) {
      imageField.textContent = imageInfo["name"].toUpperCase();
    }
    updateImageField(Hues.getCurrentImage());
    Hues.addEventListener("imagechange", updateImageField);
  };

  var setupStatusBeatNum = function(statusDiv) {
    var beatDiv = document.createElement("div");
    statusDiv.appendChild(beatDiv);
    var beatLabel = document.createElement("span");
    beatLabel.textContent = "B=$0x";
    beatDiv.appendChild(beatLabel);
    var beatField = document.createElement("span");
    beatField.textContent = "0000";
    beatDiv.appendChild(beatField);

    var updateBeatField = function(beat) {
      var beatNum = "0";
      if (beat["buildup"] !== null) {
        beatNum = beat["buildup"].toString(16);
      } else if (beat["loop"] !== null) {
        beatNum = beat["loop"].toString(16);
      }
      var padding = 4 - beatNum.length;
      if (padding > 0) {
        beatNum = "0".repeat(padding) + beatNum;
      }
      if (beat["buildup"] !== null) {
        beatNum += " (BUILD)";
      }
      beatField.textContent = beatNum.toUpperCase();
    };
    Hues.addEventListener("beat", updateBeatField);
  };

  var setupStatusVolume = function(statusDiv) {
    var volumeDiv = document.createElement("div");
    statusDiv.appendChild(volumeDiv);
    var volumeLabel = document.createElement("span");
    volumeLabel.textContent = "V=";
    volumeDiv.appendChild(volumeLabel);
    var volumeField = document.createElement("span");
    volumeField.textContent = "0.0dB";
    volumeDiv.appendChild(volumeField);

    var updateVolumeField = function(muted, gain) {
      if (muted) {
        volumeField.textContent = "MUTED";
      } else {
        volumeField.textContent = gain.toFixed(1) + "dB";
      }
    };
    Hues.addEventListener("volumechange", updateVolumeField);
    updateVolumeField(Hues.isMuted(), Hues.getVolume());
  };

  var setupStatusHue = function(statusDiv) {
    var hueDiv = document.createElement("div");
    statusDiv.appendChild(hueDiv);
    var hueLabel = document.createElement("span");
    hueLabel.textContent = "C=$0x";
    hueDiv.appendChild(hueLabel);
    var hueField = document.createElement("span");
    hueDiv.appendChild(hueField);

    var updateHueField = function(hueInfo) {
      var hueNum = hueInfo["index"].toString(16);
      if (hueNum.length < 2) {
        hueNum = "0" + hueNum;
      }
      hueField.textContent = hueNum.toUpperCase();
    };
    updateHueField(Hues.getCurrentHue());
    Hues.addEventListener("huechange", updateHueField);
  };

  var setupStatusHueName = function(statusDiv) {
    var hueField = document.createElement("div");
    statusDiv.appendChild(hueField);

    var updateHueField = function(hueInfo) {
      hueField.textContent = hueInfo["hue"]["name"].toUpperCase();
    }
    updateHueField(Hues.getCurrentHue());
    Hues.addEventListener("huechange", updateHueField);
  };

  var setupStatusSong = function(statusDiv) {
    var songField = document.createElement("div");
    statusDiv.appendChild(songField);

    var updateSongField = function(song) {
      if (song) {
        songField.textContent = song["title"].toUpperCase();
      } else {
        songField.textContent = "[UNDEFINED]";
      }
    }
    updateSongField(Hues.getCurrentSong());
    Hues.addEventListener("songchange", updateSongField);
  }

  var setupStatusCredits = function(statusDiv) {
    var creditsDiv = document.createElement("div");
    creditsDiv.style.opacity = "0.50";
    statusDiv.appendChild(creditsDiv);
    var creditsLink = document.createElement("a");
    creditsLink.href = "https://github.com/kepstin/0x40hues-html5";
    creditsLink.textContent = "0x40 HUES OF HTML5 BY KEPSTIN";
    creditsLink.target = "_blank";
    creditsDiv.appendChild(creditsLink);
  }

  var setupStatusBeats = function(statusDiv) {
    var beatsDiv = document.createElement("div");
    beatsDiv.style.overflowX = "hidden";
    beatsDiv.style.whiteSpace = "nowrap";
    statusDiv.appendChild(beatsDiv);
    var beatsLabel = document.createElement("span");
    beatsLabel.textContent = ">>";
    beatsDiv.appendChild(beatsLabel);
    var beatsField = document.createElement("span");
    beatsDiv.appendChild(beatsField);

    var updateBeats = function(beat) {
      var beats = Hues.getBeatString();
      beatsField.textContent = beats;
    }
    Hues.addEventListener("beat", updateBeats);
  }

  var setupStatusArea = function(rootElement) {
    var statusDiv = document.createElement("div");
    statusDiv.style.position = "absolute";
    statusDiv.style.left = "0";
    statusDiv.style.right = "0";
    statusDiv.style.bottom = "0";
    rootElement.appendChild(statusDiv);

    setupStatusMode(statusDiv);
    setupStatusImage(statusDiv);
    setupStatusVolume(statusDiv);
    setupStatusBeatNum(statusDiv);
    setupStatusHue(statusDiv);
    setupStatusHueName(statusDiv);
    setupStatusSong(statusDiv);
    setupStatusCredits(statusDiv);
    setupStatusBeats(statusDiv);

    return Promise.resolve(rootElement);
  }

  var setupProgress = function(rootElement) {
    return new Promise(function(resolve, reject) {
      var progressContainer = document.createElement("div");
      progressContainer.style.position = "absolute";
      progressContainer.style.display = "block";
      progressContainer.style.background = "white";
      progressContainer.style.top = "0";
      progressContainer.style.left = "0";
      progressContainer.style.right = "0";
      progressContainer.style.bottom = "0";
      progressContainer.style.width = "100%";
      progressContainer.style.height = "100%";
      rootElement.appendChild(progressContainer);

      var progressDiv = document.createElement("div");
      progressDiv.style.position = "relative";
      progressDiv.style.top = "50%";
      progressDiv.style.transform = "translateY(-50%);"
      progressDiv.style.textAlign = "center";
      progressDiv.style.fontSize = "600%";
      progressContainer.appendChild(progressDiv);

      var completed = 0;
      var total = 0;
      var updateProgress = function() {
        var progress;
        if (total == 0) {
          progress = 0;
        } else {
          progress = completed / total;
        }
        progress = Math.floor(progress * 64);

        var progressStr = progress.toString(16);
        var padding = 2 - progressStr.length;
        if (padding > 0) {
          progressStr = "0".repeat(padding) + progressStr;
        }
        progressDiv.textContent = "0x" + progressStr;
      };
      Hues.addEventListener("progressstart", function() {
        completed = 0;
        total = 0;
        progressContainer.style.display = "block";
        updateProgress();
      });
      Hues.addEventListener("progress", function(done, added) {
        completed += done;
        total += added;
        updateProgress();
      });
      Hues.addEventListener("progressend", function() {
        setTimeout(function() {
          progressContainer.style.display = "none";
          resolve(rootElement);
        }, 500);
      });
    });
  }

  var setupEffectCanvas = function(rootElement) {
    var canvas = document.createElement("canvas");
    canvas.style.position = "absolute";
    canvas.style.display = "block";
    canvas.style.top = "0";
    canvas.style.left = "0";
    canvas.style.right = "0";
    canvas.style.bottom = "0";
    canvas.style.width = "100%";
    canvas.style.height = "100%";
    canvas.width = rootElement.clientWidth;
    canvas.height = rootElement.clientHeight;
    rootElement.appendChild(canvas);

    return window.HuesEffect.setup(window.Hues, canvas)
      .then(function() { return rootElement; });
  }

  var setupKeyHandlers = function(rootElement) {
    /* Even though we have the root element, keys are going to be installed
     * on the window. */

    window.addEventListener("keypress", function(e) {
      /* Firefox returns the character in 'key', chrome the code in 'keyCode'.
       * Because lol javascript */
      if (e.defaultPrevented) {
        return;
      }

      console.log(e);
      var key = e.key;
      if (!key) {
        switch (e.keyCode) {
        case 43: key = '+'; break;
        case 45: key = '-'; break;
        case 61: key = '='; break;
        case 102: key = 'f'; break;
        case 109: key = 'm'; break;
        }
      }
      switch (key) {
      case '+':
      case '=':
        Hues.adjustVolume(1.0);
        break;
      case '-':
        Hues.adjustVolume(-1.0);
        break;
      case 'f':
        if (Hues.getAutoMode() == "normal") {
          Hues.setAutoMode("full auto");
        } else {
          Hues.setAutoMode("normal");
        }
        break;
      case 'm':
        if (Hues.isMuted()) {
          Hues.unmute();
        } else {
          Hues.mute();
        }
        break;
      }
    });
    /* Arrow keys don't have "press" events */
    window.addEventListener("keyup", function(e) {
      if (e.defaultPrevented) {
        return;
      }

      var key = e.key;
      if (!key) {
        switch (e.keyCode) {
        case 16: key = 'Shift'; break;
        case 37: key = 'ArrowLeft'; break;
        case 38: key = 'ArrowUp'; break;
        case 39: key = 'ArrowRight'; break;
        case 40: key = 'ArrowDown'; break;
        }
      }
      switch (key) {
      case 'Shift':
        Hues.randomSong();
        break;
      case 'ArrowDown':
      case 'Down':
        Hues.prevSong();
        break;
      case 'ArrowUp':
      case 'Up':
        Hues.nextSong();
        break;
      case 'ArrowLeft':
      case 'Left':
        Hues.setAutoMode("normal");
        Hues.prevImage();
        break;
      case 'ArrowRight':
      case 'Right':
        Hues.setAutoMode("normal");
        Hues.nextImage();
        break;
      }
    });
  }

  var initialize = function() {
    var rootElement = setupRootElement()
    .then(setupEffectCanvas);
    var progress = rootElement.then(setupProgress);
    var respack = rootElement.then(Hues.loadDefaultRespack);

    return Promise.all([rootElement, progress, respack])
    .then(function(args) { return args[0]; })
    .then(setupStatusArea)
    .then(setupKeyHandlers)
    .then(function() {
      if (autoPlay) { return Hues.playSong(); }
    }).catch(function(error) {
      console.log(error);
    });
  }
  HuesUI["initialize"] = initialize;

  window.HuesUI = HuesUI;
})();

if (document.readyState == "complete") {
  HuesUI.initialize();
} else {
  document.addEventListener("readystatechange", function() {
    if (document.readyState == "complete") {
      HuesUI.initialize();
    }
  });
}
<commit_msg>Stop logging keypress events again<commit_after>/* Approximation of Retro UI */
(function() {
  "use strict";
  var selector = window.huesConfig["uiSelector"];
  var autoPlay = window.huesConfig["autoPlay"];
  if (typeof(selector) === 'undefined') {
    selector = 'body';
  }
  if (typeof(autoPlay) === 'undefined') {
    autoPlay = false;
  }

  var HuesUI = {};

  var setupRootElement = function() {
    var rootElement = document.querySelector(selector);
    if (!rootElement) {
      return Promise.reject(Error("Cannot find requested root element " +
            rootElement + " on page."));
    }
    /*while (rootElement.firstChild) {
      rootElement.removeChild(rootElement.firstChild);
    }*/
    return Promise.resolve(rootElement);
  }

  var setupStatusMode = function(statusDiv) {
    var modeDiv = document.createElement("div");
    statusDiv.appendChild(modeDiv);
    var modeLabel = document.createElement("span");
    modeLabel.textContent = "M=";
    modeDiv.appendChild(modeLabel);
    var modeField = document.createElement("span");
    modeField.textContent = "undefined";
    modeDiv.appendChild(modeField);

    var updateModeField = function(autoMode) {
      modeField.textContent = autoMode.toUpperCase();
    };
    updateModeField(Hues.getAutoMode());
    Hues.addEventListener("automodechange", updateModeField);
  }

  var setupStatusImage = function(statusDiv) {
    var imageDiv = document.createElement("div");
    statusDiv.appendChild(imageDiv);
    var imageLabel = document.createElement("span");
    imageLabel.textContent = "I=";
    imageDiv.appendChild(imageLabel);
    var imageField = document.createElement("span");
    imageField.textContent = "undefined";
    imageDiv.appendChild(imageField);

    var updateImageField = function(imageInfo) {
      imageField.textContent = imageInfo["name"].toUpperCase();
    }
    updateImageField(Hues.getCurrentImage());
    Hues.addEventListener("imagechange", updateImageField);
  };

  var setupStatusBeatNum = function(statusDiv) {
    var beatDiv = document.createElement("div");
    statusDiv.appendChild(beatDiv);
    var beatLabel = document.createElement("span");
    beatLabel.textContent = "B=$0x";
    beatDiv.appendChild(beatLabel);
    var beatField = document.createElement("span");
    beatField.textContent = "0000";
    beatDiv.appendChild(beatField);

    var updateBeatField = function(beat) {
      var beatNum = "0";
      if (beat["buildup"] !== null) {
        beatNum = beat["buildup"].toString(16);
      } else if (beat["loop"] !== null) {
        beatNum = beat["loop"].toString(16);
      }
      var padding = 4 - beatNum.length;
      if (padding > 0) {
        beatNum = "0".repeat(padding) + beatNum;
      }
      if (beat["buildup"] !== null) {
        beatNum += " (BUILD)";
      }
      beatField.textContent = beatNum.toUpperCase();
    };
    Hues.addEventListener("beat", updateBeatField);
  };

  var setupStatusVolume = function(statusDiv) {
    var volumeDiv = document.createElement("div");
    statusDiv.appendChild(volumeDiv);
    var volumeLabel = document.createElement("span");
    volumeLabel.textContent = "V=";
    volumeDiv.appendChild(volumeLabel);
    var volumeField = document.createElement("span");
    volumeField.textContent = "0.0dB";
    volumeDiv.appendChild(volumeField);

    var updateVolumeField = function(muted, gain) {
      if (muted) {
        volumeField.textContent = "MUTED";
      } else {
        volumeField.textContent = gain.toFixed(1) + "dB";
      }
    };
    Hues.addEventListener("volumechange", updateVolumeField);
    updateVolumeField(Hues.isMuted(), Hues.getVolume());
  };

  var setupStatusHue = function(statusDiv) {
    var hueDiv = document.createElement("div");
    statusDiv.appendChild(hueDiv);
    var hueLabel = document.createElement("span");
    hueLabel.textContent = "C=$0x";
    hueDiv.appendChild(hueLabel);
    var hueField = document.createElement("span");
    hueDiv.appendChild(hueField);

    var updateHueField = function(hueInfo) {
      var hueNum = hueInfo["index"].toString(16);
      if (hueNum.length < 2) {
        hueNum = "0" + hueNum;
      }
      hueField.textContent = hueNum.toUpperCase();
    };
    updateHueField(Hues.getCurrentHue());
    Hues.addEventListener("huechange", updateHueField);
  };

  var setupStatusHueName = function(statusDiv) {
    var hueField = document.createElement("div");
    statusDiv.appendChild(hueField);

    var updateHueField = function(hueInfo) {
      hueField.textContent = hueInfo["hue"]["name"].toUpperCase();
    }
    updateHueField(Hues.getCurrentHue());
    Hues.addEventListener("huechange", updateHueField);
  };

  var setupStatusSong = function(statusDiv) {
    var songField = document.createElement("div");
    statusDiv.appendChild(songField);

    var updateSongField = function(song) {
      if (song) {
        songField.textContent = song["title"].toUpperCase();
      } else {
        songField.textContent = "[UNDEFINED]";
      }
    }
    updateSongField(Hues.getCurrentSong());
    Hues.addEventListener("songchange", updateSongField);
  }

  var setupStatusCredits = function(statusDiv) {
    var creditsDiv = document.createElement("div");
    creditsDiv.style.opacity = "0.50";
    statusDiv.appendChild(creditsDiv);
    var creditsLink = document.createElement("a");
    creditsLink.href = "https://github.com/kepstin/0x40hues-html5";
    creditsLink.textContent = "0x40 HUES OF HTML5 BY KEPSTIN";
    creditsLink.target = "_blank";
    creditsDiv.appendChild(creditsLink);
  }

  var setupStatusBeats = function(statusDiv) {
    var beatsDiv = document.createElement("div");
    beatsDiv.style.overflowX = "hidden";
    beatsDiv.style.whiteSpace = "nowrap";
    statusDiv.appendChild(beatsDiv);
    var beatsLabel = document.createElement("span");
    beatsLabel.textContent = ">>";
    beatsDiv.appendChild(beatsLabel);
    var beatsField = document.createElement("span");
    beatsDiv.appendChild(beatsField);

    var updateBeats = function(beat) {
      var beats = Hues.getBeatString();
      beatsField.textContent = beats;
    }
    Hues.addEventListener("beat", updateBeats);
  }

  var setupStatusArea = function(rootElement) {
    var statusDiv = document.createElement("div");
    statusDiv.style.position = "absolute";
    statusDiv.style.left = "0";
    statusDiv.style.right = "0";
    statusDiv.style.bottom = "0";
    rootElement.appendChild(statusDiv);

    setupStatusMode(statusDiv);
    setupStatusImage(statusDiv);
    setupStatusVolume(statusDiv);
    setupStatusBeatNum(statusDiv);
    setupStatusHue(statusDiv);
    setupStatusHueName(statusDiv);
    setupStatusSong(statusDiv);
    setupStatusCredits(statusDiv);
    setupStatusBeats(statusDiv);

    return Promise.resolve(rootElement);
  }

  var setupProgress = function(rootElement) {
    return new Promise(function(resolve, reject) {
      var progressContainer = document.createElement("div");
      progressContainer.style.position = "absolute";
      progressContainer.style.display = "block";
      progressContainer.style.background = "white";
      progressContainer.style.top = "0";
      progressContainer.style.left = "0";
      progressContainer.style.right = "0";
      progressContainer.style.bottom = "0";
      progressContainer.style.width = "100%";
      progressContainer.style.height = "100%";
      rootElement.appendChild(progressContainer);

      var progressDiv = document.createElement("div");
      progressDiv.style.position = "relative";
      progressDiv.style.top = "50%";
      progressDiv.style.transform = "translateY(-50%);"
      progressDiv.style.textAlign = "center";
      progressDiv.style.fontSize = "600%";
      progressContainer.appendChild(progressDiv);

      var completed = 0;
      var total = 0;
      var updateProgress = function() {
        var progress;
        if (total == 0) {
          progress = 0;
        } else {
          progress = completed / total;
        }
        progress = Math.floor(progress * 64);

        var progressStr = progress.toString(16);
        var padding = 2 - progressStr.length;
        if (padding > 0) {
          progressStr = "0".repeat(padding) + progressStr;
        }
        progressDiv.textContent = "0x" + progressStr;
      };
      Hues.addEventListener("progressstart", function() {
        completed = 0;
        total = 0;
        progressContainer.style.display = "block";
        updateProgress();
      });
      Hues.addEventListener("progress", function(done, added) {
        completed += done;
        total += added;
        updateProgress();
      });
      Hues.addEventListener("progressend", function() {
        setTimeout(function() {
          progressContainer.style.display = "none";
          resolve(rootElement);
        }, 500);
      });
    });
  }

  var setupEffectCanvas = function(rootElement) {
    var canvas = document.createElement("canvas");
    canvas.style.position = "absolute";
    canvas.style.display = "block";
    canvas.style.top = "0";
    canvas.style.left = "0";
    canvas.style.right = "0";
    canvas.style.bottom = "0";
    canvas.style.width = "100%";
    canvas.style.height = "100%";
    canvas.width = rootElement.clientWidth;
    canvas.height = rootElement.clientHeight;
    rootElement.appendChild(canvas);

    return window.HuesEffect.setup(window.Hues, canvas)
      .then(function() { return rootElement; });
  }

  var setupKeyHandlers = function(rootElement) {
    /* Even though we have the root element, keys are going to be installed
     * on the window. */

    window.addEventListener("keypress", function(e) {
      /* Firefox returns the character in 'key', chrome the code in 'keyCode'.
       * Because lol javascript */
      if (e.defaultPrevented) {
        return;
      }

      var key = e.key;
      if (!key) {
        switch (e.keyCode) {
        case 43: key = '+'; break;
        case 45: key = '-'; break;
        case 61: key = '='; break;
        case 102: key = 'f'; break;
        case 109: key = 'm'; break;
        }
      }
      switch (key) {
      case '+':
      case '=':
        Hues.adjustVolume(1.0);
        break;
      case '-':
        Hues.adjustVolume(-1.0);
        break;
      case 'f':
        if (Hues.getAutoMode() == "normal") {
          Hues.setAutoMode("full auto");
        } else {
          Hues.setAutoMode("normal");
        }
        break;
      case 'm':
        if (Hues.isMuted()) {
          Hues.unmute();
        } else {
          Hues.mute();
        }
        break;
      }
    });
    /* Arrow keys don't have "press" events */
    window.addEventListener("keyup", function(e) {
      if (e.defaultPrevented) {
        return;
      }

      var key = e.key;
      if (!key) {
        switch (e.keyCode) {
        case 16: key = 'Shift'; break;
        case 37: key = 'ArrowLeft'; break;
        case 38: key = 'ArrowUp'; break;
        case 39: key = 'ArrowRight'; break;
        case 40: key = 'ArrowDown'; break;
        }
      }
      switch (key) {
      case 'Shift':
        Hues.randomSong();
        break;
      case 'ArrowDown':
      case 'Down':
        Hues.prevSong();
        break;
      case 'ArrowUp':
      case 'Up':
        Hues.nextSong();
        break;
      case 'ArrowLeft':
      case 'Left':
        Hues.setAutoMode("normal");
        Hues.prevImage();
        break;
      case 'ArrowRight':
      case 'Right':
        Hues.setAutoMode("normal");
        Hues.nextImage();
        break;
      }
    });
  }

  var initialize = function() {
    var rootElement = setupRootElement()
    .then(setupEffectCanvas);
    var progress = rootElement.then(setupProgress);
    var respack = rootElement.then(Hues.loadDefaultRespack);

    return Promise.all([rootElement, progress, respack])
    .then(function(args) { return args[0]; })
    .then(setupStatusArea)
    .then(setupKeyHandlers)
    .then(function() {
      if (autoPlay) { return Hues.playSong(); }
    }).catch(function(error) {
      console.log(error);
    });
  }
  HuesUI["initialize"] = initialize;

  window.HuesUI = HuesUI;
})();

if (document.readyState == "complete") {
  HuesUI.initialize();
} else {
  document.addEventListener("readystatechange", function() {
    if (document.readyState == "complete") {
      HuesUI.initialize();
    }
  });
}
<|endoftext|>


<commit_before>//
//     nodemavens
//     Copyright(c) 2014 Matt Hernandez <matt@modulus.io>
//     MIT Licensed
//

var blacklist = JSON.parse(process.env.BLACKLIST || '[]');

module.exports = function(app, controller) {

  //
  // Disallow blacklisted IPs and verify the session count.
  //
  app.all('/*', function(req, res, next) {
    if ('POST' === req.method) {

      var ip = req.headers['x-forwarded-for'].split(',')[0]
        , ua = req.headers['user-agent'];

      console.log(new Date().toString(), ip);

      if (blacklist.indexOf(ip) >= 0 || !ua || ua.indexOf('curl') >= 0) {
        res.statusCode = 403;
        return res.json();
      }

      if (req.session.count) {
        if (req.session.count === 5) {
          return res.json({
            error: 'Whoa! That\'s a little too much love... you\'re making people uncomfortable...'
          });
        } else {
          req.session.count++;
        }
      } else {
        req.session.count = 1;
      }
    }

    next();
  });

  //
  // GET index.
  //
  app.get('/', function(req, res) {
    res.sendfile('./server/views/index.html');
  });

  //
  // API routes.
  // ===========
  //

  //
  // GET the most recent mavens.
  //
  app.get('/api/mavens/recent', function(req, res) {
    controller.getRecent()
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // GET mavens.
  //
  app.get('/api/mavens/:username?', function(req, res) {
    controller.get(req.params.username)
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Create/POST a maven.
  //
  app.post('/api/mavens', function(req, res) {
    controller.create(req.body.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Vote for a maven.
  //
  app.post('/api/mavens/:username/love', function(req, res) {
    controller.love(req.params.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });
};
<commit_msg>Updated to work correctly when run locally.<commit_after>//
//     nodemavens
//     Copyright(c) 2014 Matt Hernandez <matt@modulus.io>
//     MIT Licensed
//

var blacklist = JSON.parse(process.env.BLACKLIST || '[]');

module.exports = function(app, controller) {

  //
  // Disallow blacklisted IPs and verify the session count.
  //
  app.all('/*', function(req, res, next) {
    if ('POST' === req.method) {

      if (!req.headers['x-forwarded-for']) {
        return next();
      }

      var ip = req.headers['x-forwarded-for'].split(',')[0]
        , ua = req.headers['user-agent'];

      console.log(new Date().toString(), ip);

      if (blacklist.indexOf(ip) >= 0 || !ua || ua.indexOf('curl') >= 0) {
        res.statusCode = 403;
        return res.json();
      }

      if (req.session.count) {
        if (req.session.count === 5) {
          return res.json({
            error: 'Whoa! That\'s a little too much love... you\'re making people uncomfortable...'
          });
        } else {
          req.session.count++;
        }
      } else {
        req.session.count = 1;
      }
    }

    next();
  });

  //
  // GET index.
  //
  app.get('/', function(req, res) {
    res.sendfile('./server/views/index.html');
  });

  //
  // API routes.
  // ===========
  //

  //
  // GET the most recent mavens.
  //
  app.get('/api/mavens/recent', function(req, res) {
    controller.getRecent()
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // GET mavens.
  //
  app.get('/api/mavens/:username?', function(req, res) {
    controller.get(req.params.username)
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Create/POST a maven.
  //
  app.post('/api/mavens', function(req, res) {
    controller.create(req.body.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Vote for a maven.
  //
  app.post('/api/mavens/:username/love', function(req, res) {
    controller.love(req.params.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/cal', function(req, res, next) {
  res.json(['2015-05-23', '2015-05-22', '2015-05-21']);
});

router.get('/news', function(req, res) {
  res.json({
    feeds: [
      {
        content: '헬스 휘트니스 옷장과 화장대 내 무단 보관된 사물은 내일 폐기합니다.',
        date: '2015-05-18'
      },
      {
        content: '기간 연장은 입원치료등 서류 제출시 가능하며, 여행등은 해당되지 않습니다.',
        date: '2015-05-15'
      },
      {
        content: '회원들께서는 휘트니스 이용수칙을 잘 지켜주시기 바랍니다. 감사합니다.',
        date: '2015-05-08'
      },
      {
        content: '재등록하셔서 다시 운동하는 모습으로 뵙기를 바랍니다. ^^',
        date: '2015-05-04'
      }
    ]
  });
});

router.get('/profile', function(req, res) {
  res.json({
    name: '구재성',
    image: '/images/flat-avatar.png'
  })
});

router.get('/today', function(req, res) {
  res.json({
    time: 50,
    timeBase: 60,
    distance: 4,
    distanceBase: 5,
    calories: 1000,
    caloriesBase: 1500
  });
});

router.get('/activities', function(req, res) {
  res.json({
    activities: [
      {
        name: 'Walking / Running'
      },
      {
        name: 'Biking'
      },
      {
        name: 'Aerobics'
      },
      {
        name: 'Yoga'
      },
      {
        name: 'Weight Training'
      }
    ]
  });
});

module.exports = router;
<commit_msg>dummy json response updated<commit_after>var express = require('express');
var router = express.Router();

router.get('/cal', function(req, res, next) {
  res.json(['2015-06-02', '2015-06-04', '2015-06-09']);
});

router.get('/news', function(req, res) {
  res.json({
    feeds: [
      {
        content: '헬스 휘트니스 옷장과 화장대 내 무단 보관된 사물은 내일 폐기합니다.',
        date: '2015-05-18'
      },
      {
        content: '기간 연장은 입원치료등 서류 제출시 가능하며, 여행등은 해당되지 않습니다.',
        date: '2015-05-15'
      },
      {
        content: '회원들께서는 휘트니스 이용수칙을 잘 지켜주시기 바랍니다. 감사합니다.',
        date: '2015-05-08'
      },
      {
        content: '재등록하셔서 다시 운동하는 모습으로 뵙기를 바랍니다. ^^',
        date: '2015-05-04'
      }
    ]
  });
});

router.get('/profile', function(req, res) {
  res.json({
    name: '구재성',
    image: '/images/flat-avatar.png'
  })
});

router.get('/today', function(req, res) {
  res.json({
    time: 50,
    timeBase: 60,
    distance: 4,
    distanceBase: 5,
    calory: 1000,
    caloryBase: 1500
  });
});

router.get('/activities', function(req, res) {
  res.json({
    activities: [
      {
        name: 'Walking / Running'
      },
      {
        name: 'Biking'
      },
      {
        name: 'Aerobics'
      },
      {
        name: 'Yoga'
      }
    ]
  });
});

// key(date) must be sorted
router.get('/data', function(req, res) {
  res.json({
    '2015-06-01': [
      {
        activity_index: 0,
        data: {
          distance: 5,
          time: 40,
          calory: 1000
        }
      },
      {
        activity_index: 1,
        data: {
          distance: 5,
          time: 20,
          calory: 500
        }
      },
      {
        activity_index: 0,
        data: {
          distance: 2,
          time: 10,
          calory: 200
        }
      }
    ],
    '2015-06-02': [
      {
        activity_index: 0,
        data: {
          distance: 3,
          time: 20,
          calory: 400
        }
      },
      {
        activity_index: 3,
        data: {
          distance: 2,
          time: 10,
          calory: 300
        }
      }
    ]
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var router = require('express').Router();
var Note = require('../models/note');

router.post('/', function(req, res) {
  var newNote = new Note({
    user: req.user,
    title: req.body.note.title,
    body_html: req.body.note.body_html
  });
  newNote.save(function(err) {
    if (err) { console.log('OHNOES!', err); }
    else { res.json({ note: newNote }); }
  });
});

// create some records with mongo cli like this:
// $ mongo
// > use caedence_net_development
// > db.notes.insert({ title: "Hello", body_html: "
World
", body_text: "World" })
// WriteResult({ "nInserted" : 1 })
// > db.notes.find()
// { "_id" : ObjectId("562473c0802fa33ca991217b"), "title" : "Hello", "body_html" : "
World
", "body_text" : "World" }
router.get('/', function(req, res) {
  Note.find({ user: req.user }).then(function(notes) {
    res.json(notes);
  });
});

router.get('/:id', function(req, res) {
  var id = req.params.id;
  var note = Note.findOne({ user: req.user, _id: id }).then(function(note) {
    res.json(note);
  });
});

router.put('/:id', function(req, res) {
  Note.findOne({ user: req.user, _id: req.params.id }).then(function(note) {
    note.title = req.body.note.title;
    note.body_html = req.body.note.body_html;
    note.save().then(function() {
      res.json({ message: 'Successfully updated note', note: note });
    });
  });
});

router.delete('/:id', function(req, res) {
  Note.findOne({ user: req.user, _id: req.params.id }).then(function(note) {
    note.remove().then(function(){
      res.json({ message: 'Successfully deleted note.' });
    });
  });
});

module.exports = router;
<commit_msg>Sort notes listing by updated_at property.<commit_after>var router = require('express').Router();
var Note = require('../models/note');

router.post('/', function(req, res) {
  var newNote = new Note({
    user: req.user,
    title: req.body.note.title,
    body_html: req.body.note.body_html
  });
  newNote.save(function(err) {
    if (err) { console.log('OHNOES!', err); }
    else { res.json({ note: newNote }); }
  });
});

// create some records with mongo cli like this:
// $ mongo
// > use caedence_net_development
// > db.notes.insert({ title: "Hello", body_html: "
World
", body_text: "World" })
// WriteResult({ "nInserted" : 1 })
// > db.notes.find()
// { "_id" : ObjectId("562473c0802fa33ca991217b"), "title" : "Hello", "body_html" : "
World
", "body_text" : "World" }
router.get('/', function(req, res) {
  Note.find({ user: req.user }).sort({ updated_at: 'desc' }).then(function(notes) {
    res.json(notes);
  });
});

router.get('/:id', function(req, res) {
  var id = req.params.id;
  var note = Note.findOne({ user: req.user, _id: id }).then(function(note) {
    res.json(note);
  });
});

router.put('/:id', function(req, res) {
  Note.findOne({ user: req.user, _id: req.params.id }).then(function(note) {
    note.title = req.body.note.title;
    note.body_html = req.body.note.body_html;
    note.save().then(function() {
      res.json({ message: 'Successfully updated note', note: note });
    });
  });
});

router.delete('/:id', function(req, res) {
  Note.findOne({ user: req.user, _id: req.params.id }).then(function(note) {
    note.remove().then(function(){
      res.json({ message: 'Successfully deleted note.' });
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var path = require('path');
var request = require('request');
var dateFormat = require('dateformat');

var ListGroup = require('../models/todo.js');

router.route('/clock')
    .post(function (req, res) {
        res.render('partials/content/clock', {
            pageId: "Clock",
            pageTitle: "Clock",
            pageDescription: "Home Control's clock page.",
            pageCss: ['main'],
            pageScripts: ['clock'],
            useBootstrap: true,
        });
    });

router.route('/calendar-month')
    .post(function(req, res) {
        res.send('<iframe src="https://calendar.google.com/calendar/embed?showTitle=0&showNav=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&height=600&wkst=1&bgcolor=%23FFFFFF&src=crschriever%40gmail.com&color=%2329527A&src=c0o5k11fbc01q37b085kens8ju3p2lom%40import.calendar.google.com&color=%2323164E&src=lh6rbkc5mmchli5qehorh3c0cn6kbum8%40import.calendar.google.com&color=%23875509&src=en.usa%23holiday%40group.v.calendar.google.com&color=%2329527A&ctz=America%2FNew_York" style="border-width:0" width="800" height="600" frameborder="0" scrolling="no">');
    });

router.route('/calendar-agenda')
    .post(function(req, res) {
        res.send('<iframe src="https://calendar.google.com/calendar/embed?showTitle=0&showNav=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&mode=AGENDA&height=600&wkst=1&bgcolor=%23FFFFFF&src=crschriever%40gmail.com&color=%2329527A&src=c0o5k11fbc01q37b085kens8ju3p2lom%40import.calendar.google.com&color=%2323164E&src=en.usa%23holiday%40group.v.calendar.google.com&color=%2329527A&ctz=America%2FNew_York" style="border-width:0" width="800" height="600" frameborder="0" scrolling="no">');
    });

router.route('/weather')
    .post(function(req, res) {
        res.redirect('/weather/Fernandina Beach');
    });

router.route('/weather/:city')
    .post(function(req, res) {

        let timeOffset = req.body.timeOffset / 60;
        let day, hourly, responded = false;

        let done = function(d, h) {
            if (d) {
                day = d;
            }
            if (h) {
                hourly = h;
            }

            if (day && hourly) {

                let weather = {
                    date: new Date(new Date().toString() + ' UTC+' + timeOffset),
                    cityName: day.name,
                    icon: day.weather[0].icon,
                    temperature: (((9 / 5)  * day.main.temp) - 459.67).toFixed(1) + ' °F',
                    main: day.weather[0].description.charAt(0).toUpperCase() + day.weather[0].description.slice(1),
                    hours: []
                };

                for (let i = 0; i < 5; i++) {
                    let cHour = hourly.list[i];
                    weather.hours[i] = {
                        date: dateFormat(new Date(cHour.dt_txt + ' UTC+' + timeOffset), 'ddd mmm d, h TT'),
                        min: (((9 / 5)  * cHour.main.temp_min) - 459.67).toFixed(1),
                        max: (((9 / 5)  * cHour.main.temp_max) - 459.67).toFixed(1),
                        main: cHour.weather[0].description.charAt(0).toUpperCase() + cHour.weather[0].description.slice(1),
                    }
                }

                res.render('partials/content/weather', {
                    pageId: "Weather",
                    pageTitle: "weather",
                    pageDescription: "Home Control's weather page.",
                    pageWeather: weather,
                    pageCss: ['main'],
                    pageScripts: ['weather'],
                    useBootstrap: true
                });
            }
        }

        request('http://api.openweathermap.org/data/2.5/weather?q=' + req.params.city + ',us&APPID=6e81c08216ea10e956e2447bfefba7a7', function (error, response, body) {

            console.log(error);

            if (error && !responded) {
                responded = true;
                res.json({"error": error});
            } else if (!responded){
                done(JSON.parse(body));
            }
        });

        request('http://api.openweathermap.org/data/2.5/forecast?q=' + req.params.city + ',us&APPID=6e81c08216ea10e956e2447bfefba7a7', function (error, response, body) {

            console.log(error);

            if (error && !responded) {
                responded = true;
                res.json({"error": error});
            } else if (!responded){
                done(null, JSON.parse(body));
            }
        });
    });

router.route('/lists')
    .post(function(req, res) {
        let listNames = [];
        ListGroup.find({}, function(err, users) {
            users.forEach(function(listGroup) {
                listNames.push(listGroup.name);
            });
            res.render('partials/content/lists', {
                pageId: "Lists",
                pageTitle: "Lists",
                pageDescription: "Home Control's lists page.",
                pageCss: ['main'],
                pageScripts: ['lists'],
                useBootstrap: true,
                listSets: listNames
            });
        });
    });

router.route('/list/:name')
    .post(function(req, res) {

        ListGroup.findOne({name: req.params.name}, function(err, list) {

            res.render('partials/content/list', {
                pageId: "List",
                pageTitle: "List",
                pageDescription: "Home Control's list page.",
                pageCss: ['main'],
                pageScripts: ['list'],
                useBootstrap: true,
                name: req.params.name,
                groups: list.groups
            });
        });
    });

module.exports = router;<commit_msg>Update Calandar views to use my current calandars<commit_after>var express = require('express');
var router = express.Router();
var path = require('path');
var request = require('request');
var dateFormat = require('dateformat');

var ListGroup = require('../models/todo.js');

router.route('/clock')
    .post(function (req, res) {
        res.render('partials/content/clock', {
            pageId: "Clock",
            pageTitle: "Clock",
            pageDescription: "Home Control's clock page.",
            pageCss: ['main'],
            pageScripts: ['clock'],
            useBootstrap: true,
        });
    });

router.route('/calendar-month')
    .post(function(req, res) {
        res.send('<iframe src="https://calendar.google.com/calendar/embed?showTitle=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&height=600&wkst=1&bgcolor=%23FFFFFF&src=crschriever%40gmail.com&color=%2329527A&src=td6m9idu672orrk7t5liujo540qdqlm7%40import.calendar.google.com&color=%23125A12&src=gp2alrjlrfvu3p0mqckv6drb3g%40group.calendar.google.com&color=%236B3304&src=lh6rbkc5mmchli5qehorh3c0cn6kbum8%40import.calendar.google.com&color=%23875509&src=ncaab_232_Georgia%2BTech%2BYellow%2BJackets%23sports%40group.v.calendar.google.com&color=%23AB8B00&src=ncaaf_4_Georgia%2BTech%2BYellow%2BJackets%23sports%40group.v.calendar.google.com&color=%23AB8B00&src=en.usa%23holiday%40group.v.calendar.google.com&color=%2329527A&ctz=America%2FNew_York" style="border-width:0" width="800" height="600" frameborder="0" scrolling="no">');
    });

router.route('/calendar-agenda')
    .post(function(req, res) {
        res.send('<iframe src="https://calendar.google.com/calendar/embed?showTitle=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&mode=AGENDA&height=600&wkst=1&bgcolor=%23FFFFFF&src=crschriever%40gmail.com&color=%2329527A&src=td6m9idu672orrk7t5liujo540qdqlm7%40import.calendar.google.com&color=%23125A12&src=gp2alrjlrfvu3p0mqckv6drb3g%40group.calendar.google.com&color=%236B3304&src=lh6rbkc5mmchli5qehorh3c0cn6kbum8%40import.calendar.google.com&color=%23875509&src=ncaab_232_Georgia%2BTech%2BYellow%2BJackets%23sports%40group.v.calendar.google.com&color=%23AB8B00&src=ncaaf_4_Georgia%2BTech%2BYellow%2BJackets%23sports%40group.v.calendar.google.com&color=%23AB8B00&src=en.usa%23holiday%40group.v.calendar.google.com&color=%2329527A&ctz=America%2FNew_York" style="border-width:0" width="800" height="600" frameborder="0" scrolling="no">');
    });

router.route('/weather')
    .post(function(req, res) {
        res.redirect('/weather/Fernandina Beach');
    });

router.route('/weather/:city')
    .post(function(req, res) {

        let timeOffset = req.body.timeOffset / 60;
        let day, hourly, responded = false;

        let done = function(d, h) {
            if (d) {
                day = d;
            }
            if (h) {
                hourly = h;
            }

            if (day && hourly) {

                let weather = {
                    date: new Date(new Date().toString() + ' UTC+' + timeOffset),
                    cityName: day.name,
                    icon: day.weather[0].icon,
                    temperature: (((9 / 5)  * day.main.temp) - 459.67).toFixed(1) + ' °F',
                    main: day.weather[0].description.charAt(0).toUpperCase() + day.weather[0].description.slice(1),
                    hours: []
                };

                for (let i = 0; i < 5; i++) {
                    let cHour = hourly.list[i];
                    weather.hours[i] = {
                        date: dateFormat(new Date(cHour.dt_txt + ' UTC+' + timeOffset), 'ddd mmm d, h TT'),
                        min: (((9 / 5)  * cHour.main.temp_min) - 459.67).toFixed(1),
                        max: (((9 / 5)  * cHour.main.temp_max) - 459.67).toFixed(1),
                        main: cHour.weather[0].description.charAt(0).toUpperCase() + cHour.weather[0].description.slice(1),
                    }
                }

                res.render('partials/content/weather', {
                    pageId: "Weather",
                    pageTitle: "weather",
                    pageDescription: "Home Control's weather page.",
                    pageWeather: weather,
                    pageCss: ['main'],
                    pageScripts: ['weather'],
                    useBootstrap: true
                });
            }
        }

        request('http://api.openweathermap.org/data/2.5/weather?q=' + req.params.city + ',us&APPID=6e81c08216ea10e956e2447bfefba7a7', function (error, response, body) {

            console.log(error);

            if (error && !responded) {
                responded = true;
                res.json({"error": error});
            } else if (!responded){
                done(JSON.parse(body));
            }
        });

        request('http://api.openweathermap.org/data/2.5/forecast?q=' + req.params.city + ',us&APPID=6e81c08216ea10e956e2447bfefba7a7', function (error, response, body) {

            console.log(error);

            if (error && !responded) {
                responded = true;
                res.json({"error": error});
            } else if (!responded){
                done(null, JSON.parse(body));
            }
        });
    });

router.route('/lists')
    .post(function(req, res) {
        let listNames = [];
        ListGroup.find({}, function(err, users) {
            users.forEach(function(listGroup) {
                listNames.push(listGroup.name);
            });
            res.render('partials/content/lists', {
                pageId: "Lists",
                pageTitle: "Lists",
                pageDescription: "Home Control's lists page.",
                pageCss: ['main'],
                pageScripts: ['lists'],
                useBootstrap: true,
                listSets: listNames
            });
        });
    });

router.route('/list/:name')
    .post(function(req, res) {

        ListGroup.findOne({name: req.params.name}, function(err, list) {

            res.render('partials/content/list', {
                pageId: "List",
                pageTitle: "List",
                pageDescription: "Home Control's list page.",
                pageCss: ['main'],
                pageScripts: ['list'],
                useBootstrap: true,
                name: req.params.name,
                groups: list.groups
            });
        });
    });

module.exports = router;<|endoftext|>


<commit_before>const express = require('express')
const bodyParser = require('body-parser')

const db = require('../db/users')
const token = require('../auth/token')

const router = express.Router()

router.use(bodyParser.json())

module.exports = router

// GET /users
router.get('/', token.decode, (req, res) => {
  db.getAllUsers()
    .then(allUsers => {
      res.json(allUsers)
    })
    .catch(err => {
      res.status(500).send(err.message)
    })
})

router.put('/approvals', token.decode, (req, res) => {
  console.log(req.body)
})

// GET /users/:id
router.get('/:id', token.decode, (req, res) => {
  db.getUserById(Number(req.params.id))
    .then(user => {
      res.json(user)
    })
    .catch(err => {
      res.status(500).send(err.message)
    })
})

// PUT /users/:id
router.put('/:id', token.decode, (req, res) => {
  const id = Number(req.params.id)
  const {username, currentPassword, newPassword} = req.body
  db.updateUser(id, username, currentPassword, newPassword)
    .then(() => {
      res.status(202).end()
    })
    .catch(err => {
      res.status(500).send(err.message)
    })
})

<commit_msg>fixed error<commit_after>const express = require('express')
const bodyParser = require('body-parser')

const db = require('../db/users')
const token = require('../auth/token')

const router = express.Router()

router.use(bodyParser.json())

module.exports = router

// GET /users
router.get('/', token.decode, (req, res) => {
  db.getAllUsers()
    .then(allUsers => {
      res.json(allUsers)
    })
    .catch(err => {
      res.status(500).send(err.message)
    })
})

// router.put('/approvals', token.decode, (req, res) => {
//   console.log(req.body)
// })

// GET /users/:id
router.get('/:id', token.decode, (req, res) => {
  db.getUserById(Number(req.params.id))
    .then(user => {
      res.json(user)
    })
    .catch(err => {
      res.status(500).send(err.message)
    })
})

// PUT /users/:id
router.put('/:id', token.decode, (req, res) => {
  const id = Number(req.params.id)
  const {username, currentPassword, newPassword} = req.body
  db.updateUser(id, username, currentPassword, newPassword)
    .then(() => {
      res.status(202).end()
    })
    .catch(err => {
      res.status(500).send(err.message)
    })
})
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';

var debug = require('debug')('Example:Data');
var cache = require('./cache');
var fetchLib = require('./fetch');

/**
 * Get a resource from cache.
 * If not found, get a resource from FRED
 */
function fetch (params, callback) {
  debug('fetching resource "'+params.resource+'"');

  if (cache.get(params.resource)) {
    debug('cache hit');
    return callback(null, cache.get(params.resource));
  }

  fetchLib.fetchOne(params, callback);
}

/**
 * Initialize the data layer
 */
function initialize (callback) {
  debug('initializing');

  fetchLib.fetchMain(callback);
}

module.exports = {
  fetch: fetch,
  initialize: initialize
};
<commit_msg>fix fetch to call get once<commit_after>/**
 * Copyright (c) 2015 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';

var debug = require('debug')('Example:Data');
var cache = require('./cache');
var fetchLib = require('./fetch');

/**
 * Get a resource from cache.
 * If not found, get a resource from FRED
 */
function fetch (params, callback) {
  debug('fetching resource "'+params.resource+'"');

  var resource = cache.get(params.resource);

  if (resource) {
    debug('cache hit');
    return callback(null, resource);
  }

  fetchLib.fetchOne(params, callback);
}

/**
 * Initialize the data layer
 */
function initialize (callback) {
  debug('initializing');

  fetchLib.fetchMain(callback);
}

module.exports = {
  fetch: fetch,
  initialize: initialize
};
<|endoftext|>


<commit_before>var cadence = require('cadence')

function Consumer (head) {
    this._head = head
}

Consumer.prototype.shift = function (callback) {
    if (this._head.next) {
        this._head = this._head.next
        callback(null, this._head.value)
    } else {
        this._callback = callback
    }
}

Consumer.prototype.destroy = function () {
    this.destroyed = true
}

Consumer.prototype.join = cadence(function (async, condition) {
    var loop = async(function () {
        this.shift(async())
    }, function (value) {
        if (condition(value)) {
            return [ loop.break, value ]
        }
    })()
})

Consumer.prototype._nudge = function () {
    if (this._callback != null) {
        var callback = [ this._callback, this._callback = null ][0]
        this._head = this._head.next
        callback(null, this._head.value)
    }
}

module.exports = Consumer
<commit_msg>Use `setImmediate`.<commit_after>var cadence = require('cadence')

function Consumer (head) {
    this._head = head
}

Consumer.prototype.shift = function (callback) {
    if (this._head.next) {
        this._head = this._head.next
        callback(null, this._head.value)
    } else {
        this._callback = callback
    }
}

Consumer.prototype.destroy = function () {
    this.destroyed = true
}

Consumer.prototype.join = cadence(function (async, condition) {
    var loop = async(function () {
        this.shift(async())
    }, function (value) {
        if (condition(value)) {
            return [ loop.break, value ]
        }
    })()
})

Consumer.prototype._nudge = function () {
    if (this._callback != null) {
        var callback = [ this._callback, this._callback = null ][0]
        this._head = this._head.next
        setImmediate(callback, null, this._head.value)
    }
}

module.exports = Consumer
<|endoftext|>


<commit_before>const XboxController = require('xbox-controller');
const WebSocket = require('ws');

const xbox = new XboxController();
const wss = new WebSocket.Server({ port: 8081 });

wss.on('connection', () => {
  /* eslint no-console: "allow" */
  console.log('Client connected.');
});

xbox.on('left:move', (position) => {
  const data = {
    type: 'left:move',
    x: position.x,
    y: position.y,
  };
  broadcast(data);
});

xbox.on('right:move', (position) => {
  const data = {
    type: 'right:move',
    x: position.x,
    y: position.y,
  };
  broadcast(data);
});

xbox.on('lefttrigger', (position) => {
  const data = {
    type: 'lefttrigger',
    x: position,
  };
  broadcast(data);
});

xbox.on('righttrigger', (position) => {
  const data = {
    type: 'righttrigger',
    x: position,
  };
  broadcast(data);
});

function broadcast(data) {
  const message = JSON.stringify(data);
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(message);
    }
  });
}
<commit_msg>Removed duplicate controls.js after renaming to controls-server.js<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var inherits = require('util').inherits;
var EventEmitter = require('tchannel/lib/event_emitter');
var Result = require('bufrw/result');

var states = require('./states.js');
var StateMachine = require('./state_machine.js');

// Each circuit uses the circuits collection as the "nextHandler" for
// "shouldRequest" to consult.  Peers use this hook to weight peers both by
// healthy and other factors, but the circuit only needs to know about health
// before forwarding.

function AlwaysShouldRequestHandler() { }

AlwaysShouldRequestHandler.prototype.shouldRequest = function shouldRequest() {
    return true;
};

var alwaysShouldRequestHandler = new AlwaysShouldRequestHandler();

function CircuitStateChange(circuit, oldState, state) {
    var self = this;
    self.circuit = circuit;
    self.oldState = oldState;
    self.state = state;
}

//  circuit = circuits                        : Circuits
//      .circuitsByServiceName[serviceName]   : ServiceCircuits
//      .circuitsByCallerName[callerName]     : EndpointCircuits
//      .circuitsByEndpointName[endpointName]

function EndpointCircuits(root) {
    var self = this;
    self.root = root;
    self.circuitsByEndpointName = {};
}

EndpointCircuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) {
    var self = this;
    var circuit = self.circuitsByEndpointName['$' + endpointName];
    if (!circuit) {
        circuit = new Circuit(callerName, serviceName, endpointName);
        circuit.stateOptions = new states.StateOptions(circuit, self.root.stateOptions);
        circuit.stateChangedEvent.on(function circuitStateChanged(newStates) {
            self.root.emitCircuitStateChange(circuit, newStates);
        });
        circuit.setState(states.HealthyState);
        self.circuitsByEndpointName['$' + endpointName] = circuit;
    }
    return circuit;
};

EndpointCircuits.prototype.collectCircuitTuples = function collectCircuitTuples(tuples) {
    var self = this;
    var endpointNames = Object.keys(self.circuitsByEndpointName);
    for (var index = 0; index < endpointNames.length; index++) {
        var endpointName = endpointNames[index];
        var circuit = self.circuitsByEndpointName[endpointName];
        tuples.push([circuit.callerName, circuit.serviceName, circuit.endpointName]);
    }
};

function ServiceCircuits(root) {
    var self = this;
    self.root = root;
    self.circuitsByCallerName = {};
}

ServiceCircuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) {
    var self = this;
    var circuits = self.circuitsByCallerName['$' + callerName];
    if (!circuits) {
        circuits = new EndpointCircuits(self.root);
        self.circuitsByCallerName['$' + callerName] = circuits;
    }
    return circuits.getCircuit(callerName, serviceName, endpointName);
};

ServiceCircuits.prototype.collectCircuitTuples = function collectCircuitTuples(tuples) {
    var self = this;
    var callerNames = Object.keys(self.circuitsByCallerName);
    for (var index = 0; index < callerNames.length; index++) {
        var callerName = callerNames[index];
        var circuit = self.circuitsByCallerName[callerName];
        circuit.collectCircuitTuples(tuples);
    }
};

function Circuits(options) {
    var self = this;
    EventEmitter.call(self);
    self.circuitStateChangeEvent = self.defineEvent('circuitStateChange');
    self.circuitsByServiceName = {};
    self.config = options.config || {};

    self.stateOptions = new states.StateOptions(null, {
        timeHeap: options.timeHeap,
        timers: options.timers,
        random: options.random,
        nextHandler: alwaysShouldRequestHandler,
        period: self.config.period,
        maxErrorRate: self.config.maxErrorRate,
        minRequests: self.config.minRequests,
        probation: self.config.probation
    });
    self.egressNodes = options.egressNodes;
}

inherits(Circuits, EventEmitter);

Circuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) {
    var self = this;
    var circuits = self.circuitsByServiceName['$' + serviceName];
    if (!circuits) {
        circuits = new ServiceCircuits(self);
        self.circuitsByServiceName['$' + serviceName] = circuits;
    }
    return circuits.getCircuit(callerName, serviceName, endpointName);
};

Circuits.prototype.getCircuitTuples = function getCircuitTuples() {
    var self = this;
    var tuples = [];
    var serviceNames = Object.keys(self.circuitsByServiceName);
    for (var index = 0; index < serviceNames.length; index++) {
        var serviceName = serviceNames[index];
        self.circuitsByServiceName[serviceName].collectCircuitTuples(tuples);
    }
    return tuples;
};

Circuits.prototype.getCircuitForRequest = function getCircuitForRequest(req) {
    var self = this;

    // Default the caller name.
    // All callers that fail to specifiy a cn share a circuit for each sn:en
    // and fail together.
    var callerName = req.headers.cn || 'no-cn';
    var serviceName = req.serviceName;
    if (!serviceName) {
        return new Result(new ErrorFrame('BadRequest', 'All requests must have a service name'));
    }

    var arg1 = String(req.arg1);
    var circuit = self.getCircuit(callerName, serviceName, arg1);

    if (!circuit.state.shouldRequest()) {
        return new Result(new ErrorFrame('Declined', 'Service is not healthy'));
    }

    return new Result(null, circuit);
};

function ErrorFrame(codeName, message) {
    this.codeName = codeName;
    this.message = message;
}

// Called upon membership change to collect services that the corresponding
// exit node is no longer responsible for.
Circuits.prototype.updateServices = function updateServices() {
    var self = this;
    var serviceNames = Object.keys(self.circuitsByServiceName);
    for (var index = 0; index < serviceNames.length; index++) {
        var serviceName = serviceNames[index];
        if (!self.egressNodes.isExitFor(serviceName)) {
            delete self.circuitsByServiceName[serviceName];
        }
    }
};

Circuits.prototype.emitCircuitStateChange = function emitCircuitStateChange(circuit, newStates) {
    var self = this;
    self.circuitStateChangeEvent.emit(
        self.root,
        new CircuitStateChange(circuit, newStates[0], newStates[1])
    );
};

function Circuit(callerName, serviceName, endpointName) {
    var self = this;
    EventEmitter.call(self);
    StateMachine.call(self);
    self.stateChangedEvent = self.defineEvent('stateChanged');
    self.callerName = callerName || 'no-cn';
    self.serviceName = serviceName;
    self.endpointName = endpointName;
    self.stateOptions = null;
}

inherits(Circuit, EventEmitter);

Circuit.prototype.setState = StateMachine.prototype.setState;

Circuit.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;
    info.callerName = self.callerName;
    info.serviceName = self.serviceName;
    info.endpointName = self.endpointName;
    return info;
};

module.exports = Circuits;
<commit_msg>Circuits: eliminate a event coupling clousers that scale with number of circuits<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var inherits = require('util').inherits;
var EventEmitter = require('tchannel/lib/event_emitter');
var Result = require('bufrw/result');

var states = require('./states.js');
var StateMachine = require('./state_machine.js');

// Each circuit uses the circuits collection as the "nextHandler" for
// "shouldRequest" to consult.  Peers use this hook to weight peers both by
// healthy and other factors, but the circuit only needs to know about health
// before forwarding.

function AlwaysShouldRequestHandler() { }

AlwaysShouldRequestHandler.prototype.shouldRequest = function shouldRequest() {
    return true;
};

var alwaysShouldRequestHandler = new AlwaysShouldRequestHandler();

function CircuitStateChange(circuit, oldState, state) {
    var self = this;
    self.circuit = circuit;
    self.oldState = oldState;
    self.state = state;
}

//  circuit = circuits                        : Circuits
//      .circuitsByServiceName[serviceName]   : ServiceCircuits
//      .circuitsByCallerName[callerName]     : EndpointCircuits
//      .circuitsByEndpointName[endpointName]

function EndpointCircuits(root) {
    var self = this;
    self.root = root;
    self.circuitsByEndpointName = {};
}

EndpointCircuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) {
    var self = this;
    var circuit = self.circuitsByEndpointName['$' + endpointName];
    if (!circuit) {
        circuit = new Circuit(callerName, serviceName, endpointName);
        circuit.stateOptions = new states.StateOptions(circuit, self.root.stateOptions);
        circuit.stateChangedEvent.on(self.root.boundEmitCircuitStateChange);
        circuit.setState(states.HealthyState);
        self.circuitsByEndpointName['$' + endpointName] = circuit;
    }
    return circuit;
};

EndpointCircuits.prototype.collectCircuitTuples = function collectCircuitTuples(tuples) {
    var self = this;
    var endpointNames = Object.keys(self.circuitsByEndpointName);
    for (var index = 0; index < endpointNames.length; index++) {
        var endpointName = endpointNames[index];
        var circuit = self.circuitsByEndpointName[endpointName];
        tuples.push([circuit.callerName, circuit.serviceName, circuit.endpointName]);
    }
};

function ServiceCircuits(root) {
    var self = this;
    self.root = root;
    self.circuitsByCallerName = {};
}

ServiceCircuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) {
    var self = this;
    var circuits = self.circuitsByCallerName['$' + callerName];
    if (!circuits) {
        circuits = new EndpointCircuits(self.root);
        self.circuitsByCallerName['$' + callerName] = circuits;
    }
    return circuits.getCircuit(callerName, serviceName, endpointName);
};

ServiceCircuits.prototype.collectCircuitTuples = function collectCircuitTuples(tuples) {
    var self = this;
    var callerNames = Object.keys(self.circuitsByCallerName);
    for (var index = 0; index < callerNames.length; index++) {
        var callerName = callerNames[index];
        var circuit = self.circuitsByCallerName[callerName];
        circuit.collectCircuitTuples(tuples);
    }
};

function Circuits(options) {
    var self = this;
    EventEmitter.call(self);
    self.circuitStateChangeEvent = self.defineEvent('circuitStateChange');
    self.circuitsByServiceName = {};
    self.config = options.config || {};

    self.stateOptions = new states.StateOptions(null, {
        timeHeap: options.timeHeap,
        timers: options.timers,
        random: options.random,
        nextHandler: alwaysShouldRequestHandler,
        period: self.config.period,
        maxErrorRate: self.config.maxErrorRate,
        minRequests: self.config.minRequests,
        probation: self.config.probation
    });
    self.egressNodes = options.egressNodes;
    self.boundEmitCircuitStateChange = boundEmitCircuitStateChange;

    function boundEmitCircuitStateChange(newStates, circuit) {
        self.emitCircuitStateChange(newStates, circuit);
    }
}

inherits(Circuits, EventEmitter);

Circuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) {
    var self = this;
    var circuits = self.circuitsByServiceName['$' + serviceName];
    if (!circuits) {
        circuits = new ServiceCircuits(self);
        self.circuitsByServiceName['$' + serviceName] = circuits;
    }
    return circuits.getCircuit(callerName, serviceName, endpointName);
};

Circuits.prototype.getCircuitTuples = function getCircuitTuples() {
    var self = this;
    var tuples = [];
    var serviceNames = Object.keys(self.circuitsByServiceName);
    for (var index = 0; index < serviceNames.length; index++) {
        var serviceName = serviceNames[index];
        self.circuitsByServiceName[serviceName].collectCircuitTuples(tuples);
    }
    return tuples;
};

Circuits.prototype.getCircuitForRequest = function getCircuitForRequest(req) {
    var self = this;

    // Default the caller name.
    // All callers that fail to specifiy a cn share a circuit for each sn:en
    // and fail together.
    var callerName = req.headers.cn || 'no-cn';
    var serviceName = req.serviceName;
    if (!serviceName) {
        return new Result(new ErrorFrame('BadRequest', 'All requests must have a service name'));
    }

    var arg1 = String(req.arg1);
    var circuit = self.getCircuit(callerName, serviceName, arg1);

    if (!circuit.state.shouldRequest()) {
        return new Result(new ErrorFrame('Declined', 'Service is not healthy'));
    }

    return new Result(null, circuit);
};

function ErrorFrame(codeName, message) {
    this.codeName = codeName;
    this.message = message;
}

// Called upon membership change to collect services that the corresponding
// exit node is no longer responsible for.
Circuits.prototype.updateServices = function updateServices() {
    var self = this;
    var serviceNames = Object.keys(self.circuitsByServiceName);
    for (var index = 0; index < serviceNames.length; index++) {
        var serviceName = serviceNames[index];
        if (!self.egressNodes.isExitFor(serviceName)) {
            delete self.circuitsByServiceName[serviceName];
        }
    }
};

Circuits.prototype.emitCircuitStateChange = function emitCircuitStateChange(newStates, circuit) {
    var self = this;
    self.circuitStateChangeEvent.emit(
        self.root,
        new CircuitStateChange(circuit, newStates[0], newStates[1])
    );
};

function Circuit(callerName, serviceName, endpointName) {
    var self = this;
    EventEmitter.call(self);
    StateMachine.call(self);
    self.stateChangedEvent = self.defineEvent('stateChanged');
    self.callerName = callerName || 'no-cn';
    self.serviceName = serviceName;
    self.endpointName = endpointName;
    self.stateOptions = null;
}

inherits(Circuit, EventEmitter);

Circuit.prototype.setState = StateMachine.prototype.setState;

Circuit.prototype.extendLogInfo = function extendLogInfo(info) {
    var self = this;
    info.callerName = self.callerName;
    info.serviceName = self.serviceName;
    info.endpointName = self.endpointName;
    return info;
};

module.exports = Circuits;
<|endoftext|>


<commit_before>var Bot = (new function() {
	var _user = KnuddelsServer.getDefaultBotUser();

	this.getNick = function() {
		return _user.getNick();
	};

	this.join = function() {
		_user.joinChannel();
	};

	this.leave = function() {
		_user.leaveChannel();
	};

	this.knuddel = function(user, amount, message) {
		if(message === undefined) {
			_user.transferKnuddel(user, amount);
		} else {
			_user.transferKnuddel(user, amount, message);
		}
	};

	this.getKnuddels = function() {
		return _user.getKnuddelAmount().asNumber();
	};

	this.exception = function(exception) {
		_user.sendPublicMessage('°RR°_Exception:_°r°#' + (exception.message == undefined ? exception : exception.message));
	};

	this.publicMessage = function(message) {
		Logger.info("This shit is _DEPERECATED_!");
		this.public(message);
	}

	this.publicMessage = function(message) {
		if(message instanceof KCode) {
			message = message.toString();
		}
		_user.sendPublicMessage(message);
	};

	this.postMessage = function(user, message, topic) {
		Logger.info("This shit is _DEPERECATED_!");
		this.post(user, message, topic);
	}

	this.post = function(user, message, topic) {
		if(message instanceof KCode) {
			message = message.toString();
		}

		// send to online users
		if(user == undefined) {
			var users = KnuddelsServer.getChannel().getOnlineUsers(UserType.Human);
			for(var index in users) {
				var user = users[index];
				user.sendPostMessage(topic, message);
			}
		} else {
			user.sendPostMessage(topic, message);
		}
	};

	this.privateMessage = function(user, message) {
		Logger.info("This shit is _DEPERECATED_!");
		this.private(user, message);
	}

	this.private = function(user, message) {
		if(message instanceof KCode) {
			message = message.toString();
		}

		// send to online users
		if(user == undefined) {
			var users = KnuddelsServer.getChannel().getOnlineUsers(UserType.Human);
			for(var index in users) {
				var user = users[index];
				user.sendPrivateMessage(message);
				//_user.sendPrivateMessage(message, user);
			}
		} else {
			var users = KnuddelsServer.getChannel().getOnlineUsers(UserType.Human);
			for(var index in users) {
				if(users[index].getNick() == user.toString()) {
					users[index].sendPrivateMessage(message);
				}
				//_user.sendPrivateMessage(message, user);
			}
			//_user.sendPrivateMessage(message, user);
		}
	};

	this.exec = function(command) {
		_user.sendToChannel(command);
	};
}());<commit_msg>bot easing<commit_after>var Bot = (new function() {
	var _user = KnuddelsServer.getDefaultBotUser();

	this.getNick = function() {
		return _user.getNick();
	};

	this.join = function() {
		_user.joinChannel();
	};

	this.leave = function() {
		_user.leaveChannel();
	};

	this.knuddel = function(user, amount, message) {
		if(message === undefined) {
			_user.transferKnuddel(user, amount);
		} else {
			_user.transferKnuddel(user, amount, message);
		}
	};

	this.getKnuddels = function() {
		return _user.getKnuddelAmount().asNumber();
	};

	this.exception = function(exception) {
		_user.sendPublicMessage('°RR°_Exception:_°r°#' + (exception.message == undefined ? exception : exception.message));
	};

	this.publicMessage = function(message) {
		Logger.info("This shit is _DEPERECATED_!");
		this.public(message);
	}

	this.postMessage = function(user, message, topic) {
		Logger.info("This shit is _DEPERECATED_!");
		this.post(user, message, topic);
	}

	this.privateMessage = function(user, message) {
		Logger.info("This shit is _DEPERECATED_!");
		this.private(user, message);
	}

	this.public = function(message) {
		if(message instanceof KCode) {
			message = message.toString();
		}
		_user.sendPublicMessage(message);
	};

	this.post = function(user, message, topic) {
		if(message instanceof KCode) {
			message = message.toString();
		}

		// send to online users
		if(user == undefined) {
			var users = KnuddelsServer.getChannel().getOnlineUsers(UserType.Human);
			for(var index in users) {
				var user = users[index];
				user.sendPostMessage(topic, message);
			}
		} else {
			user.sendPostMessage(topic, message);
		}
	};

	this.private = function(user, message) {
		if(message instanceof KCode) {
			message = message.toString();
		}

		// send to online users
		if(user == undefined) {
			var users = KnuddelsServer.getChannel().getOnlineUsers(UserType.Human);
			for(var index in users) {
				var user = users[index];
				user.sendPrivateMessage(message);
				//_user.sendPrivateMessage(message, user);
			}
		} else {
			var users = KnuddelsServer.getChannel().getOnlineUsers(UserType.Human);
			for(var index in users) {
				if(users[index].getNick() == user.toString()) {
					users[index].sendPrivateMessage(message);
				}
				//_user.sendPrivateMessage(message, user);
			}
			//_user.sendPrivateMessage(message, user);
		}
	};

	this.exec = function(command) {
		_user.sendToChannel(command);
	};
}());<|endoftext|>


<commit_before>define(['jquery', 'lodash'], function ($, _) {
    'use strict';

    return {
        killParticle: function (particle) {
            $(particle).removeClass('elementalParticle');
        },
        setExistence: function(newVal, particle) {
            particle.existence = newVal;
            particle.isAlive = false;
            this.killParticle(particle);
        },
        deadCowntDown: function (particle) {
            // web worker
            var worker = new Worker('core/workers.js'),
                that = this;
            worker.addEventListener('message', function(e) {
                if (e.data === 0) {
                    that.setExistence(e.data, particle);
                }
            });
            worker.postMessage({ 'ex': particle.existence });
        },
        upLevel: function (self) {
            self.size = self.size * 2;
            self.strength = self.strength * 2;
            self.existence = self.existence + 30;
            self.speed = self.speed * 2;
            return self;
        },
        detectDomElement: function (node, name, options) {
            _.map(node.childNodes, function(n) {
                if (n.tagName === 'SELECT') {
                    var nodeName = n.getAttribute('name');
                    if (nodeName === name) {
                        _.each(options, function(op, i) {
                            $(n).append('<option class="selectTableSize' + i + '">' + op + '</option>');
                        });
                    }
                }
            });
        },
        randomNumber: function (first, last) {
            return _.random(first, last);
        },
        detectSelect: function (node, name) {
            var newObj = null;
            _.each(node.childNodes, function(n) {
                if (n.tagName === 'SELECT') {
                    var nodeName = n.getAttribute('name');
                    if (nodeName === name) {
                        newObj = n;
                    }
                }
            });
            return newObj;
        },
        returnClasses: function (data) {
            var result = [];
            _.map(data, function(n) {
                if (n.tagName === 'TR' || n.tagName === 'TD') {
                    result.push(n.className);
                }
            });
            return result;
        },
        particlesFight: function(particle) {
            console.log('particle fight');
        },
        movements: ['top', 'bottom', 'right', 'left'],
        sizeOptions: ['100 x 300', '300 x 600', '600 x 800', '800 x 1200', '1200 x 1400', '1400 x 1600'],
        particleOptions: ['Random', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '200', '300', '400', '500', '600', '700', '800', '900', '1000'],
        moveTop: function(particle) {
            if (!_.isUndefined(particle.className)) {
                var self = this,
                    particleName = particle.getAttribute('name'),
                    particleParent = particle.parentNode,
                    particleParentData = particleParent.getAttribute('data'),
                    upTrNum = particleParentData - 10,
                    upTr = document.getElementsByClassName('tr' + upTrNum);

                    if (!_.isUndefined(upTr)) {
                        _.map(upTr[0].childNodes, function(n) {
                            var nName = n.getAttribute('name');
                            if (n.tagName === 'TD' && nName === particleName) {
                                if (n.className === nName + ' elementalParticle') {
                                    self.particlesFight(particle);
                                } else {
                                    $(particle).removeClass('elementalParticle');
                                    $(n).addClass('elementalParticle');
                                }
                            }
                        });
                    }
            }
        },
        moveBottom: function(particle) {
            if (!_.isUndefined(particle.className)) {
                var self = this,
                    particleName = particle.getAttribute('name'),
                    particleParent = particle.parentNode,
                    particleParentData = particleParent.getAttribute('data'),
                    upTrNum = particleParentData + 10,
                    upTr = document.getElementsByClassName('tr' + upTrNum);

                    if (!_.isUndefined(upTr)) {
                        _.map(upTr[0].childNodes, function(n) {
                            var nName = n.getAttribute('name');
                            if (n.tagName === 'TD' && nName === particleName) {
                                if (n.className === nName + ' elementalParticle') {
                                    self.particlesFight(particle);
                                } else {
                                    $(particle).removeClass('elementalParticle');
                                    $(n).addClass('elementalParticle');
                                }
                            }
                        });
                    }
            }
        },
        moveRight: function(particle) {
            // TODO: Think how to do this
        },
        moveLeft: function(particle) {
            // TODO: Think how to do this
        }
    };
});
<commit_msg>Working in particle movements<commit_after>define(['jquery', 'lodash'], function ($, _) {
    'use strict';

    return {
        killParticle: function (particle) {
            $(particle).removeClass('elementalParticle');
        },
        setExistence: function(newVal, particle) {
            particle.existence = newVal;
            particle.isAlive = false;
            this.killParticle(particle);
        },
        deadCowntDown: function (particle) {
            // web worker
            var worker = new Worker('core/workers.js'),
                that = this;
            worker.addEventListener('message', function(e) {
                if (e.data === 0) {
                    that.setExistence(e.data, particle);
                }
            });
            worker.postMessage({ 'ex': particle.existence });
        },
        upLevel: function (self) {
            self.size = self.size * 2;
            self.strength = self.strength * 2;
            self.existence = self.existence + 30;
            self.speed = self.speed * 2;
            return self;
        },
        detectDomElement: function (node, name, options) {
            _.map(node.childNodes, function(n) {
                if (n.tagName === 'SELECT') {
                    var nodeName = n.getAttribute('name');
                    if (nodeName === name) {
                        _.each(options, function(op, i) {
                            $(n).append('<option class="selectTableSize' + i + '">' + op + '</option>');
                        });
                    }
                }
            });
        },
        randomNumber: function (first, last) {
            return _.random(first, last);
        },
        detectSelect: function (node, name) {
            var newObj = null;
            _.each(node.childNodes, function(n) {
                if (n.tagName === 'SELECT') {
                    var nodeName = n.getAttribute('name');
                    if (nodeName === name) {
                        newObj = n;
                    }
                }
            });
            return newObj;
        },
        returnClasses: function (data) {
            var result = [];
            _.map(data, function(n) {
                if (n.tagName === 'TR' || n.tagName === 'TD') {
                    result.push(n.className);
                }
            });
            return result;
        },
        particlesFight: function(particle) {
            console.log('particle fight');
        },
        movements: ['top', 'bottom', 'right', 'left'],
        sizeOptions: ['100 x 300', '300 x 600', '600 x 800', '800 x 1200', '1200 x 1400', '1400 x 1600'],
        particleOptions: ['Random', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '200', '300', '400', '500', '600', '700', '800', '900', '1000'],
        moveTop: function(particle) {
            if (!_.isUndefined(particle.className)) {
                var self = this,
                    particleName = particle.getAttribute('name'),
                    particleParent = particle.parentNode,
                    particleParentData = particleParent.getAttribute('data'),
                    upTrNum = particleParentData - 10,
                    upTr = document.getElementsByClassName('tr' + upTrNum);

                    if (!_.isUndefined(upTr)) {
                        _.map(upTr[0].childNodes, function(n) {
                            var nName = n.getAttribute('name');
                            if (n.tagName === 'TD' && nName === particleName) {
                                if (n.className === nName + ' elementalParticle') {
                                    self.particlesFight(particle);
                                } else {
                                    $(particle).removeClass('elementalParticle');
                                    $(n).addClass('elementalParticle');
                                }
                            }
                        });
                    }
            }
        },
        moveBottom: function(particle) {
            if (!_.isUndefined(particle.className)) {
                var self = this,
                    particleName = particle.getAttribute('name'),
                    particleParent = particle.parentNode,
                    particleParentData = particleParent.getAttribute('data'),
                    upTrNum = particleParentData + 10,
                    upTr = document.getElementsByClassName('tr' + upTrNum);

                    if (!_.isUndefined(upTr)) {
                        _.map(upTr[0].childNodes, function(n) {
                            var nName = n.getAttribute('name');
                            if (n.tagName === 'TD' && nName === particleName) {
                                if (n.className === nName + ' elementalParticle') {
                                    self.particlesFight(particle);
                                } else {
                                    $(particle).removeClass('elementalParticle');
                                    $(n).addClass('elementalParticle');
                                }
                            }
                        });
                    }
            }
        },
        moveRight: function(particle) {
            if (!_.isUndefined(particle.className)) {
                var prevTd = $(particle).prev();
                $(particle).removeClass('elementalParticle');
                $(prevTd).addClass('elementalParticle');
            }
        },
        moveLeft: function(particle) {
            if (!_.isUndefined(particle.className)) {
                var nextTd = $(particle).next();
                $(particle).removeClass('elementalParticle');
                $(nextTd).addClass('elementalParticle');
            }
        }
    };
});
<|endoftext|>


<commit_before>var net = require('net');

var shortid = require('shortid');
var Discord = require('discord.io');

class Bot {
	constructor(key, disnode) {
		this.key = key;
		this.client = {};
		this.disnode = disnode;
		this.bind_onMessage = null;
		this.isRemote = false;
		this.remoteID = "";
	}

	Connect() {
		var self = this;
		return new Promise(function (resolve, reject) {

			if (self.disnode.botConfig.balancerEnabled == true) {
				if (!self.disnode.botConfig.balancerIP) {
					reject("No Load Balancer IP!");
				}
				if (!self.disnode.botConfig.balancerPORT) {
					reject("No Load Balancer Port!");
				}

				self.client.type == "REMOTE";
				self.client = new net.Socket();
				self.client.connect(self.disnode.botConfig.balancerPORT, self.disnode.botConfig.balancerIP, function () {
					self.remoteID = shortid.generate();
					self.client.write(JSON.stringify({
						type: "REGISTER",
						id: self.remoteID
					}))
					self.client.on('data', (data) => self.ParseRemoteCommand(data));
					self.isRemote = true;
					resolve("Connected to remote Load Balancer!");
					return;
				});
			} else {
				self.client = new Discord.Client({
					autorun: true,
					token: self.key
				});

				self.client.on('ready', function (event) {
					self.SetUpLocalBinds();
					resolve();
				});

			}

		});
	}

	Disconnect() {
		var self = this;
		return new Promise(function (resolve, reject) {
			self.client.disconnect();
			resolve();
		});
	}

	Restart() {
		var self = this;
		self.Disconnect().then(function (){
			self.client.connect()
		});
	}

	ParseRemoteCommand(command) {
		var self = this;
		var obj = JSON.parse(command);

		switch (obj.type) {
		case "RECV_MESSAGE":

			if (self.bind_onMessage) {
				self.bind_onMessage(obj.data);
			} else {

			}
		}
	}

	SetUpLocalBinds() {
		var self = this;
		self.client.on('message', function (user, userID, channelID, message, event) {
			if (self.bind_onMessage) {
				var _server = "DM";
				if(self.client.channels[channelID]){
						_server = self.client.channels[channelID].guild_id;
				}
				var msgObject = {
					user: user,
					userID: userID,
					channel: channelID,
					message: message,
					server: _server
				}
				self.bind_onMessage(msgObject);
			}
		});
	}

	bindOnMessage(msgFunction) {
		this.bind_onMessage = msgFunction;
	}

	SendMessage(channel, msg, typing=false, tts=false) {
		var self = this;
		if (self.isRemote) {
			var msgOBJ = {
				channel: channel,
				msg: msg,
				typing: typing,
      	tts: tts
			};
			var commandObj = {
				type: "SEND_MESSAGE",
				id: self.remoteID,
				data: msgOBJ
			};

			self.client.write(JSON.stringify(commandObj));
		}else{
			return new Promise(function(resolve, reject) {
				self.client.sendMessage({
					to: channel,
					message: msg,
		 			typing: typing,
		      tts: tts
				}, function(err, resp) {
					if(err){
						reject(err);
					}else {
						resolve(resp);
					}
				});
			});
		}
	}
	SendEmbed(channel, embed){
		var self = this;
		self.client.sendMessage({
			to: channel,
			embed: embed
		});
	}
	SendCompactEmbed(channel, title, body) {
		var self = this;
		self.client.sendMessage({
			to: channel,
			embed: {
				color: 3447003,
				author: {},
				fields: [{
					name: title,
					inline: false,
					value: body,
				}],
				footer: {}
			}
		});
	}
	SetStatus(status){
		var self = this;
		self.client.setPresence({game: {name: status}});
	}

	SetUsername(name){
		var self = this;
		self.client.editUserInfo({username: name});
	}

	JoinVoiceChannel(voiceID){
		var self = this;
		this.client.joinVoiceChannel(voiceID,function(err){
			if(err){
				console.log(err);
			}else{
			}
		})
	}

  LeaveVoiceChannel(voiceID){
		var self = this;
		this.client.leaveVoiceChannel(voiceID,function(err){
			if(err){
				console.log(err);
			}else{
			}
		})
	}
		JoinUsersVoiceChannel(serverID, userID){
		var user = this.GetUserByID(serverID, userID);
		if(!user){
			return;
		}
		this.JoinVoiceChannel(user.voice_channel_id);
	}
    LeaveUsersVoiceChannel(serverID, userID) {
    var user = this.GetUserByID(serverID, userID);
		if(!user){
			return;
		}
			this.LeaveVoiceChannel(user.voice_channel_id);
  }
		GetServerByID(id){
		var servers = this.client.servers;
		return servers[id];
	}
		GetUserByID(serverId, userId){
		var server = this.GetServerByID(serverId);
		if(!server){
			return;
		}
		return server.members[userId];
	}
		GetUserRoles(serverId, userId){
		var user = this.GetUserByID(serverId, userId);
		if(!user){
			return;
		}
		return user.roles;
	}

	GetRoleById(serverId, roleId){
		var server = this.GetServerByID(serverId);
		if(!server){
			return;
		}
		return server.roles[roleId];
	}
	//Oh hey im a comment!
	GetBotInfo(){
		var self = this;
		return {
			username: self.client.username,
			id: self.client.id,
			avatar: self.client.avatar,
			bot: self.client.bot,
			discriminator: self.client.discriminator,
		}
	}
	GetUserInfo(UserID){
		var self = this;
		return self.client.users[userID];
	}
}

module.exports = Bot;
<commit_msg>No More Comment!<commit_after>var net = require('net');

var shortid = require('shortid');
var Discord = require('discord.io');

class Bot {
	constructor(key, disnode) {
		this.key = key;
		this.client = {};
		this.disnode = disnode;
		this.bind_onMessage = null;
		this.isRemote = false;
		this.remoteID = "";
	}

	Connect() {
		var self = this;
		return new Promise(function (resolve, reject) {

			if (self.disnode.botConfig.balancerEnabled == true) {
				if (!self.disnode.botConfig.balancerIP) {
					reject("No Load Balancer IP!");
				}
				if (!self.disnode.botConfig.balancerPORT) {
					reject("No Load Balancer Port!");
				}

				self.client.type == "REMOTE";
				self.client = new net.Socket();
				self.client.connect(self.disnode.botConfig.balancerPORT, self.disnode.botConfig.balancerIP, function () {
					self.remoteID = shortid.generate();
					self.client.write(JSON.stringify({
						type: "REGISTER",
						id: self.remoteID
					}))
					self.client.on('data', (data) => self.ParseRemoteCommand(data));
					self.isRemote = true;
					resolve("Connected to remote Load Balancer!");
					return;
				});
			} else {
				self.client = new Discord.Client({
					autorun: true,
					token: self.key
				});

				self.client.on('ready', function (event) {
					self.SetUpLocalBinds();
					resolve();
				});

			}

		});
	}

	Disconnect() {
		var self = this;
		return new Promise(function (resolve, reject) {
			self.client.disconnect();
			resolve();
		});
	}

	Restart() {
		var self = this;
		self.Disconnect().then(function (){
			self.client.connect()
		});
	}

	ParseRemoteCommand(command) {
		var self = this;
		var obj = JSON.parse(command);

		switch (obj.type) {
		case "RECV_MESSAGE":

			if (self.bind_onMessage) {
				self.bind_onMessage(obj.data);
			} else {

			}
		}
	}

	SetUpLocalBinds() {
		var self = this;
		self.client.on('message', function (user, userID, channelID, message, event) {
			if (self.bind_onMessage) {
				var _server = "DM";
				if(self.client.channels[channelID]){
						_server = self.client.channels[channelID].guild_id;
				}
				var msgObject = {
					user: user,
					userID: userID,
					channel: channelID,
					message: message,
					server: _server
				}
				self.bind_onMessage(msgObject);
			}
		});
	}

	bindOnMessage(msgFunction) {
		this.bind_onMessage = msgFunction;
	}

	SendMessage(channel, msg, typing=false, tts=false) {
		var self = this;
		if (self.isRemote) {
			var msgOBJ = {
				channel: channel,
				msg: msg,
				typing: typing,
      	tts: tts
			};
			var commandObj = {
				type: "SEND_MESSAGE",
				id: self.remoteID,
				data: msgOBJ
			};

			self.client.write(JSON.stringify(commandObj));
		}else{
			return new Promise(function(resolve, reject) {
				self.client.sendMessage({
					to: channel,
					message: msg,
		 			typing: typing,
		      tts: tts
				}, function(err, resp) {
					if(err){
						reject(err);
					}else {
						resolve(resp);
					}
				});
			});
		}
	}
	SendEmbed(channel, embed){
		var self = this;
		self.client.sendMessage({
			to: channel,
			embed: embed
		});
	}
	SendCompactEmbed(channel, title, body) {
		var self = this;
		self.client.sendMessage({
			to: channel,
			embed: {
				color: 3447003,
				author: {},
				fields: [{
					name: title,
					inline: false,
					value: body,
				}],
				footer: {}
			}
		});
	}
	SetStatus(status){
		var self = this;
		self.client.setPresence({game: {name: status}});
	}

	SetUsername(name){
		var self = this;
		self.client.editUserInfo({username: name});
	}

	JoinVoiceChannel(voiceID){
		var self = this;
		this.client.joinVoiceChannel(voiceID,function(err){
			if(err){
				console.log(err);
			}else{
			}
		})
	}

  LeaveVoiceChannel(voiceID){
		var self = this;
		this.client.leaveVoiceChannel(voiceID,function(err){
			if(err){
				console.log(err);
			}else{
			}
		})
	}
		JoinUsersVoiceChannel(serverID, userID){
		var user = this.GetUserByID(serverID, userID);
		if(!user){
			return;
		}
		this.JoinVoiceChannel(user.voice_channel_id);
	}
    LeaveUsersVoiceChannel(serverID, userID) {
    var user = this.GetUserByID(serverID, userID);
		if(!user){
			return;
		}
			this.LeaveVoiceChannel(user.voice_channel_id);
  }
		GetServerByID(id){
		var servers = this.client.servers;
		return servers[id];
	}
		GetUserByID(serverId, userId){
		var server = this.GetServerByID(serverId);
		if(!server){
			return;
		}
		return server.members[userId];
	}
		GetUserRoles(serverId, userId){
		var user = this.GetUserByID(serverId, userId);
		if(!user){
			return;
		}
		return user.roles;
	}

	GetRoleById(serverId, roleId){
		var server = this.GetServerByID(serverId);
		if(!server){
			return;
		}
		return server.roles[roleId];
	}
	GetBotInfo(){
		var self = this;
		return {
			username: self.client.username,
			id: self.client.id,
			avatar: self.client.avatar,
			bot: self.client.bot,
			discriminator: self.client.discriminator,
		}
	}
	GetUserInfo(UserID){
		var self = this;
		return self.client.users[userID];
	}
}

module.exports = Bot;
<|endoftext|>