<commit_before>this.BlackBox = (function(EventEmitter, extendClass, hasOwnProperty, Queue, getUndefined, Map, Set){
  var errorListener = function(e){

    if (!hasOwnProperty(this, "_lastError"))
      this._lastError = e;
  };
  var init = (function(){

    var processWire, processBlock;

    processWire = function(wire, wireSet, blockSet){

      // Check if this wire has already been processed
      if (!wireSet.has(wire)){

        // Wire has not been processed
        // Add wire to wire set
        wireSet.add(wire);

        // Process all blocks connected to the wire
        var it = wire.connections();
        while (!it.peek().done)
          processBlock(it.next().value.block, wireSet, blockSet);
      }
    };

    processBlock = function(block, wireSet, blockSet){

      // Check if this block has already been processed
      if (!blockSet.has(block)){

        // Block has not been processed
        // Add block to block set
        blockSet.add(block);

        // Process all wires connected to the block
        var it = block.connections();
        while (!it.peek().done)
          processWire(it.next().value.wire, wireSet, blockSet);
      }
    };

    return function(pins){

      // Create wire set and block set
      // These collect all wires and blocks in the network
      var wireSet = new Set();
      var blockSet = new Set();

      // Process pins hash
      for (var pin in pins){

        // Add pin to internal wire hash
        this._internalWires[pin] = pins[pin].wire;

        // Process the wire and all connected blocks
        processWire(pins[pin].wire, wireSet, blockSet);
      }

      // All blocks are in the block set now
      // Attach "error" event listener to all blocks in the network
      var it = blockSet.values();
      while (!it.peek().done)
        it.next().value.on("error", this._errorListener);
    };
  }());
  function BlackBox(hash){

    EventEmitter.call(this);

    this._updating = false;
    this._internalWires = {};
    this._externalWires = {};
    this._errorListener = errorListener.bind(this);

    if (typeof hash !== "undefined"){

      // Add pins if supplied
      if (hasOwnProperty(hash, "pins"))
        init.call(this, hash.pins);

      // Add queue if supplied
      if (hasOwnProperty(hash, "queue"))
        this._updateQueue = hash.queue;
    }

    // Set defaults
    if (!hasOwnProperty(this, "_updateQueue"))
      this._updateQueue = new Queue();
  }
  extendClass(EventEmitter, BlackBox);
  var P = BlackBox.prototype;
  P.duplicate = (function(){

    var processWire, processBlock;

    processWire = function(wire, wireMap, blockMap){

      // Check if this wire has already been processed
      var duplicate = wireMap.get(wire);
      if (duplicate)
        return duplicate;

      // Wire has not been processed
      // Duplicate the wire
      duplicate = wire.duplicate();

      // Add duplicate wire to wire map
      wireMap.put(wire, duplicate);

      // Process all blocks connected to the wire
      var it = wire.connections();
      while (!it.peek().done)
        processBlock(it.next().value.block, wireMap, blockMap);

      // Return duplicate wire
      return duplicate;
    };

    processBlock = function(block, wireMap, blockMap){

      // Check if this block has already been processed
      var duplicate = blockMap.get(block);
      if (duplicate)
        return duplicate;

      // Block has not been processed
      // Duplicate the block
      duplicate = block.duplicate();

      // Add duplicate block to block map
      blockMap.put(block, duplicate);

      // Process all wires connected to the block
      var it = block.connections();
      while (!it.peek().done){

        // Process and get the duplicate wire
        var wire = processWire(it.peek().value.wire, wireMap, blockMap);

        // Connect the duplicate block to the duplicate wire
        duplicate.connect(it.next().value.pin, wire);
      }

      // Return duplicate block
      return duplicate;
    };

    return function(){

      // Create wire map and block map
      // These map wires and blocks in the original circuit to their duplicates
      var wireMap = new Map();
      var blockMap = new Map();

      // Construct pins hash for the new BlackBox
      var pins;
      for (var pin in this._internalWires)
        pins[pin] = processWire(this._internalWires[pin], wireMap, blockMap);

      // Return the new BlackBox
      return new BlackBox({pins: pins, queue: this._updateQueue.duplicate()});
    };
  }());
  P.update = function(pin){

    // A connected wire value changed

    // Check updating flag
    if (this._updating){

      // Add update to queue and return
      this._updateQueue.push(pin);
      return;
    }
    else
      this._updating = true; // Set updating flag

    // Main loop
    while (true){

      // Defensive copy external wires
      // Internal wires should never change
      var internalWires = this._internalWires, externalWires = {};
      for (var name in internalWires){

        if (this._externalWires[name])
          externalWires[name] = this._externalWires[name];
      }

      // Get updated pin value
      var value;
      if(externalWires[pin])
        value = externalWires[pin].value();
      else
        value = getUndefined();

      // Fire update event
      this.fire("update", {pin: pin, value: value});

      // Clear last error, if any
      delete this._lastError;

      // Copy values from external wires to internal wires
      for (var name in internalWires){

        if (externalWires[name])
          internalWires[name].value(externalWires[name].value());
        else
          internalWires[name].value(getUndefined());
      }

      // Handle successful run
      if (!hasOwnProperty(this, "_lastError")){

        // Fire event
        this.fire("success");

        // Copy values from internal wires to external wires
        for (var name in internalWires){

          if (externalWires[name])
            externalWires[name].value(internalWires[name].value());
        }
      }
      else
        this.fire("error", this._lastError); // Fire event

      // Proces update queue
      if (this._updateQueue.isEmpty()){

        // Unset updating flag and return
        this._updating = false;
        return;
      }
      else
        pin = this._updateQueue.next(); // Get next updated pin from queue

      // Restart loop
    }
  };
  return BlackBox;
}(this.EventEmitter, this.extendClass, this.hasOwnProperty, this.Queue, this.getUndefined, this.Map, this.Set));

<commit_msg>Flesh out BlackBox class<commit_after>this.BlackBox = (function(EventEmitter, extendClass, hasOwnProperty, Queue, getUndefined, Map, Set, Error){
  var errorListener = function(e){

    if (!hasOwnProperty(this, "_lastError"))
      this._lastError = e;
  };
  var _disconnect = function(pin){

    // Disconnect from wire, if any
    if (hasOwnProperty(this._externalWires, pin)){

      var wire = this._externalWires[pin];
      wire.unbind(this, pin);
      delete this._externalWires[pin];

      // Fire disconnect event
      this.fire("disconnect", {pin: pin, wire: wire});
    }
  };
  var init = (function(){

    var processWire, processBlock;

    processWire = function(wire, wireSet, blockSet){

      // Check if this wire has already been processed
      if (!wireSet.has(wire)){

        // Wire has not been processed
        // Add wire to wire set
        wireSet.add(wire);

        // Process all blocks connected to the wire
        var it = wire.connections();
        while (!it.peek().done)
          processBlock(it.next().value.block, wireSet, blockSet);
      }
    };

    processBlock = function(block, wireSet, blockSet){

      // Check if this block has already been processed
      if (!blockSet.has(block)){

        // Block has not been processed
        // Add block to block set
        blockSet.add(block);

        // Process all wires connected to the block
        var it = block.connections();
        while (!it.peek().done)
          processWire(it.next().value.wire, wireSet, blockSet);
      }
    };

    return function(pins){

      // Create wire set and block set
      // These collect all wires and blocks in the network
      var wireSet = new Set();
      var blockSet = new Set();

      // Process pins hash
      for (var pin in pins){

        // Add pin to internal wire hash
        this._internalWires[pin] = pins[pin].wire;

        // Process the wire and all connected blocks
        processWire(pins[pin].wire, wireSet, blockSet);
      }

      // All blocks are in the block set now
      // Attach "error" event listener to all blocks in the network
      var it = blockSet.values();
      while (!it.peek().done)
        it.next().value.on("error", this._errorListener);
    };
  }());
  function BlackBox(hash){

    EventEmitter.call(this);

    this._updating = false;
    this._internalWires = {};
    this._externalWires = {};
    this._errorListener = errorListener.bind(this);

    if (typeof hash !== "undefined"){

      // Add pins if supplied
      if (hasOwnProperty(hash, "pins"))
        init.call(this, hash.pins);

      // Add queue if supplied
      if (hasOwnProperty(hash, "queue"))
        this._updateQueue = hash.queue;
    }

    // Set defaults
    if (!hasOwnProperty(this, "_updateQueue"))
      this._updateQueue = new Queue();
  }
  extendClass(EventEmitter, BlackBox);
  var P = BlackBox.prototype;
  P.duplicate = (function(){

    var processWire, processBlock;

    processWire = function(wire, wireMap, blockMap){

      // Check if this wire has already been processed
      var duplicate = wireMap.get(wire);
      if (duplicate)
        return duplicate;

      // Wire has not been processed
      // Duplicate the wire
      duplicate = wire.duplicate();

      // Add duplicate wire to wire map
      wireMap.put(wire, duplicate);

      // Process all blocks connected to the wire
      var it = wire.connections();
      while (!it.peek().done)
        processBlock(it.next().value.block, wireMap, blockMap);

      // Return duplicate wire
      return duplicate;
    };

    processBlock = function(block, wireMap, blockMap){

      // Check if this block has already been processed
      var duplicate = blockMap.get(block);
      if (duplicate)
        return duplicate;

      // Block has not been processed
      // Duplicate the block
      duplicate = block.duplicate();

      // Add duplicate block to block map
      blockMap.put(block, duplicate);

      // Process all wires connected to the block
      var it = block.connections();
      while (!it.peek().done){

        // Process and get the duplicate wire
        var wire = processWire(it.peek().value.wire, wireMap, blockMap);

        // Connect the duplicate block to the duplicate wire
        duplicate.connect(it.next().value.pin, wire);
      }

      // Return duplicate block
      return duplicate;
    };

    return function(){

      // Create wire map and block map
      // These map wires and blocks in the original circuit to their duplicates
      var wireMap = new Map();
      var blockMap = new Map();

      // Construct pins hash for the new BlackBox
      var pins;
      for (var pin in this._internalWires)
        pins[pin] = processWire(this._internalWires[pin], wireMap, blockMap);

      // Return the new BlackBox
      return new BlackBox({pins: pins, queue: this._updateQueue.duplicate()});
    };
  }());
  P.error = function(){

    return this._lastError;
  };
  P.connect = function(pin, wire){

    // Throw error if pin does not exist
    if (!hasOwnProperty(this._internalWires, pin))
      throw new Error("Pin \"" + pin + "\" not found");

    // Do nothing if the pin is already connected to the wire
    if (this._externalWires[pin] !== wire){

      // Disconnect from old wire, if any
      _disconnect.call(this, pin);

      // Record new wire
      this._externalWires[pin] = wire;

      // Bind pin to wire
      wire.bind(this, pin);

      // Fire connect event
      this.fire("connect", {pin: pin, wire: wire});

      // Process wire value
      this.update(pin);
    }
  };
  P.disconnect = function(pin){

    // Disconnect from wire, if any
    _disconnect.call(this, pin);

    // Process wire value
    this.update(pin);
  };
  P.update = function(pin){

    // A connected wire value changed

    // Check updating flag
    if (this._updating){

      // Add update to queue and return
      this._updateQueue.push(pin);
      return;
    }
    else
      this._updating = true; // Set updating flag

    // Main loop
    while (true){

      // Defensive copy internal and external wires
      var internalWires = {}, externalWires = {};
      for (var name in internalWires){

        // Copy internal wire
        internalWires[name] = this._internalWires[name];

        // Copy external wire, if exists
        if (this._externalWires[name])
          externalWires[name] = this._externalWires[name];
      }

      // Get updated pin value
      var value;
      if(externalWires[pin])
        value = externalWires[pin].value();
      else
        value = getUndefined();

      // Fire update event
      this.fire("update", {pin: pin, value: value});

      // Clear last error, if any
      delete this._lastError;

      // Copy values from external wires to internal wires
      for (var name in internalWires){

        if (externalWires[name])
          internalWires[name].value(externalWires[name].value());
        else
          internalWires[name].value(getUndefined());
      }

      // Handle successful run
      if (!hasOwnProperty(this, "_lastError")){

        // Fire event
        this.fire("success");

        // Copy values from internal wires to external wires
        for (var name in internalWires){

          if (externalWires[name])
            externalWires[name].value(internalWires[name].value());
        }
      }
      else
        this.fire("error", this._lastError); // Fire event

      // Proces update queue
      if (this._updateQueue.isEmpty()){

        // Unset updating flag and return
        this._updating = false;
        return;
      }
      else
        pin = this._updateQueue.next(); // Get next updated pin from queue

      // Restart loop
    }
  };
  P.pins = function(){

    // Collect pins in a set
    var pinSet = new Set();
    for (var pin in this._internalWires)
      pinSet.add({pin: pin, wire: this._internalWires[pin]});

    // Return set iterator
    return pinSet.values();
  };
  return BlackBox;
}(this.EventEmitter, this.extendClass, this.hasOwnProperty, this.Queue, this.getUndefined, this.Map, this.Set, host.Error));

<|endoftext|>


<commit_before>/*eslint-env mocha*/
/*global assert*/

describe("e2e/06-bugs/92560", function() {
	function test(href, expected) {
		var anchor = document.createElement("a");
		anchor.href = href;
		assert.equal(
			BOOMR.plugins.AutoXHR.getPathname(anchor),
			expected);
	}

	var tf = BOOMR.plugins.TestFramework;
	it("Should get only 2 beacons: 1 onload, 1 xhr (2nd xhr should be excluded)", function(done) {
		tf.ifAutoXHR(
			done,
			function() {
				tf.ensureBeaconCount(done,  2);
			});
	});

	it("getPathname test - path/file.js", function() {
		test("path/file.js", "/pages/06-bugs/path/file.js");
	});

	it("getPathname test - /path/file.js", function() {
		test("/path/file.js", "/path/file.js");
	});

	it("getPathname test - //path/file.js", function() {
		test("//path/file.js", "/file.js");
	});

	it("getPathname test - ./path/file.js", function() {
		test("./path/file.js", "/pages/06-bugs/path/file.js");
	});

	it("getPathname test - ../path/file.js", function() {
		test("../path/file.js", "/pages/path/file.js");
	});

	it("getPathname test - #ref", function() {
		test("#ref", "/pages/06-bugs/92560.html");
	});

	it("getPathname test - ?val=1", function() {
		test("?val=1", "/pages/06-bugs/92560.html");
	});

	it("getPathname test - (empty string))", function() {
		test("", "/pages/06-bugs/92560.html");
	});

	it("getPathname test - ../../../../file.js", function() {
		test("../../../../file.js", "/file.js");
	});

});
<commit_msg>06-bugs/92560: Remove getPathname test for empty string<commit_after>/*eslint-env mocha*/
/*global assert*/

describe("e2e/06-bugs/92560", function() {
	function test(href, expected) {
		var anchor = document.createElement("a");
		anchor.href = href;
		assert.equal(
			BOOMR.plugins.AutoXHR.getPathname(anchor),
			expected);
	}

	var tf = BOOMR.plugins.TestFramework;
	it("Should get only 2 beacons: 1 onload, 1 xhr (2nd xhr should be excluded)", function(done) {
		// because the XHRs might take over a second
		this.timeout(10000);

		t.ifAutoXHR(
			done,
			function() {
				tf.ensureBeaconCount(done,  2);
			});
	});

	it("getPathname test - path/file.js", function() {
		test("path/file.js", "/pages/06-bugs/path/file.js");
	});

	it("getPathname test - /path/file.js", function() {
		test("/path/file.js", "/path/file.js");
	});

	it("getPathname test - //path/file.js", function() {
		test("//path/file.js", "/file.js");
	});

	it("getPathname test - ./path/file.js", function() {
		test("./path/file.js", "/pages/06-bugs/path/file.js");
	});

	it("getPathname test - ../path/file.js", function() {
		test("../path/file.js", "/pages/path/file.js");
	});

	it("getPathname test - #ref", function() {
		test("#ref", "/pages/06-bugs/92560.html");
	});

	it("getPathname test - ?val=1", function() {
		test("?val=1", "/pages/06-bugs/92560.html");
	});

	it("getPathname test - ../../../../file.js", function() {
		test("../../../../file.js", "/file.js");
	});

});
<|endoftext|>


<commit_before>/*    Copyright 2019 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict'

let instance = null;

const exec = require('child-process-promise').exec;
const fConfig = require('../../net2/config.js').getConfig();
const log = require('../../net2/logger.js')(__filename);

const sysManager = require('../../net2/SysManager.js');

const platformLoader = require('../../platform/PlatformLoader.js');
const platform = platformLoader.getPlatform();
const model = platform.getName();
const serial = platform.getBoardSerial();
const fs = require('fs');
const Promise = require('bluebird');

const f = require('../../net2/Firewalla.js');

Promise.promisifyAll(fs);

const rp = require('request-promise');

class FWDiag {
  constructor() {
    if(instance === null) {
      instance = this;
    }

    return instance;
  }

  getEndpoint() {
    return fConfig.firewallaDiagServerURL || `https://api.firewalla.com/diag/api/v1/device/`
  }

  async getGatewayMac(gatewayIP) {
    const pingCmd = `ping -q -c 1 -w 2 ${gatewayIP} || /bin/true`;
    await exec(pingCmd);

    const arpCmd = `arp -a -n | grep ${gatewayIP} -w | awk '{print $4}'`;
    const result = await exec(arpCmd);
    const mac = result.stdout;
    if(mac) {
      return mac.substring(0, 11);
    } else {
      return null;
    }
  }

  async getGatewayName(gatewayIP) {
    const cmd = `arp ${gatewayIP} | tail -n 1 | awk '{print $1}'`;
    // return empty if command execute failed
    const result = await exec(cmd).catch(() => "");
    const name = result.stdout;
    return name.replace(/\n$/, '')
  }

  async getBranchInfo() {
    const result = await exec("git rev-parse --abbrev-ref HEAD");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  getVersion() {
    return fConfig.version;
  }

  async getLongVersion() {
    const result = await exec("git describe --tags");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  async getTotalMemory() {
    const result = await exec("free -m | awk '/Mem:/ {print $2}'");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  async getGID() {
    const result = await exec("redis-cli hget sys:ept gid");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  async hasLicenseFile() {
    const filePath = `${f.getHiddenFolder()}/license`;
    try {
      await fs.accessAsync(filePath, fs.constants.F_OK);
      return true;
    } catch (err) {
      return false;
    }
  }

  async prepareData(payload) {
    const inter = sysManager.getDefaultWanInterface()

    const ip = inter.ip_address;
    const gateway = inter.gateway_ip;
    const mac = platform.getSignatureMac();

    const gatewayMac = await this.getGatewayMac(gateway);
    const gatewayName = await this.getGatewayName(gateway);

    const ts = Math.floor(new Date() / 1000);

    return Object.assign({}, payload, {
      gw: gateway,
      fw: ip,
      mac: mac,
      ts: ts,
      gw_mac: gatewayMac,
      gw_name: gatewayName,
      model: model
    });
  }

  async submitInfo(payload) {
    const data = await this.prepareData(payload);
    if(data.gw) {
      const rclient = require('../../util/redis_manager.js').getRedisClient();

      const options = {
        uri:  this.getEndpoint() + data.gw,
        method: 'POST',
        json: data
      }
      const result = await rp(options);
      if(result && result.mode) {
        await rclient.setAsync("recommend_firewalla_mode", result.mode);
      }

      if(result && result.guessedRouter) {
        await rclient.setAsync("guessed_router", JSON.stringify(result.guessedRouter));
      }

      log.info(`submitted ${payload.event} info to diag server successfully with result ${JSON.stringify(result)}`);
    }
  }

  async getCpuTemperature() {
    try {
      return platform.getCpuTemperature()
    } catch(err) {
      return -1;
    }
  }

  async prepareHelloData() {
    const inter = sysManager.getDefaultWanInterface()

    const firewallaIP = inter.ip_address;
    const mac = platform.getSignatureMac();
    const gateway = inter.gateway_ip;

    const version = this.getVersion();

    const [gatewayMac, branch, longVersion, memory, gid, hasLicense, nicSpeed, cpuTemp] =
      await Promise.all([
        this.getGatewayMac(gateway),
        this.getBranchInfo(),
        this.getLongVersion(),
        this.getTotalMemory(),
        this.getGID(),
        this.hasLicenseFile(),
        platform.getNetworkSpeed(),
        this.getCpuTemperature()
      ]);

    return {
      mac,
      firewallaIP,
      gatewayMac,
      branch,
      version,
      longVersion,
      memory,
      model,
      serial,
      gid,
      hasLicense,
      nicSpeed,
      cpuTemp
    };
  }

  async sayHello() {
    const data = await this.prepareHelloData();
    const options = {
      uri: this.getEndpoint() + 'hello',
      method: 'POST',
      json: data
    }
    await rp(options);
    log.info("said hello to Firewalla Cloud");
  }

  async log(level, data) {
    const sysData = await this.prepareHelloData();
    const options = {
      uri: this.getEndpoint() + 'log/' + level,
      method: 'POST',
      json: Object.assign({}, data, sysData)
    }
    log.info(`Sending diag log, [${level}] ${JSON.stringify(data)}`);
    await rp(options);
  }
}

module.exports = new FWDiag();
<commit_msg>use rrWithErrHandling in diag.js<commit_after>/*    Copyright 2019 Firewalla INC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

'use strict'

let instance = null;

const exec = require('child-process-promise').exec;
const fConfig = require('../../net2/config.js').getConfig();
const log = require('../../net2/logger.js')(__filename);

const sysManager = require('../../net2/SysManager.js');

const platformLoader = require('../../platform/PlatformLoader.js');
const platform = platformLoader.getPlatform();
const model = platform.getName();
const serial = platform.getBoardSerial();
const fs = require('fs');
const Promise = require('bluebird');

const f = require('../../net2/Firewalla.js');

Promise.promisifyAll(fs);

const { rrWithErrHandling } = require('../../util/requestWrapper.js')

class FWDiag {
  constructor() {
    if(instance === null) {
      instance = this;
    }

    return instance;
  }

  getEndpoint() {
    return fConfig.firewallaDiagServerURL || `https://api.firewalla.com/diag/api/v1/device/`
  }

  async getGatewayMac(gatewayIP) {
    const pingCmd = `ping -q -c 1 -w 2 ${gatewayIP} || /bin/true`;
    await exec(pingCmd);

    const arpCmd = `arp -a -n | grep ${gatewayIP} -w | awk '{print $4}'`;
    const result = await exec(arpCmd);
    const mac = result.stdout;
    if(mac) {
      return mac.substring(0, 11);
    } else {
      return null;
    }
  }

  async getGatewayName(gatewayIP) {
    const cmd = `arp ${gatewayIP} | tail -n 1 | awk '{print $1}'`;
    // return empty if command execute failed
    const result = await exec(cmd).catch(() => "");
    const name = result.stdout;
    return name.replace(/\n$/, '')
  }

  async getBranchInfo() {
    const result = await exec("git rev-parse --abbrev-ref HEAD");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  getVersion() {
    return fConfig.version;
  }

  async getLongVersion() {
    const result = await exec("git describe --tags");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  async getTotalMemory() {
    const result = await exec("free -m | awk '/Mem:/ {print $2}'");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  async getGID() {
    const result = await exec("redis-cli hget sys:ept gid");
    return result && result.stdout && result.stdout.replace(/\n$/, '')
  }

  async hasLicenseFile() {
    const filePath = `${f.getHiddenFolder()}/license`;
    try {
      await fs.accessAsync(filePath, fs.constants.F_OK);
      return true;
    } catch (err) {
      return false;
    }
  }

  async prepareData(payload) {
    const inter = sysManager.getDefaultWanInterface()

    const ip = inter.ip_address;
    const gateway = inter.gateway_ip;
    const mac = platform.getSignatureMac();

    const gatewayMac = await this.getGatewayMac(gateway);
    const gatewayName = await this.getGatewayName(gateway);

    const ts = Math.floor(new Date() / 1000);

    return Object.assign({}, payload, {
      gw: gateway,
      fw: ip,
      mac: mac,
      ts: ts,
      gw_mac: gatewayMac,
      gw_name: gatewayName,
      model: model
    });
  }

  async submitInfo(payload) {
    const data = await this.prepareData(payload);
    if(data.gw) {
      const rclient = require('../../util/redis_manager.js').getRedisClient();

      const options = {
        uri:  this.getEndpoint() + data.gw,
        method: 'POST',
        json: data,
        maxAttempts: 2,
        timeout: 10000
      }
      const result = await rrWithErrHandling(options);
      if(result && result.mode) {
        await rclient.setAsync("recommend_firewalla_mode", result.mode);
      }

      if(result && result.guessedRouter) {
        await rclient.setAsync("guessed_router", JSON.stringify(result.guessedRouter));
      }

      log.info(`submitted ${payload.event} info to diag server successfully with result ${JSON.stringify(result)}`);
    }
  }

  async getCpuTemperature() {
    try {
      return platform.getCpuTemperature()
    } catch(err) {
      return -1;
    }
  }

  async prepareHelloData() {
    const inter = sysManager.getDefaultWanInterface()

    const firewallaIP = inter.ip_address;
    const mac = platform.getSignatureMac();
    const gateway = inter.gateway_ip;

    const version = this.getVersion();

    const [gatewayMac, branch, longVersion, memory, gid, hasLicense, nicSpeed, cpuTemp] =
      await Promise.all([
        this.getGatewayMac(gateway),
        this.getBranchInfo(),
        this.getLongVersion(),
        this.getTotalMemory(),
        this.getGID(),
        this.hasLicenseFile(),
        platform.getNetworkSpeed(),
        this.getCpuTemperature()
      ]);

    return {
      mac,
      firewallaIP,
      gatewayMac,
      branch,
      version,
      longVersion,
      memory,
      model,
      serial,
      gid,
      hasLicense,
      nicSpeed,
      cpuTemp
    };
  }

  async sayHello() {
    const data = await this.prepareHelloData();
    const options = {
      uri: this.getEndpoint() + 'hello',
      method: 'POST',
      json: data,
      maxAttempts: 2,
      timeout: 10000
    }
    await rrWithErrHandling(options);
    log.info("said hello to Firewalla Cloud");
  }

  async log(level, data) {
    const sysData = await this.prepareHelloData();
    const options = {
      uri: this.getEndpoint() + 'log/' + level,
      method: 'POST',
      json: Object.assign({}, data, sysData),
      maxAttempts: 2,
      timeout: 10000
    }
    log.info(`Sending diag log, [${level}] ${JSON.stringify(data)}`);
    await rrWithErrHandling(options);
  }
}

module.exports = new FWDiag();
<|endoftext|>


<commit_before>var pack = require('../../package.json');
var storage = require('../storage.js');

function mapToObject(data, id) {
    var harvest = data.harvest;
    var filename = harvest && harvest.images && ('/screenshots/' + id + '/' + harvest.images[harvest.images.length - 1].filename);
    return {
        id: id,
        filename: filename,
        hasImage: !! filename,
        success: data.report && data.report.error.length === 0 && data.report.warn.length === 0
    };
}

module.exports = {
    method: 'GET',
    path: '/',
    config: {
        handler: function (request) {
            var resultIds = storage.map(mapToObject);

            request.reply.view('index.html', {
                pack: pack,
                showForm: true,
                ids: resultIds,
                hasIds: resultIds && resultIds.length > 0
            });
        }
    }
};<commit_msg>Sort latest first<commit_after>var pack = require('../../package.json');
var storage = require('../storage.js');

function mapToObject(data, id) {
    var harvest = data.harvest;
    var filename = harvest && harvest.images && ('/screenshots/' + id + '/' + harvest.images[harvest.images.length - 1].filename);
    return {
        time: data.time,
        id: id,
        filename: filename,
        hasImage: !! filename,
        success: data.report && data.report.error.length === 0 && data.report.warn.length === 0
    };
}

module.exports = {
    method: 'GET',
    path: '/',
    config: {
        handler: function (request) {
            var resultIds = storage.map(mapToObject).sort(function(a, b){ return (a.time > b.time ? -1 : 1);});

            request.reply.view('index.html', {
                pack: pack,
                showForm: true,
                ids: resultIds,
                hasIds: resultIds && resultIds.length > 0
            });
        }
    }
};
<|endoftext|>


<commit_before>var input    = require('./digits.js');
var exercise = {};

exercise.one = function(){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 1st function not implemented 0824';
};

exercise.two = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 2nd function not implemented';
};

exercise.three = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 3rd function not implemented';
};

exercise.four = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 4th function not implemented';
};

exercise.five = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 5th function not implemented';
};

module.exports = exercise;
<commit_msg>Update exercise.js<commit_after>var input    = require('./digits.js');
var exercise = {};

exercise.one = function(){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 1st function not implemented 1829';
};

exercise.two = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 2nd function not implemented';
};

exercise.three = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 3rd function not implemented';
};

exercise.four = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 4th function not implemented';
};

exercise.five = function(data){
    //-------------------
    //---- Your Code ----
    //-------------------
    return 'Error: 5th function not implemented';
};

module.exports = exercise;
<|endoftext|>


<commit_before>'use strict';

var ddb = require('../../config/dynamo_database').ddb;
var _ = require('underscore');

var proposalModel = require('../model/proposalModel');

exports.findAll = function (req, res){
  return ddb.scan('proposals', {}, function (err, proposals) {
    if (!err) {
      return res.send(_.sortBy(proposals.items, function(element){
        return element.tema + element.subtema;
      }) );
    } else {
      return console.log(err);
    }
  });
};

exports.add = function (req, res){
  var proposal = proposalModel.newProposal(req);
  ddb.putItem('proposals', proposal, {}, function (err) {
    if (!err) {
      return console.log("Created Proposal");
    } else {
      return console.log(err);
    }
  });
  return res.send(202,proposal);
};

exports.findById = function (req, res){
  return ddb.getItem('proposals', req.params.id, null, {}, function (err, proposal) {
    if (!err) {
      return res.send(proposal);
    } else {
      return console.log(err);
    }
  });
};

exports.update = function (req, res){
  var proposal = proposalModel.updateProposal(req);

  return ddb.updateItem('proposals', req.params.id, null, proposal, function (err, proposals) {
      if (!err) {
        console.log("Updated Proposal");
      } else {
        console.log(err);
      }
      return res.send(202, proposals);
  });
};

exports.updateMedia = function (id, newMedia){
  return ddb.updateItem('proposals', id, null, {media:{value:newMedia}}, function (err, proposals) {
      if (err) {
        console.log(err);
      }
  });
};

exports.delete = function (req, res){
  ddb.deleteItem('proposals', req.params.id, null, {},  function (err, proposal) {
      if (!err) {
        console.log("Removed Proposal");
        return res.send('');
      } else {
        console.log(err);
      }
  });
};

exports.findRandom = function (req, res){
  return ddb.scan('proposals', {}, function (err, proposals) {
    if (!err) {
      var items = [];
      for(var i=0;i<req.params.qtd;i++){
        var index = parseInt(Math.random() * proposals.count);
        items.push(proposals.items[index]);
      }
      return res.send(items);
    } else {
      return console.log(err);
    }
  });
};<commit_msg>Loging the return to see whats is happeneing wrong<commit_after>'use strict';

var ddb = require('../../config/dynamo_database').ddb;
var _ = require('underscore');

var proposalModel = require('../model/proposalModel');

exports.findAll = function (req, res){
	return ddb.scan('proposals', {}, function (err, proposals) {
		if (!err) {
			return res.send(_.sortBy(proposals.items, function(element){
				return element.tema + element.subtema;
			}) );
		} else {
			return console.log(err);
		}
	});
};

exports.add = function (req, res){
	var proposal = proposalModel.newProposal(req);
	ddb.putItem('proposals', proposal, {}, function (err) {
		if (!err) {
			return console.log("Created Proposal");
		} else {
			return console.log(err);
		}
	});
	return res.send(202,proposal);
};

exports.findById = function (req, res){
	return ddb.getItem('proposals', req.params.id, null, {}, function (err, proposal) {
		if (!err) {
			return res.send(proposal);
		} else {
			return console.log(err);
		}
	});
};

exports.update = function (req, res){
	var proposal = proposalModel.updateProposal(req);

	return ddb.updateItem('proposals', req.params.id, null, proposal, function (err, proposals) {
		if (!err) {
			console.log("Updated Proposal");
		} else {
			console.log(err);
		}
		return res.send(202, proposals);
	});
};

exports.updateMedia = function (id, newMedia){
	return ddb.updateItem('proposals', id, null, {media:{value:newMedia}}, function (err, proposals) {
		if (err) {
			console.log(err);
		}
	});
};

exports.delete = function (req, res){
	ddb.deleteItem('proposals', req.params.id, null, {},  function (err, proposal) {
		if (!err) {
			console.log("Removed Proposal");
			return res.send('');
		} else {
			console.log(err);
		}
	});
};

exports.findRandom = function (req, res){
	return ddb.scan('proposals', {}, function (err, proposals) {
		if (!err) {
			var items = [];
			var politicians = [];
			var politicians_ids = [];

			proposals.items.forEach(function(element,index){
				if(politicians[element.politicians_id] == undefined){
					politicians[element.politicians_id] = [];
					politicians_ids.push(element.politicians_id);
				}
				politicians[element.politicians_id].push(index);
			});
			console.log(politicians);
			for(var i=0;i<req.params.qtd;i++){
				var randPolitician = parseInt(Math.random() * politicians_ids.length);
				var index = parseInt(Math.random() * politicians[randPolitician].length);
				items.push(proposals.items[politicians[randPolitician][index]]);
			}
			return res.send(items);
		} else {
			return console.log(err);
		}
	});
};<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.

var _ = require('lodash');
var express = require('express');
var router = express.Router();
var ws = require("ws");
var stringify = require("json-stringify-pretty-compact");
var data = require('./data');
var generator = require('./generator');
var filter = require('./filter');
var map = require('./map');

// remove following requires when request access is removed
var nodemailer = require('nodemailer');
var path = require('path');
var templatesDir = path.resolve(__dirname, 'templates');
var emailTemplates = require('email-templates');
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var fs = require("fs");

// Actions

function filteredItems (items, queryParams) {
  if (queryParams.userQuery) {
    items = filter.filterUserQuery(items, queryParams.userQuery);
  }
  if (queryParams.query) {
    items = filter.filterQuery(items, queryParams.query);
  }
  return items;
}

function getItems (url, queryParams) {
  var items = data.getItems(queryParams.category);
  var unfilteredTotal = items.length;
  items = filteredItems(items, queryParams);

  if (queryParams.sort) {
    filter.sort(items, queryParams.sort);
  }

  var startIndex = +queryParams.start; // coerce to be a number
  if (queryParams.referenceUri) {
    items.some(function(item, index) {
      if (queryParams.referenceUri === item.uri) {
        startIndex = Math.max(index - 3, 0);
        return true;
      }
    });
  }

  // prune for start+count
  var total = items.length;
  items = items.slice(startIndex, startIndex + queryParams.count);

  return {
    category: queryParams.category,
    start: startIndex,
    count: items.length,
    total: total,
    unfilteredTotal: unfilteredTotal,
    items: items
  };
}

function getAggregate (url, queryParams) {
  var items = data.getItems(queryParams.category) || [];
  items = filteredItems(items, queryParams);

  var attributes;
  if (Array.isArray(queryParams.attribute)) {
    attributes = queryParams.attribute;
  } else {
    attributes = [queryParams.attribute];
  }
  var result = attributes.map(function(attribute) {
    return {
      attribute: attribute,
      counts: []
    };
  });

  var intervals = null;
  if (queryParams.interval) {
    intervals = [];
    var stop =  new Date();
    stop.setHours(23, 59, 59, 999);
    for (var i = 0; i < queryParams.count; i++) {
      var start = new Date(stop.getTime() + 1);
      start.setDate(start.getDate() - 1);
      intervals.push({start: start.toISOString(), stop: stop.toISOString()});
      stop = new Date(start.getTime() - 1);
    }
  }

  items.some(function(resource) {
    result.forEach(function(attributeResult) {

      var value;
      if (resource.hasOwnProperty(attributeResult.attribute)) {
        value = resource[attributeResult.attribute];
      } else if (resource.attributes &&
        resource.attributes.hasOwnProperty(attributeResult.attribute)) {
        value = resource.attributes[attributeResult.attribute];
      }

      if (undefined !== value) {
        var counts = attributeResult.counts;
        var count = null;
        for (var i = 0; i < counts.length; i++) {
          if (value === counts[i].value) {
            count = counts[i];
            break;
          }
        }

        if (!count) {
          count = {value: value, count: 0};
          if (intervals) {
            count.intervals = _.map(intervals, _.clone);
          }
          counts.push(count);
        }
        count.count += 1;

        if (count.intervals) {
          count.intervals.forEach(function(interval) {
            if (! interval.count) {
              interval.count = 0;
            }
            if (resource.created >= interval.start &&
              resource.created <= interval.stop) {
              interval.count += 1;
            }
          });
        }
      }
    });
  });

  return result;
}

// WebSocket interaction

var socketServer;
var connections = [];

function closeConnection (connection) {
  if (connection.ws) {
    connection.ws.close();
    connection.ws = null;
    var index = connections.indexOf(connection);
    connections.splice(index, 1);
  }
}

var MAP_REGEXP = /^\/rest\/index\/trees\/aggregated(.+)$/;

function respondToRequest (connection, request) {
  var response = {op: 'update', id: request.id};

  if ('/rest/index/resources' === request.url) {
    response.result = getItems(request.url, request.params);
  } else if ('/rest/index/resources/aggregated' === request.url) {
    response.result = getAggregate(request.url, request.params);
  } else if (MAP_REGEXP.test(request.url)) {
    var uri = MAP_REGEXP.exec(request.url)[1];
    response.result = map.build(uri);
  } else {
    var resource = data.getResource(request.url);
    if (resource) {
      response.result = resource;
    } else {
      response.op = 'error';
      response.result = 'unknown url ' + request.url;
    }
  }

  if (connection.ws) {
    var serializedResponse = JSON.stringify(response);
    console.log(response.op.toUpperCase(), request.url,
      stringify(request.params), serializedResponse.length);
    connection.ws.send(serializedResponse);
  }

  if ('error' === response.op) {
    closeConnection(connection);
  }
}

function onMessage (connection, request) {
  if ('start' === request.op) {
    console.log('WATCH', request.url, stringify(request.params));
    connection.requests.push(request);
    respondToRequest(connection, request);
  } else if ('stop' === request.op) {
    // Remove request
    connection.requests = connection.requests.filter(function (req) {
      return (req.id !== request.id);
    });
  } else {
    if (connection.ws) {
      connection.ws.send({error: 'unknown op ' + request.op});
      closeConnection(connection);
    }
  }
}

function onConnection (ws) {
  var connection = {
    ws: ws,
    requests: []
  };
  connections.push(connection);

  ws.on('message', function incoming(message) {
    onMessage(connection, JSON.parse(message));
  });

  ws.on("close", function () {
    closeConnection(connection);
  });
}

function initializeSocket (server) {
  socketServer = new ws.Server({server: server, path: "/rest/ws"});
  socketServer.on("connection", onConnection);
}

function requestMatches (request, events) {
  // If the request category(ies) or the request url match the change, respond
  var category;
  var uri;
  if (request.params && request.params.category) {
    category = request.params.category;
  } else {
    uri = request.url;
  }
  return events.some(function (event) {
    if (category) {
      return (category === event.category ||
        (Array.isArray(category) &&
        category.indexOf(event.category) !== -1));
    } else {
      return (uri === event.uri);
    }
  });
}

function onResourceChange (events) {
  connections.forEach(function (connection) {
    connection.requests.forEach(function (request) {
      if (requestMatches(request, events)) {
        respondToRequest(connection, request);
      }
    });
  });
}

// REST interaction

router.post('/login-sessions', function(req, res) {
  if ('error' === req.body.userName) {
    res.status(400).send({
      message: "Invalid username or password or directory.",
      resolution: "Enter correct credentials and try again." +
        " To obtain a username or password, contact your security administrator."
    });
  } else {
    res.json({
      sessionID: 'abc123'
    });
  }
});

router.delete('/login-sessions', function(req, res) {
  res.json(null);
});

router.get('/preferences/index', function(req, res) {
  var preferences = data.getPreferences(req.headers.auth, req.query.category);
  if (! preferences) {
    res.status(404).send();
  } else {
    res.json(preferences);
  }
});

// Email for Request Access TODO: move to a separate module?
function handleEmailResponse(error, info) {
  if (error) {
    console.log(error);
  } else {
    console.log('Message sent: ' + info.response);
  }
}

router.post('/request-access', function(req, res) {

  var data = req.body;

  if (!data.name || !data.email || !data.businessPurpose || !data.github) {
    res.status(400).send({
      message: "Invalid payload.",
      recommendedActions: "Enter name, email, and businessPurpose and try again."
    });
  }

  var requestsFilePath = path.resolve(__dirname, 'requests.csv');

  fs.exists(requestsFilePath, function(exists) {

    var contentCsv = [data.name, data.email, data.businessPurpose, data.github]
      .join() + '\n';

    if (exists) {
      fs.appendFile(requestsFilePath, contentCsv, function(err) {
        if (err) {
          console.log('Error while creating the requests.csv: ' + err);
        } else {
          console.log(requestsFilePath + ' has been successfully created!');
        }
      });
    } else {
      fs.writeFile(requestsFilePath, contentCsv, function(err) {
        if (err) {
          console.log('Error while updating the requests.csv: ' + err);
        } else {
          console.log(requestsFilePath + ' has been successfully updated!');
        }
      });

    }

  });

  var transport = nodemailer.createTransport(smtpTransport({
    host: 'localhost',
    port: 25
  }));

  var toGrommetConfig = {
    from: data.email,
    to: 'uxgroup@hp.com',
    subject: 'Evaluate access for ' + data.email,
    text: data.name + ' with this email: ' + data.email +
      ' wants to access Grommet for this reason: ' + data.businessPurpose +
      '. The Github account is: ' + data.github + '.'
  };

  emailTemplates(templatesDir, function(err, template) {
    if (err) {
      console.log(err);
    } else {
      template('welcome', data, function(err, html, text) {
        if (err) {
          console.log(err);
        } else {
          var toRequesterConfig = {
            from: 'grommet@hp.com',
            to: data.email,
            subject: 'Welcome to Grommet!',
            text: text,
            html: html
          };

          transport.sendMail(toRequesterConfig, handleEmailResponse);
        }
      });
    }
  });

  transport.sendMail(toGrommetConfig, handleEmailResponse);

  res.sendStatus(200);
});

router.get('/index/resources', function(req, res) {
  var result = getItems('/rest' + req.url, req.query);
  res.json(result);
});

router.get('/index/resources/aggregated', function(req, res) {
  var result = getAggregate('/rest' + req.url, req.query);
  res.json(result);
});

router.get(/^\/index\/search-suggestions/, function(req, res) {
  var items = data.getItems(req.query.category || null);

  if (req.query.userQuery) {
    items = filter.filterUserQuery(items, req.query.userQuery);
  }

  if (req.query.query) {
    items = filter.filterQuery(items, req.query.query);
  }

  var startIndex = +req.query.start; // coerce to be a number
  // prune for start+count
  items = items.slice(startIndex, startIndex + req.query.count);

  res.json(items.map(function(item) {
    return {
      name: item.name,
      category: item.category,
      uri: item.uri
    };
  }));
});

router.get(/^\/index\/trees\/aggregated(.+)$/, function(req, res) {
  var uri = req.params[0];
  res.json(map.build(uri));
});

router.get(/^\/index\/trees(.+)$/, function(req, res) {
  //var uri = req.params[0];
  res.status(501).send();
});

router.get('/:categoryName/*', function(req, res) {
  var resource = data.getResource('/rest' + req.url);
  if (resource) {
    res.json(resource);
  } else {
    res.status(404).send();
  }
});

function createTask (categoryName, action, resource) {
  var now = new Date();

  var task = {
    category: 'tasks',
    uri: '/rest/tasks/' + now.getTime(),
    name: action,
    status: 'Unknown',
    state: 'Running',
    attributes: {
      associatedResourceUri: resource.uri,
      associatedResourceName: resource.name,
      associatedResourceCategory: categoryName,
      hidden: false
    },
    created: now.toISOString(),
    modified: now.toISOString()
  };
  data.addResource('tasks', task);

  return task;
}

router.post('/:categoryName', function(req, res) {
  var categoryName = req.params.categoryName;
  var now = new Date();

  var resource = _.extend({
    category: categoryName,
    uri: '/rest/' + categoryName + '/' + now.getTime(),
    status: 'Unknown',
    state: 'Normal',
    created: now.toISOString(),
    modified: now.toISOString()
  }, req.body);
  data.addResource(categoryName, resource);

  var task = createTask(categoryName, 'Add', resource);

  res.json({
    taskUri: task.uri
  });

  setTimeout(function() {
    resource.status = 'OK';
    task.status = 'OK';
    task.state = 'Completed';
    task.modified = (new Date()).toISOString();
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 10000);

  setTimeout(function () {
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 1);
});

router.put('/:categoryName/*', function(req, res) {
  var categoryName = req.params.categoryName;
  var resource = req.body;
  var now = new Date();
  resource.modified = now.toISOString();
  data.updateResource(categoryName, resource);

  var task = createTask(categoryName, 'Update', resource);

  res.json({
    taskUri: task.uri
  });

  setTimeout(function() {
    task.status = 'OK';
    task.state = 'Completed';
    task.modified = (new Date()).toISOString();
    onResourceChange([{category: task.category, uri: task.uri}]);
  }, 10000);

  setTimeout(function () {
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 1);
});

router.delete('/:categoryName/*', function(req, res) {
  var categoryName = req.params.categoryName;
  var resource = data.getResource('/rest' + req.url);

  var task = createTask(categoryName, 'Delete', resource);

  res.json({
    taskUri: task.uri
  });

  setTimeout(function() {
    data.deleteResource(categoryName, '/rest' + req.url);
    task.status = 'OK';
    task.state = 'Completed';
    task.modified = (new Date()).toISOString();
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 10000);

  setTimeout(function () {
    onResourceChange([{category: task.category, uri: task.uri}]);
  }, 1);
});

module.exports = {
  router: router,
  setup: function (server) {
    generator.generate();
    initializeSocket(server);
    generator.listen(onResourceChange);
  }
};
<commit_msg>Remove unused request access email handling from server.<commit_after>// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.

var _ = require('lodash');
var express = require('express');
var router = express.Router();
var ws = require("ws");
var stringify = require("json-stringify-pretty-compact");
var data = require('./data');
var generator = require('./generator');
var filter = require('./filter');
var map = require('./map');

// Actions

function filteredItems (items, queryParams) {
  if (queryParams.userQuery) {
    items = filter.filterUserQuery(items, queryParams.userQuery);
  }
  if (queryParams.query) {
    items = filter.filterQuery(items, queryParams.query);
  }
  return items;
}

function getItems (url, queryParams) {
  var items = data.getItems(queryParams.category);
  var unfilteredTotal = items.length;
  items = filteredItems(items, queryParams);

  if (queryParams.sort) {
    filter.sort(items, queryParams.sort);
  }

  var startIndex = +queryParams.start; // coerce to be a number
  if (queryParams.referenceUri) {
    items.some(function(item, index) {
      if (queryParams.referenceUri === item.uri) {
        startIndex = Math.max(index - 3, 0);
        return true;
      }
    });
  }

  // prune for start+count
  var total = items.length;
  items = items.slice(startIndex, startIndex + queryParams.count);

  return {
    category: queryParams.category,
    start: startIndex,
    count: items.length,
    total: total,
    unfilteredTotal: unfilteredTotal,
    items: items
  };
}

function updateAggregateCounts (counts, resource, value, intervals) {
  var count = null;
  for (var i = 0; i < counts.length; i++) {
    if (value === counts[i].value) {
      count = counts[i];
      break;
    }
  }

  if (!count) {
    count = {value: value, count: 0};
    if (intervals) {
      count.intervals = _.map(intervals, _.clone);
    }
    counts.push(count);
  }
  count.count += 1;

  if (count.intervals) {
    count.intervals.forEach(function(interval) {
      if (! interval.count) {
        interval.count = 0;
      }
      if (resource.created >= interval.start &&
        resource.created <= interval.stop) {
        interval.count += 1;
      }
    });
  }
}

function getAggregate (url, queryParams) {
  var items = data.getItems(queryParams.category) || [];
  items = filteredItems(items, queryParams);

  var attributes;
  if (Array.isArray(queryParams.attribute)) {
    attributes = queryParams.attribute;
  } else {
    attributes = [queryParams.attribute];
  }
  var result = attributes.map(function(attribute) {
    return {
      attribute: attribute,
      counts: []
    };
  });

  var intervals = null;
  if (queryParams.interval) {
    intervals = [];
    var stop =  new Date();
    stop.setHours(23, 59, 59, 999);
    for (var i = 0; i < queryParams.count; i++) {
      var start = new Date(stop.getTime() + 1);
      start.setDate(start.getDate() - 1);
      intervals.push({start: start.toISOString(), stop: stop.toISOString()});
      stop = new Date(start.getTime() - 1);
    }
  }

  items.some(function(resource) {
    result.forEach(function(attributeResult) {

      var value;
      if (resource.hasOwnProperty(attributeResult.attribute)) {
        value = resource[attributeResult.attribute];
      } else if (resource.attributes &&
        resource.attributes.hasOwnProperty(attributeResult.attribute)) {
        value = resource.attributes[attributeResult.attribute];
      }

      if (undefined !== value) {
        updateAggregateCounts(attributeResult.counts,
          resource, value, intervals);
      }
    });
  });

  return result;
}

// WebSocket interaction

var socketServer;
var connections = [];

function closeConnection (connection) {
  if (connection.ws) {
    connection.ws.close();
    connection.ws = null;
    var index = connections.indexOf(connection);
    connections.splice(index, 1);
  }
}

var MAP_REGEXP = /^\/rest\/index\/trees\/aggregated(.+)$/;

function respondToRequest (connection, request) {
  var response = {op: 'update', id: request.id};

  if ('/rest/index/resources' === request.url) {
    response.result = getItems(request.url, request.params);
  } else if ('/rest/index/resources/aggregated' === request.url) {
    response.result = getAggregate(request.url, request.params);
  } else if (MAP_REGEXP.test(request.url)) {
    var uri = MAP_REGEXP.exec(request.url)[1];
    response.result = map.build(uri);
  } else {
    var resource = data.getResource(request.url);
    if (resource) {
      response.result = resource;
    } else {
      response.op = 'error';
      response.result = 'unknown url ' + request.url;
    }
  }

  if (connection.ws) {
    var serializedResponse = JSON.stringify(response);
    console.log(response.op.toUpperCase(), request.url,
      stringify(request.params), serializedResponse.length);
    connection.ws.send(serializedResponse);
  }

  if ('error' === response.op) {
    closeConnection(connection);
  }
}

function onMessage (connection, request) {
  if ('start' === request.op) {
    console.log('WATCH', request.url, stringify(request.params));
    connection.requests.push(request);
    respondToRequest(connection, request);
  } else if ('stop' === request.op) {
    // Remove request
    connection.requests = connection.requests.filter(function (req) {
      return (req.id !== request.id);
    });
  } else {
    if (connection.ws) {
      connection.ws.send({error: 'unknown op ' + request.op});
      closeConnection(connection);
    }
  }
}

function onConnection (ws) {
  var connection = {
    ws: ws,
    requests: []
  };
  connections.push(connection);

  ws.on('message', function incoming(message) {
    onMessage(connection, JSON.parse(message));
  });

  ws.on("close", function () {
    closeConnection(connection);
  });
}

function initializeSocket (server) {
  socketServer = new ws.Server({server: server, path: "/rest/ws"});
  socketServer.on("connection", onConnection);
}

function requestMatches (request, events) {
  // If the request category(ies) or the request url match the change, respond
  var category;
  var uri;
  if (request.params && request.params.category) {
    category = request.params.category;
  } else {
    uri = request.url;
  }
  return events.some(function (event) {
    if (category) {
      return (category === event.category ||
        (Array.isArray(category) &&
        category.indexOf(event.category) !== -1));
    } else {
      return (uri === event.uri);
    }
  });
}

function onResourceChange (events) {
  connections.forEach(function (connection) {
    connection.requests.forEach(function (request) {
      if (requestMatches(request, events)) {
        respondToRequest(connection, request);
      }
    });
  });
}

// REST interaction

router.post('/login-sessions', function(req, res) {
  if ('error' === req.body.userName) {
    res.status(400).send({
      message: "Invalid username or password or directory.",
      resolution: "Enter correct credentials and try again." +
        " To obtain a username or password, contact your security administrator."
    });
  } else {
    res.json({
      sessionID: 'abc123'
    });
  }
});

router.delete('/login-sessions', function(req, res) {
  res.json(null);
});

router.get('/preferences/index', function(req, res) {
  var preferences = data.getPreferences(req.headers.auth, req.query.category);
  if (! preferences) {
    res.status(404).send();
  } else {
    res.json(preferences);
  }
});

router.get('/index/resources', function(req, res) {
  var result = getItems('/rest' + req.url, req.query);
  res.json(result);
});

router.get('/index/resources/aggregated', function(req, res) {
  var result = getAggregate('/rest' + req.url, req.query);
  res.json(result);
});

router.get(/^\/index\/search-suggestions/, function(req, res) {
  var items = data.getItems(req.query.category || null);

  if (req.query.userQuery) {
    items = filter.filterUserQuery(items, req.query.userQuery);
  }

  if (req.query.query) {
    items = filter.filterQuery(items, req.query.query);
  }

  var startIndex = +req.query.start; // coerce to be a number
  // prune for start+count
  items = items.slice(startIndex, startIndex + req.query.count);

  res.json(items.map(function(item) {
    return {
      name: item.name,
      category: item.category,
      uri: item.uri
    };
  }));
});

router.get(/^\/index\/trees\/aggregated(.+)$/, function(req, res) {
  var uri = req.params[0];
  res.json(map.build(uri));
});

router.get(/^\/index\/trees(.+)$/, function(req, res) {
  //var uri = req.params[0];
  res.status(501).send();
});

router.get('/:categoryName/*', function(req, res) {
  var resource = data.getResource('/rest' + req.url);
  if (resource) {
    res.json(resource);
  } else {
    res.status(404).send();
  }
});

function createTask (categoryName, action, resource) {
  var now = new Date();

  var task = {
    category: 'tasks',
    uri: '/rest/tasks/' + now.getTime(),
    name: action,
    status: 'Unknown',
    state: 'Running',
    attributes: {
      associatedResourceUri: resource.uri,
      associatedResourceName: resource.name,
      associatedResourceCategory: categoryName,
      hidden: false
    },
    created: now.toISOString(),
    modified: now.toISOString()
  };
  data.addResource('tasks', task);

  return task;
}

router.post('/:categoryName', function(req, res) {
  var categoryName = req.params.categoryName;
  var now = new Date();

  var resource = _.extend({
    category: categoryName,
    uri: '/rest/' + categoryName + '/' + now.getTime(),
    status: 'Unknown',
    state: 'Normal',
    created: now.toISOString(),
    modified: now.toISOString()
  }, req.body);
  data.addResource(categoryName, resource);

  var task = createTask(categoryName, 'Add', resource);

  res.json({
    taskUri: task.uri
  });

  setTimeout(function() {
    resource.status = 'OK';
    task.status = 'OK';
    task.state = 'Completed';
    task.modified = (new Date()).toISOString();
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 10000);

  setTimeout(function () {
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 1);
});

router.put('/:categoryName/*', function(req, res) {
  var categoryName = req.params.categoryName;
  var resource = req.body;
  var now = new Date();
  resource.modified = now.toISOString();
  data.updateResource(categoryName, resource);

  var task = createTask(categoryName, 'Update', resource);

  res.json({
    taskUri: task.uri
  });

  setTimeout(function() {
    task.status = 'OK';
    task.state = 'Completed';
    task.modified = (new Date()).toISOString();
    onResourceChange([{category: task.category, uri: task.uri}]);
  }, 10000);

  setTimeout(function () {
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 1);
});

router.delete('/:categoryName/*', function(req, res) {
  var categoryName = req.params.categoryName;
  var resource = data.getResource('/rest' + req.url);

  var task = createTask(categoryName, 'Delete', resource);

  res.json({
    taskUri: task.uri
  });

  setTimeout(function() {
    data.deleteResource(categoryName, '/rest' + req.url);
    task.status = 'OK';
    task.state = 'Completed';
    task.modified = (new Date()).toISOString();
    onResourceChange([
      {category: resource.category, uri: resource.uri},
      {category: task.category, uri: task.uri}
    ]);
  }, 10000);

  setTimeout(function () {
    onResourceChange([{category: task.category, uri: task.uri}]);
  }, 1);
});

module.exports = {
  router: router,
  setup: function (server) {
    generator.generate();
    initializeSocket(server);
    generator.listen(onResourceChange);
  }
};
<|endoftext|>


<commit_before>import isExtensible from 'core-js-pure/features/object/is-extensible';

QUnit.test('Object.isExtensible', assert => {
  assert.isFunction(isExtensible);
  assert.arity(isExtensible, 1);
  const primitives = [42, 'string', false, null, undefined];
  for (const value of primitives) {
    assert.notThrows(() => isExtensible(value) || true, `accept ${ value }`);
    assert.same(isExtensible(value), false, `returns true on ${ value }`);
  }
  assert.same(isExtensible({}), true);
});
<commit_msg>Update es.object.is-extensible.js<commit_after>import isExtensible from 'core-js-pure/features/object/is-extensible';

QUnit.test('Object.isExtensible', assert => {
  assert.isFunction(isExtensible);
  assert.arity(isExtensible, 1);
  const primitives = [42, 'string', false, null, undefined];
  for (const value of primitives) {
    assert.notThrows(() => isExtensible(value) || true, `accept ${ value }`);
    assert.same(isExtensible(value), false, `returns false on ${ value }`);
  }
  assert.same(isExtensible({}), true);
});
<|endoftext|>


<commit_before>const Emeus = imports.gi.Emeus;
const GObject = imports.gi.GObject;
const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

Emeus.ConstraintLayout.prototype.pack = function(child, constraints) {
    Gtk.Container.prototype.add.call(this, child);

    let childConstraints = constraints || [];
    for (let constraint of constraints) {
        Emeus.ConstraintLayout.prototype.child_add_constraint.call(this, child, constraint);
    }
}

const MyApplicationWindow = Lang.Class({
    Name: 'MyApplicationWindow',
    Extends: Gtk.ApplicationWindow,

    _init: function() {
        this.set_default_size(400, 500);

        let box = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL, spacing: 6 });
        this.add(box);
        box.show();

        let layout = new Emeus.ConstraintLayout();
        layout.hexpand = true;
        layout.vexpand = true;
        box.add(layout);
        layout.show();

        this._layout = layout;

        let button = new Gtk.Button({ label: 'Quit' });
        button.hexpand = true;
        box.add(button);
        button.show();

        button.signal_connect('clicked', Lang.bind(this, function() { this.destroy(); }));

        this._buildGrid();
    },

    _buildGrid: function() {
        /* Grid:
         *
         * +--------------------------+
         * | +---------+  +---------+ |
         * | | Child 1 |  | Child 2 | |
         * | +---------+  +---------+ |
         * |                          |
         * | +----------------------+ |
         * | |        Child 3       | |
         * | +----------------------+ |
         * +--------------------------+
         */
        let button1 = new Gtk.Button({ label: 'Child 1' });
        this._layout.pack(button1 [
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.WIDTH,
                                   relation: Emeus.ConstraintRelation.GEQ,
                                   constant: 120, }),
        ]);
        button1.show();

        let button2 = new Gtk.Button({ label: 'Child 2' });
        this._layout.pack(button2, [
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.WIDTH,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.WIDTH, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.HEIGHT,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.HEIGHT, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.START,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.END,
                                   constant: 12, }),
        ]);
        button2.show();

        let button3 = new Gtk.Button({ label: 'Child 3' });
        this._layout.pack(button3, [
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.START,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.START, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.END,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button2,
                                   source_attribute: Emeus.ConstraintAttribute.END, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.TOP,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.BOTTOM,
                                   constant: 12, })
        ]);
    },
});

const MyApplication = Lang.Class({
    Name: 'MyApplication',
    Extends: Gtk.Application,

    _init: function() {
        this.parent({ application_id: 'io.bassi.SimpleGrid' });

        this._mainWindow = null;
    },

    vfunc_activate: function() {
        if (!this._mainWindow) {
            this._mainWindow = new MyApplicationWindow({ application: this });
            this._mainWindow.show();
        }

        this._mainWindow.present();
    },
});

let app = new MyApplication();
app.run();
<commit_msg>examples: Fix JS example<commit_after>const Emeus = imports.gi.Emeus;
const GObject = imports.gi.GObject;
const Gio = imports.gi.Gio;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;

Emeus.ConstraintLayout.prototype.pack = function(child, constraints=[]) {
    let layout_child = new Emeus.ConstraintLayoutChild();
    layout_child.add(child);
    Gtk.Container.prototype.add.call(this, layout_child);

    for (let constraint of constraints) {
        layout_child.add_constraint(constraint);
    }
}

const MyApplicationWindow = Lang.Class({
    Name: 'MyApplicationWindow',
    Extends: Gtk.ApplicationWindow,

    _init: function(props={}) {
        this.parent(props);
        this.set_default_size(400, 500);

        let box = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL, spacing: 6 });
        this.add(box);
        box.show();

        let layout = new Emeus.ConstraintLayout();
        layout.hexpand = true;
        layout.vexpand = true;
        box.add(layout);
        layout.show();

        this._layout = layout;

        let button = new Gtk.Button({ label: 'Quit' });
        button.hexpand = true;
        box.add(button);
        button.show();

        button.connect('clicked', Lang.bind(this, function() { this.destroy(); }));

        this._buildGrid();
    },

    _buildGrid: function() {
        /* Grid:
         *
         * +--------------------------+
         * | +---------+  +---------+ |
         * | | Child 1 |  | Child 2 | |
         * | +---------+  +---------+ |
         * |                          |
         * | +----------------------+ |
         * | |        Child 3       | |
         * | +----------------------+ |
         * +--------------------------+
         */
        let button1 = new Gtk.Button({ label: 'Child 1' });
        this._layout.pack(button1, [
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.WIDTH,
                                   relation: Emeus.ConstraintRelation.GE,
                                   constant: 120, }),
        ]);
        button1.show();

        let button2 = new Gtk.Button({ label: 'Child 2' });
        this._layout.pack(button2, [
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.WIDTH,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.WIDTH, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.HEIGHT,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.HEIGHT, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.START,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.END,
                                   constant: 12, }),
        ]);
        button2.show();

        let button3 = new Gtk.Button({ label: 'Child 3' });
        this._layout.pack(button3, [
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.START,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.START, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.END,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button2,
                                   source_attribute: Emeus.ConstraintAttribute.END, }),
            new Emeus.Constraint({ target_attribute: Emeus.ConstraintAttribute.TOP,
                                   relation: Emeus.ConstraintRelation.EQ,
                                   source_object: button1,
                                   source_attribute: Emeus.ConstraintAttribute.BOTTOM,
                                   constant: 12, })
        ]);
    },
});

const MyApplication = Lang.Class({
    Name: 'MyApplication',
    Extends: Gtk.Application,

    _init: function() {
        this.parent({ application_id: 'io.bassi.SimpleGrid' });

        this._mainWindow = null;
    },

    vfunc_activate: function() {
        if (!this._mainWindow) {
            this._mainWindow = new MyApplicationWindow({ application: this });
            this._mainWindow.show();
        }

        this._mainWindow.present();
    },
});

let app = new MyApplication();
app.run(['simple-grid'].concat(ARGV));
<|endoftext|>


<commit_before>module.exports = {
	'frontend-starter': 'git@github.com:sq1agency/frontend-starter.git',
	'react-starter': 'git@github.com:sq1agency/react-starter.git'
};
<commit_msg>Added react-express-starter to kits.js.<commit_after>module.exports = {
	'frontend-starter': 'git@github.com:sq1agency/frontend-starter.git',
	'react-starter': 'git@github.com:sq1agency/react-starter.git',
	'react-express-starter': 'git@github.com:sq1agency/react-express-starter.git'
};
<|endoftext|>


<commit_before>import flockn from 'flockn';

flockn(function () {

  // Set the width & height of the game
  this.width = 300;
  this.height = 300;

  // Add a new scene
  this.addScene(function () {

    // Add a new object onto the scene
    this.addGameObject(function () {
      var _this = this;
      // Set its name
      this.name = 'myGameObject';

      // Load an image for the texture
      this.texture.image.filename = 'hero_front.png';

      this.input.key.on('down', function (keyCode) {
        if (keyCode === this.up || keyCode === this.w) {
          _this.position.y -= 10;
        }

        if (keyCode === this.down || keyCode === this.s) {
          _this.position.y += 10;
        }

        if (keyCode === this.left || keyCode === this.a) {
          _this.position.x -= 10;
        }

        if (keyCode === this.right || keyCode === this.d) {
          _this.position.x += 10;
        }
      });

      this.on('click', function () {
        alert('You clicked that hero guy.');
      });

      this.on('update', function (dt) {
        return _this.angle += (dt * 10);
      });
    });

    this.addGameObject(function () {
      this.texture.backgroundColor.set(255, 0, 0);

      this.position.x = 100;
      this.position.y = 100;

      this.width = 80;
      this.height = 80;
    });

    this.addGameObject(function () {
      this.texture.label.text = 'Hello World';

      this.top = 8;
      this.right = 8;
    });
  });

  this.run();

});
<commit_msg>Set canvas renderer<commit_after>import flockn from 'flockn';
flockn.setRenderer('canvas');

flockn(function () {

  // Set the width & height of the game
  this.width = 300;
  this.height = 300;

  // Add a new scene
  this.addScene(function () {

    // Add a new object onto the scene
    this.addGameObject(function () {
      var _this = this;
      // Set its name
      this.name = 'myGameObject';

      // Load an image for the texture
      this.texture.image.filename = 'hero_front.png';

      this.input.key.on('down', function (keyCode) {
        if (keyCode === this.up || keyCode === this.w) {
          _this.position.y -= 10;
        }

        if (keyCode === this.down || keyCode === this.s) {
          _this.position.y += 10;
        }

        if (keyCode === this.left || keyCode === this.a) {
          _this.position.x -= 10;
        }

        if (keyCode === this.right || keyCode === this.d) {
          _this.position.x += 10;
        }
      });

      this.on('click', function () {
        alert('You clicked that hero guy.');
      });

      this.on('update', function (dt) {
        return _this.angle += (dt * 10);
      });
    });

    this.addGameObject(function () {
      this.texture.backgroundColor.set(255, 0, 0);

      this.position.x = 100;
      this.position.y = 100;

      this.width = 80;
      this.height = 80;
    });

    this.addGameObject(function () {
      this.texture.label.text = 'Hello World';

      this.top = 8;
      this.right = 8;
    });
  });

  this.run();

});
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')

if (!fs.existsSync(path.join(__dirname, 'config.json'))) {
	console.log('config.json file not found, please run kuro-cli or create it on your own')
	process.exit()
}

const config = require('./config.json')
const Discord = require('discord.js')
const knex = require('knex')(config.database)
const chalk = require('chalk')

let TelegramBot
let telegram

if (config.hasOwnProperty('telegramNotifications')) {
	if (config.telegramNotifications.active) {
		TelegramBot = require('node-telegram-bot-api')
		telegram = new TelegramBot(config.telegramNotifications.botToken, { polling: false })
	}
}

let filesDirectory = path.join(__dirname, 'files')
fs.existsSync(filesDirectory) || fs.mkdirSync(filesDirectory)

// Initializing the ultimate tan
const kuro = new Discord.Client()

// When ready
kuro.once('ready', () => {

	// Create database if it doesn't exist
	fs.exists('db', (exists) => exists || fs.writeFile('db', ''))

	// Getting the database ready
	kuro.db = knex

	// Making config available on every module
	kuro.config = config

	kuro.loadCommands()

	kuro.log('Kuro is ready!', 'green')
})

kuro.on('message', (msg) => {

	// If Telegram notifications are active, make extra checks
	if (config.hasOwnProperty('telegramNotifications')) {
		if (config.telegramNotifications.active) {
			// Check if someone is sending us a DM
			if (msg.channel.type === 'dm') {
				if (msg.author.id !== kuro.user.id) {
					return kuro.sendTelegramNotification('DM', msg.author.username, msg.content)
				}
			}

			// Check if it's someone mentioning us
			if (msg.isMentioned(kuro.user)) {
				return kuro.sendTelegramNotification('Ping', msg.author.username, msg.content)
			}
		}
	}

	// Ignore if the message is not ours
	if (msg.author.id !== kuro.user.id) return

	// Ignore if the message doesn't start with our prefix
	if (!msg.content.startsWith(config.prefix)) return

	// Ignore if empty command
	if (msg.content.length === config.prefix.length) return

	// Get all the arguments
	let tmp = msg.content.substring(config.prefix.length, msg.length).split(' ')
	let args = []

	for (let i = 1; i < tmp.length; i++) {
		args.push(tmp[i])
	}

	// Store the command separately
	let cmd = tmp[0]

	if (kuro.modules.hasOwnProperty(cmd)) return kuro.modules[cmd].run(msg, args)
	if (config.commandError.sendToModule === true) {
		return kuro.modules[config.commandError.module][config.commandError.function](msg, cmd)
	}

	return msg.delete()
})

kuro.on('disconnect', () => {
	kuro.error('CLIENT: Disconnected!')
	process.exit()
})
kuro.on('reconnecting', () => { kuro.log('CLIENT: Reconnecting...', 'green') })

kuro.loadCommands = function() {
	kuro.modules = {}

	// Load up all the modules
	fs.readdirSync('./commands/').forEach((file) => {
		let name = file.slice(0, -3)

		delete require.cache[require.resolve(`./commands/${file}`)]

		try {
			kuro.modules[name] = require(`./commands/${file}`)
			if (kuro.modules[name].hasOwnProperty('init')) {
				kuro.modules[name].init(kuro)
			}

			kuro.log(`Module ${name} is ready`)
		} catch (e) {
			kuro.error(`Error in module ${name}:\n${e.stack}`)
		}
	})
}

kuro.edit = function(msg, content, timeout = 3000) {
	if (timeout === 0) return msg.edit(content).catch(console.error)

	return msg.edit(content).then(() => {
		setTimeout(() => msg.delete().catch(console.error), timeout)
	})
}

kuro.sendTelegramNotification = (type, user, message) => {
	const msg = `*${type}* from *${user}*: \n${message}`
	telegram.sendMessage(config.telegramNotifications.userId, msg, { parse_mode: 'Markdown' })
}

kuro.log = function(msg, color) {
	if (color === undefined) console.log(`[Kuro]: ${msg}`)
	else console.log(chalk[color](`[Kuro]: ${msg}`))
}

kuro.error = function(msg) {
	console.log(chalk.red(`[Kuro]: ${msg}`))
}

kuro.log('Starting...', 'green')
kuro.login(config.token)

process.on('unhandledRejection', err => {
	kuro.error(`Uncaught Promise Error:\n${err.stack}`)
})
<commit_msg>Update kuro.js<commit_after>const fs = require('fs')
const path = require('path')

if (!fs.existsSync(path.join(__dirname, 'config.json'))) {
	console.log('config.json file not found, please run kuro-cli or create it on your own')
	process.exit()
}

const config = require('./config.json')
const Discord = require('discord.js')
const knex = require('knex')(config.database)
const chalk = require('chalk')

let TelegramBot
let telegram

if (config.hasOwnProperty('telegramNotifications')) {
	if (config.telegramNotifications.active) {
		TelegramBot = require('node-telegram-bot-api')
		telegram = new TelegramBot(config.telegramNotifications.botToken, { polling: false })
	}
}

let filesDirectory = path.join(__dirname, 'files')
fs.existsSync(filesDirectory) || fs.mkdirSync(filesDirectory)

// Initializing the ultimate tan
const kuro = new Discord.Client()

// When ready
kuro.once('ready', () => {

	// Create database if it doesn't exist
	fs.exists('db', (exists) => exists || fs.writeFile('db', ''))

	// Getting the database ready
	kuro.db = knex

	// Making config available on every module
	kuro.config = config

	kuro.loadCommands()

	kuro.log('Kuro is ready!', 'green')

	kuro.user.setAFK(true)
})

kuro.on('message', (msg) => {

	// If Telegram notifications are active, make extra checks
	if (config.hasOwnProperty('telegramNotifications')) {
		if (config.telegramNotifications.active) {
			// Check if someone is sending us a DM
			if (msg.channel.type === 'dm') {
				if (msg.author.id !== kuro.user.id) {
					return kuro.sendTelegramNotification('DM', msg.author.username, msg.content)
				}
			}

			// Check if it's someone mentioning us
			if (msg.isMentioned(kuro.user)) {
				return kuro.sendTelegramNotification('Ping', msg.author.username, msg.content)
			}
		}
	}

	// Ignore if the message is not ours
	if (msg.author.id !== kuro.user.id) return

	// Ignore if the message doesn't start with our prefix
	if (!msg.content.startsWith(config.prefix)) return

	// Ignore if empty command
	if (msg.content.length === config.prefix.length) return

	// Get all the arguments
	let tmp = msg.content.substring(config.prefix.length, msg.length).split(' ')
	let args = []

	for (let i = 1; i < tmp.length; i++) {
		args.push(tmp[i])
	}

	// Store the command separately
	let cmd = tmp[0]

	if (kuro.modules.hasOwnProperty(cmd)) return kuro.modules[cmd].run(msg, args)
	if (config.commandError.sendToModule === true) {
		return kuro.modules[config.commandError.module][config.commandError.function](msg, cmd)
	}

	return msg.delete()
})

kuro.on('disconnect', () => {
	kuro.error('CLIENT: Disconnected!')
	process.exit()
})
kuro.on('reconnecting', () => { kuro.log('CLIENT: Reconnecting...', 'green') })

kuro.loadCommands = function() {
	kuro.modules = {}

	// Load up all the modules
	fs.readdirSync('./commands/').forEach((file) => {
		let name = file.slice(0, -3)

		delete require.cache[require.resolve(`./commands/${file}`)]

		try {
			kuro.modules[name] = require(`./commands/${file}`)
			if (kuro.modules[name].hasOwnProperty('init')) {
				kuro.modules[name].init(kuro)
			}

			kuro.log(`Module ${name} is ready`)
		} catch (e) {
			kuro.error(`Error in module ${name}:\n${e.stack}`)
		}
	})
}

kuro.edit = function(msg, content, timeout = 3000) {
	if (timeout === 0) return msg.edit(content).catch(console.error)

	return msg.edit(content).then(() => {
		setTimeout(() => msg.delete().catch(console.error), timeout)
	})
}

kuro.sendTelegramNotification = (type, user, message) => {
	const msg = `*${type}* from *${user}*: \n${message}`
	telegram.sendMessage(config.telegramNotifications.userId, msg, { parse_mode: 'Markdown' })
}

kuro.log = function(msg, color) {
	if (color === undefined) console.log(`[Kuro]: ${msg}`)
	else console.log(chalk[color](`[Kuro]: ${msg}`))
}

kuro.error = function(msg) {
	console.log(chalk.red(`[Kuro]: ${msg}`))
}

kuro.log('Starting...', 'green')
kuro.login(config.token)

process.on('unhandledRejection', err => {
	kuro.error(`Uncaught Promise Error:\n${err.stack}`)
})
<|endoftext|>


<commit_before>/**
 * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity.
 * Counts the number of if, conditional, for, whilte, try, switch/case,
 * @author Patrick Brosset
 */

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    THRESHOLD = context.options[0];

    //--------------------------------------------------------------------------
    // Helpers
    //--------------------------------------------------------------------------

    // Storing all functions met during the parsing
    var fns = [];

    // When parsing a new function, store it in our function stack
    function startNewFunction(node) {
        fns.push({ node: node, complexity: 1 });
    }

    // Given a node, find which function it is placed into
    function getFunctionAtRange(node) {
        var stack = [], range = node.range;

        for(var i = 0; i < fns.length; i ++) {
            var fnRange = fns[i].node.range;

            if(fnRange[0] <= range[0] && fnRange[1] >= range[1]) {
                stack.push(fns[i]);
            }
        }

        return stack.sort(function(fn1, fn2) {
            return fn2.node.range[0] - fn1.node.range[0];
        })[0];
    }

    function increaseComplexity(node) {
        var fn = getFunctionAtRange(node);
        fn && fn.complexity ++;
    }

    function increaseSwitchComplexity(node) {
        // Avoiding `default`
        node.test && increaseComplexity(node);
    }

    function increaseLogicalComplexity(node) {
        // Avoiding &&
        node.operator === "||" && increaseComplexity(node);
    }

    function reportComplexity() {
        var i, fn;
        for(i = 0; i < fns.length; i ++) {
            fn = fns[i], name = fn.node.id ? fn.node.id.name : "anonymous";
            if(fn.complexity > THRESHOLD) {
                context.report(fn.node, "Function '{{name}}' has a complexity of {{complexity}}.", { name: name, complexity: fn.complexity });
            }
        }
    }

    //--------------------------------------------------------------------------
    // Public API
    //--------------------------------------------------------------------------

    return {
        "FunctionDeclaration": startNewFunction,
        "FunctionExpression": startNewFunction,

        "CatchClause": increaseComplexity,
        "ConditionalExpression": increaseComplexity,
        "LogicalExpression": increaseLogicalComplexity,
        "ForStatement": increaseComplexity,
        "ForInStatement": increaseComplexity,
        "IfStatement": increaseComplexity,
        "SwitchCase": increaseSwitchComplexity,
        "WhileStatement": increaseComplexity,
        "DoWhileStatement": increaseComplexity,

        "Program:after": reportComplexity
    };

};
<commit_msg>Fixing style issues discovered while npm testing<commit_after>/**
 * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity.
 * Counts the number of if, conditional, for, whilte, try, switch/case,
 * @author Patrick Brosset
 */

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    THRESHOLD = context.options[0];

    //--------------------------------------------------------------------------
    // Helpers
    //--------------------------------------------------------------------------

    // Storing all functions met during the parsing
    var fns = [];

    // When parsing a new function, store it in our function stack
    function startNewFunction(node) {
        fns.push({ node: node, complexity: 1 });
    }

    // Given a node, find which function it is placed into
    function getFunctionAtRange(node) {
        var stack = [], range = node.range;

        for(var i = 0; i < fns.length; i ++) {
            var fnRange = fns[i].node.range;

            if(fnRange[0] <= range[0] && fnRange[1] >= range[1]) {
                stack.push(fns[i]);
            }
        }

        return stack.sort(function(fn1, fn2) {
            return fn2.node.range[0] - fn1.node.range[0];
        })[0];
    }

    function increaseComplexity(node) {
        var fn = getFunctionAtRange(node);
        if(fn) {
            fn.complexity ++;
        }
    }

    function increaseSwitchComplexity(node) {
        // Avoiding `default`
        if(node.test) {
            increaseComplexity(node);
        }
    }

    function increaseLogicalComplexity(node) {
        // Avoiding &&
        if(node.operator === "||") {
            increaseComplexity(node);
        }
    }

    function reportComplexity() {
        var i, fn, name;
        for(i = 0; i < fns.length; i ++) {
            fn = fns[i];
            name = "anonymous";
            if(fn.node.id) {
                name = fn.node.id.name;
            }
            if(fn.complexity > THRESHOLD) {
                context.report(fn.node, "Function '{{name}}' has a complexity of {{complexity}}.", { name: name, complexity: fn.complexity });
            }
        }
    }

    //--------------------------------------------------------------------------
    // Public API
    //--------------------------------------------------------------------------

    return {
        "FunctionDeclaration": startNewFunction,
        "FunctionExpression": startNewFunction,

        "CatchClause": increaseComplexity,
        "ConditionalExpression": increaseComplexity,
        "LogicalExpression": increaseLogicalComplexity,
        "ForStatement": increaseComplexity,
        "ForInStatement": increaseComplexity,
        "IfStatement": increaseComplexity,
        "SwitchCase": increaseSwitchComplexity,
        "WhileStatement": increaseComplexity,
        "DoWhileStatement": increaseComplexity,

        "Program:after": reportComplexity
    };

};
<|endoftext|>


<commit_before>
L.CRS.EPSG3395 = L.extend({}, L.CRS, {
	code: 'EPSG:3395',

	projection: L.Projection.Mercator,

	transformation: (function () {
		var m = L.Projection.Mercator,
		    r = m.R_MAJOR,
		    r2 = m.R_MINOR;

		return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
	}())
});
<commit_msg>Fixing wrong EPGS3395 transformation<commit_after>
L.CRS.EPSG3395 = L.extend({}, L.CRS, {
	code: 'EPSG:3395',

	projection: L.Projection.Mercator,

	transformation: (function () {
		var m = L.Projection.Mercator,
		    r = m.R_MAJOR,
		    scale = 0.5 / (Math.PI * r);

		return new L.Transformation(scale, 0.5, -scale, 0.5);
	}())
});
<|endoftext|>