<commit_before>'use strict';

// Dependencies.
var RecursiveIterator = require('recursive-iterator');

/**
 * Adds the tags property to a swagger object.
 * @function
 * @param {object} conf - Flexible configuration.
 */
function _attachTags(conf) {
  var tag = conf.tag;
  var swaggerObject = conf.swaggerObject;
  var propertyName = conf.propertyName;

  // Correct deprecated property.
  if (propertyName === 'tag') {
    propertyName = 'tags';
  }

  if (Array.isArray(tag)) {
    for (var i = 0; i < tag.length; i = i + 1) {
      swaggerObject[propertyName].push(tag[i]);
    }
  } else {
    swaggerObject[propertyName].push(tag);
  }
}

/**
 * Merges two objects
 * @function
 * @param {object} obj1 - Object 1
 * @param {object} obj2 - Object 2
 * @returns {object} Merged Object
 */
function _objectMerge(obj1, obj2) {
  var obj3 = {};
  for (var attr in obj1) {
    if (obj1.hasOwnProperty(attr)) {
      obj3[attr] = obj1[attr];
    }
  }
  for (var name in obj2) {
    if (obj2.hasOwnProperty(name)) {
      obj3[name] = obj2[name];
    }
  }
  return obj3;
}

/**
 * Adds necessary swagger schema object properties.
 * @see https://goo.gl/Eoagtl
 * @function
 * @param {object} swaggerObject - The object to receive properties.
 * @returns {object} swaggerObject - The updated object.
 */
function swaggerizeObj(swaggerObject) {
  swaggerObject.swagger = '2.0';
  swaggerObject.paths = swaggerObject.paths || {};
  swaggerObject.definitions = swaggerObject.definitions || {};
  swaggerObject.responses = swaggerObject.responses || {};
  swaggerObject.parameters = swaggerObject.parameters || {};
  swaggerObject.securityDefinitions = swaggerObject.securityDefinitions || {};
  swaggerObject.tags = swaggerObject.tags || [];
  return swaggerObject;
}

/**
 * List of deprecated or wrong swagger schema properties in singular.
 * @function
 * @returns {array} The list of deprecated property names.
 */
function _getSwaggerSchemaWrongProperties() {
  return [
    'consume',
    'produce',
    'path',
    'tag',
    'definition',
    'securityDefinition',
    'scheme',
    'response',
    'parameter',
  ];
}

/**
 * Makes a deprecated property plural if necessary.
 * @function
 * @param {string} propertyName - The swagger property name to check.
 * @returns {string} The updated propertyName if neccessary.
 */
function _correctSwaggerKey(propertyName) {
  var wrong = _getSwaggerSchemaWrongProperties();
  if (wrong.indexOf(propertyName) > 0) {
    // Returns the corrected property name.
    return propertyName + 's';
  }
  return propertyName;
}

/**
 * Handles swagger propertyName in pathObject context for swaggerObject.
 * @function
 * @param {object} swaggerObject - The swagger object to update.
 * @param {object} pathObject - The input context of an item for swaggerObject.
 * @param {string} propertyName - The property to handle.
 */
function _organizeSwaggerProperties(swaggerObject, pathObject, propertyName) {
  var simpleProperties = [
    'consume',
    'consumes',
    'produce',
    'produces',
    'path',
    'paths',
    'schema',
    'schemas',
    'securityDefinition',
    'securityDefinitions',
    'response',
    'responses',
    'parameter',
    'parameters',
    'definition',
    'definitions',
  ];

  // Common properties.
  if (simpleProperties.indexOf(propertyName) !== -1) {
    var keyName = _correctSwaggerKey(propertyName);
    var definitionNames = Object
      .getOwnPropertyNames(pathObject[propertyName]);
    for (var k = 0; k < definitionNames.length; k = k + 1) {
      var definitionName = definitionNames[k];
      swaggerObject[keyName][definitionName] =
        pathObject[propertyName][definitionName];
    }
  // Tags.
  } else if (propertyName === 'tag' || propertyName === 'tags') {
    var tag = pathObject[propertyName];
    _attachTags({
      tag: tag,
      swaggerObject: swaggerObject,
      propertyName: propertyName,
    });
  // Paths.
  } else {
    swaggerObject.paths[propertyName] = _objectMerge(
      swaggerObject.paths[propertyName], pathObject[propertyName]
    );
  }
}

/**
 * Adds the data in to the swagger object.
 * @function
 * @param {object} swaggerObject - Swagger object which will be written to
 * @param {object[]} data - objects of parsed swagger data from yml or jsDoc
 *                          comments
 */
function addDataToSwaggerObject(swaggerObject, data) {
  if (!swaggerObject || !data) {
    throw new Error('swaggerObject and data are required!');
  }

  for (var i = 0; i < data.length; i = i + 1) {
    var pathObject = data[i];
    var propertyNames = Object.getOwnPropertyNames(pathObject);
    // Iterating the properties of the a given pathObject.
    for (var j = 0; j < propertyNames.length; j = j + 1) {
      var propertyName = propertyNames[j];
      // Do what's necessary to organize the end specification.
      _organizeSwaggerProperties(swaggerObject, pathObject, propertyName);
    }
  }
}

/**
 * Aggregates a list of wrong properties in problems.
 * Searches in object based on a list of wrongSet.
 * @param {Array|object} list - a list to iterate
 * @param {Array} wrongSet - a list of wrong properties
 * @param {Array} problems - aggregate list of found problems
 */
function seekWrong(list, wrongSet, problems) {
  var iterator = new RecursiveIterator(list, 0, false);
  for (var item = iterator.next(); !item.done; item = iterator.next()) {
    if (wrongSet.indexOf(item.value.key) > 0) {
      problems.push(item.value.key);
    }
  }
}

/**
 * Returns a list of problematic tags if any.
 * @function
 * @param {Array} sources - a list of objects to iterate and check
 * @returns {Array} problems - a list of problems encountered
 */
function findDeprecated(sources) {
  var wrong = _getSwaggerSchemaWrongProperties();
  // accumulate problems encountered
  var problems = [];
  sources.forEach(function(source) {
    // Iterate through `source`, search for `wrong`, accumulate in `problems`.
    seekWrong(source, wrong, problems);
  });
  return problems;
}

module.exports = {
  addDataToSwaggerObject: addDataToSwaggerObject,
  swaggerizeObj: swaggerizeObj,
  findDeprecated: findDeprecated,
};
<commit_msg>Ignore deprecation check<commit_after>'use strict';

// Dependencies.
var RecursiveIterator = require('recursive-iterator');

/**
 * Adds the tags property to a swagger object.
 * @function
 * @param {object} conf - Flexible configuration.
 */
function _attachTags(conf) {
  var tag = conf.tag;
  var swaggerObject = conf.swaggerObject;
  var propertyName = conf.propertyName;

  // Correct deprecated property.
  if (propertyName === 'tag') {
    propertyName = 'tags';
  }

  if (Array.isArray(tag)) {
    for (var i = 0; i < tag.length; i = i + 1) {
      swaggerObject[propertyName].push(tag[i]);
    }
  } else {
    swaggerObject[propertyName].push(tag);
  }
}

/**
 * Merges two objects
 * @function
 * @param {object} obj1 - Object 1
 * @param {object} obj2 - Object 2
 * @returns {object} Merged Object
 */
function _objectMerge(obj1, obj2) {
  var obj3 = {};
  for (var attr in obj1) {
    if (obj1.hasOwnProperty(attr)) {
      obj3[attr] = obj1[attr];
    }
  }
  for (var name in obj2) {
    if (obj2.hasOwnProperty(name)) {
      obj3[name] = obj2[name];
    }
  }
  return obj3;
}

/**
 * Adds necessary swagger schema object properties.
 * @see https://goo.gl/Eoagtl
 * @function
 * @param {object} swaggerObject - The object to receive properties.
 * @returns {object} swaggerObject - The updated object.
 */
function swaggerizeObj(swaggerObject) {
  swaggerObject.swagger = '2.0';
  swaggerObject.paths = swaggerObject.paths || {};
  swaggerObject.definitions = swaggerObject.definitions || {};
  swaggerObject.responses = swaggerObject.responses || {};
  swaggerObject.parameters = swaggerObject.parameters || {};
  swaggerObject.securityDefinitions = swaggerObject.securityDefinitions || {};
  swaggerObject.tags = swaggerObject.tags || [];
  return swaggerObject;
}

/**
 * List of deprecated or wrong swagger schema properties in singular.
 * @function
 * @returns {array} The list of deprecated property names.
 */
function _getSwaggerSchemaWrongProperties() {
  return [
    'consume',
    'produce',
    'path',
    'tag',
    'definition',
    'securityDefinition',
    'scheme',
    'response',
    'parameter',
  ];
}

/**
 * Makes a deprecated property plural if necessary.
 * @function
 * @param {string} propertyName - The swagger property name to check.
 * @returns {string} The updated propertyName if neccessary.
 */
function _correctSwaggerKey(propertyName) {
  var wrong = _getSwaggerSchemaWrongProperties();
  if (wrong.indexOf(propertyName) > 0) {
    // Returns the corrected property name.
    return propertyName + 's';
  }
  return propertyName;
}

/**
 * Handles swagger propertyName in pathObject context for swaggerObject.
 * @function
 * @param {object} swaggerObject - The swagger object to update.
 * @param {object} pathObject - The input context of an item for swaggerObject.
 * @param {string} propertyName - The property to handle.
 */
function _organizeSwaggerProperties(swaggerObject, pathObject, propertyName) {
  var simpleProperties = [
    'consume',
    'consumes',
    'produce',
    'produces',
    'path',
    'paths',
    'schema',
    'schemas',
    'securityDefinition',
    'securityDefinitions',
    'response',
    'responses',
    'parameter',
    'parameters',
    'definition',
    'definitions',
  ];

  // Common properties.
  if (simpleProperties.indexOf(propertyName) !== -1) {
    var keyName = _correctSwaggerKey(propertyName);
    var definitionNames = Object
      .getOwnPropertyNames(pathObject[propertyName]);
    for (var k = 0; k < definitionNames.length; k = k + 1) {
      var definitionName = definitionNames[k];
      swaggerObject[keyName][definitionName] =
        pathObject[propertyName][definitionName];
    }
  // Tags.
  } else if (propertyName === 'tag' || propertyName === 'tags') {
    var tag = pathObject[propertyName];
    _attachTags({
      tag: tag,
      swaggerObject: swaggerObject,
      propertyName: propertyName,
    });
  // Paths.
  } else {
    swaggerObject.paths[propertyName] = _objectMerge(
      swaggerObject.paths[propertyName], pathObject[propertyName]
    );
  }
}

/**
 * Adds the data in to the swagger object.
 * @function
 * @param {object} swaggerObject - Swagger object which will be written to
 * @param {object[]} data - objects of parsed swagger data from yml or jsDoc
 *                          comments
 */
function addDataToSwaggerObject(swaggerObject, data) {
  if (!swaggerObject || !data) {
    throw new Error('swaggerObject and data are required!');
  }

  for (var i = 0; i < data.length; i = i + 1) {
    var pathObject = data[i];
    var propertyNames = Object.getOwnPropertyNames(pathObject);
    // Iterating the properties of the a given pathObject.
    for (var j = 0; j < propertyNames.length; j = j + 1) {
      var propertyName = propertyNames[j];
      // Do what's necessary to organize the end specification.
      _organizeSwaggerProperties(swaggerObject, pathObject, propertyName);
    }
  }
}

/**
 * Aggregates a list of wrong properties in problems.
 * Searches in object based on a list of wrongSet.
 * @param {Array|object} list - a list to iterate
 * @param {Array} wrongSet - a list of wrong properties
 * @param {Array} problems - aggregate list of found problems
 */
function seekWrong(list, wrongSet, problems) {
  var iterator = new RecursiveIterator(list, 0, false);
  for (var item = iterator.next(); !item.done; item = iterator.next()) {
    var isDirectChildOfProperties = item.value.path[item.value.path.length - 2] === 'properties';
    if (wrongSet.indexOf(item.value.key) > 0 && !isDirectChildOfProperties) {
      problems.push(item.value.key);
    }
  }
}

/**
 * Returns a list of problematic tags if any.
 * @function
 * @param {Array} sources - a list of objects to iterate and check
 * @returns {Array} problems - a list of problems encountered
 */
function findDeprecated(sources) {
  var wrong = _getSwaggerSchemaWrongProperties();
  // accumulate problems encountered
  var problems = [];
  sources.forEach(function(source) {
    // Iterate through `source`, search for `wrong`, accumulate in `problems`.
    seekWrong(source, wrong, problems);
  });
  return problems;
}

module.exports = {
  addDataToSwaggerObject: addDataToSwaggerObject,
  swaggerizeObj: swaggerizeObj,
  findDeprecated: findDeprecated,
};
<|endoftext|>


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

const {
  BLINKSOCKS_DIR,
  LOG_DIR,
  DEFAULT_GFWLIST_PATH,
  SUDO_AGENT_CONTROLLER,
  SUDO_AGENT_IMPLEMENT
} = require('./constants');

const BUILT_IN_GFWLIST = path.join(__dirname, 'resources/gfwlist.txt');

function mkdir(dir) {
  try {
    fs.lstatSync(dir);
  } catch (err) {
    if (err.code === 'ENOENT') {
      fs.mkdirSync(dir);
    }
  }
}

// create ~/.blinksocks directory if not exist
mkdir(BLINKSOCKS_DIR);

// create ~/.blinksocks/logs if not exist
mkdir(LOG_DIR);

// create ~/.blinksocks/gfwlist.txt if not exist
try {
  fs.lstatSync(DEFAULT_GFWLIST_PATH);
} catch (err) {
  if (err.code === 'ENOENT') {
    const data = fs.readFileSync(BUILT_IN_GFWLIST);
    fs.writeFileSync(DEFAULT_GFWLIST_PATH, data);
  }
}

// overwrite ~/sudo-agent.js and ~/darwin.sudo.js for macOS
if (process.platform === 'darwin') {
  fs.createReadStream(path.join(__dirname, 'system/sudo-agent.js')).pipe(fs.createWriteStream(SUDO_AGENT_CONTROLLER));
  fs.createReadStream(path.join(__dirname, 'system/platforms/darwin.sudo.js')).pipe(fs.createWriteStream(SUDO_AGENT_IMPLEMENT));
}
<commit_msg>chore(darwin): also copy proxy_conf_helper when init<commit_after>const fs = require('fs');
const path = require('path');

const {
  BLINKSOCKS_DIR,
  LOG_DIR,
  DEFAULT_GFWLIST_PATH,
  SUDO_AGENT_CONTROLLER,
  SUDO_AGENT_IMPLEMENT
} = require('./constants');

const BUILT_IN_GFWLIST = path.join(__dirname, 'resources/gfwlist.txt');

function mkdir(dir) {
  try {
    fs.lstatSync(dir);
  } catch (err) {
    if (err.code === 'ENOENT') {
      fs.mkdirSync(dir);
    }
  }
}

// create ~/.blinksocks directory if not exist
mkdir(BLINKSOCKS_DIR);

// create ~/.blinksocks/logs if not exist
mkdir(LOG_DIR);

// create ~/.blinksocks/gfwlist.txt if not exist
try {
  fs.lstatSync(DEFAULT_GFWLIST_PATH);
} catch (err) {
  if (err.code === 'ENOENT') {
    const data = fs.readFileSync(BUILT_IN_GFWLIST);
    fs.writeFileSync(DEFAULT_GFWLIST_PATH, data);
  }
}

// overwrite ~/sudo-agent.js and ~/darwin.sudo.js for macOS
if (process.platform === 'darwin') {
  const src = [
    ['system/sudo-agent.js', SUDO_AGENT_CONTROLLER],
    ['system/platforms/darwin.sudo.js', SUDO_AGENT_IMPLEMENT],
    ['resources/proxy_conf_helper', path.join(BLINKSOCKS_DIR, 'proxy_conf_helper'), {mode: 0o755}]
  ];
  for (const s of src) {
    const inp = fs.createReadStream(path.join(__dirname, s[0]));
    const out = fs.createWriteStream(s[1], s[2] || {});
    inp.pipe(out);
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var version = 22;
console.log("Octo-Node v" + version + " starting...");

var cfg = require("../config");
cfg.version = version;
var tools = require("./tools");
var uuid = require("node-uuid");
var nodeid = uuid();
var os = require("os");
var dgram = require("dgram");
var EventEmitter = require("events").EventEmitter;
var ev = new EventEmitter();
var ips = null;
var peers = [];

var s = dgram.createSocket("udp4");

console.log("Connecting to " + cfg.netname);

function debug(msg) {
	if (cfg.debug) {
		console.log(msg);
	}
}

function sendToIP(ip, port, msg) {
	msg.octo = true;
	msg.from = nodeid;
	msg.version = cfg.version;
	msg.netname = cfg.netname;
	msg.port = cfg.port;
	tools.pack(msg, function(err, res) {
		if (err) {
			console.log(err);
			return;
		}
		tools.addDataUsage(res, true);
		s.send(res, 0, res.length, port, ip);
	});
}

function sendToID(id, msg) {
	var found = false;
	peers.forEach(function(v) {
		if (v.id == id) {
			sendToIP(v.ip, v.port, msg);
			found = true;
		}
	});
	if (!found) {
		debug("Failed to send message to " + id);
		debug(msg);
	}
}

function registerPeer(addr, port, id) {
	sendToIP(addr, port {
		cmd: "register",
		args: {
			ips: ips,
			from: nodeid,
			leech: cfg.leech,
			port: cfg.port
		},
		to: id
	});
}

function announcePeers(peer) {
	if (peer) {
		console.log(peer + " connected : " + peers.length + " total peer(s)");
	} else {
		console.log("Connected to " + peers.length + " peer(s)");
	}
}

function start() {
	s.bind(cfg.port, "0.0.0.0", function() {
		cfg.seeds.forEach(function(v) {
			registerPeer(v[0], v[1]);
		});
		console.log("Pinged " + cfg.seeds.length + " peers(s)");
		console.log("Now accepting incoming connections");
	});
}

tools.ipList(function(iplist) {
	ips = iplist;
	start();
});

var commands = {};

commands.ping = function(args, peer) {
	sendToID(peer.id, {
		cmd: "pong"
	});
};

commands.pong = function(args, peer) {
	peer.ping = true;
};

commands.register = function(args, rinfo) {
	if (args.ips && args.from && args.port) {
		if (peers.length >= cfg.maxPeers) { return; }
		peers.push({
			ping: true,
			ip: rinfo.address,
			ips: args.ips,
			id: args.from,
			leech: args.leech,
			port: args.port
		});
		registerPeer(rinfo.address);
		announcePeers(args.from);
		ev.emit("peer", args.from);
	}
};

commands.peerlist = function(args, peer) {
	if (args.peers && !cfg.leech) {
		args.peers.forEach(function(v) {
			var found = false;
			peers.forEach(function(vpeer) {
				if (vpeer.id == v.id) {
					found = true;
				}
			});
			if (!found) {
				v.ips.forEach(function(vip) {
					registerPeer(vip, v.id);
				});
			}
		});
	}
};

var msgs = {};

commands.spreadmessage = function(args, peer) {
	if (args["msg"] && args["msgid"]) {
		if (!msgs[args["msgid"]]) {
			msgs[args["msgid"]] = true;
			ev.emit("message", args["msg"], args["msgid"], args["core"]);
			peers.forEach(function(v) {
				sendToID(v.id, {
					cmd: "spreadmessage",
					args: args
				});
			});
			if (!args["core"]) {
				console.log(args["msg"]);
			}
		}
	}
};

commands.getpeerlist = function(args, peer) {
	var sendpeers = [];
	peers.forEach(function(v) {
		if (!v.leech && v.id != peer.id) {
			sendpeers.push(v);
		}
	});
	sendToID(peer.id, {
		cmd: "peerlist",
		args: sendpeers
	});
};

s.on("message", function(buff, rinfo) {
	tools.addDataUsage(buff, false);
	tools.unpack(buff, function(err, msg) {
		if (err) {
			console.log(err);
			return;
		}
		if (msg) {
			if (msg["octo"] && msg["cmd"] && msg["from"] && msg["version"] && msg["netname"]) {
				if (commands[msg["cmd"]] && msg["version"] == cfg.version && msg["netname"] == cfg.netname) {
					if(msg["to"]) {
						if(msg["to"] != nodeid) {
							debug("Received message ment for someone else");
							return;
						}
					}
					if (msg["cmd"] != "register") {
						peers.forEach(function(v) {
							if (v.ip == rinfo.address && v.id == msg["from"] && v.port == msg["port"]) {
								commands[msg["cmd"]](msg["args"], v);
							}
						});
					} else {
						var exit = false;
						peers.forEach(function(v) {
							if (v.ip == rinfo.address && v.port == msg["port"]) {
								exit = true;
							}
						});
						if (exit) { return; }
						commands.register(msg["args"], rinfo);
					}
				}
			}
		}
	});
});

setInterval(function() {
	var toRemove = [];
	peers.forEach(function(peer) {
		if (peer.ping) {
			peer.ping = false;
			sendToID(peer.id, {
				cmd: "ping"
			});
		} else {
			ev.emit("disconnect", peer.id);
			toRemove.push(peer.id);
		}
		if (toRemove.length > 0) {
			toRemove.forEach(function(id) {
				var newPeers = [];
				peers.forEach(function(peer) {
					if (peer.id != id) {
						newPeers.push(JSON.parse(JSON.stringify(peer)));
					}
				});
				peers = newPeers;
			});
			announcePeers();
		}
	});
}, 1000 * 5);

setInterval(function() {
	cfg.seeds.forEach(function(v) {
		registerPeer(v);
	});
}, 1000 * 10);

if (!cfg.leech) {
	setInterval(function() {
		peers.forEach(function(peer) {
			sendToID(peer.id, {
				cmd: "getpeerlist"
			});
		});
	}, 1000 * 60);
}

// API

function sendMessage(msg, core) {
	commands.spreadmessage({
		msg: msg,
		msgid: uuid(),
		core: core
	});
}

module.exports = ev;
module.exports.id = nodeid;
module.exports.ips = ips;
module.exports.sendMessage = sendMessage;
<commit_msg>Fix syntax<commit_after>#!/usr/bin/env node
var version = 22;
console.log("Octo-Node v" + version + " starting...");

var cfg = require("../config");
cfg.version = version;
var tools = require("./tools");
var uuid = require("node-uuid");
var nodeid = uuid();
var os = require("os");
var dgram = require("dgram");
var EventEmitter = require("events").EventEmitter;
var ev = new EventEmitter();
var ips = null;
var peers = [];

var s = dgram.createSocket("udp4");

console.log("Connecting to " + cfg.netname);

function debug(msg) {
	if (cfg.debug) {
		console.log(msg);
	}
}

function sendToIP(ip, port, msg) {
	msg.octo = true;
	msg.from = nodeid;
	msg.version = cfg.version;
	msg.netname = cfg.netname;
	msg.port = cfg.port;
	tools.pack(msg, function(err, res) {
		if (err) {
			console.log(err);
			return;
		}
		tools.addDataUsage(res, true);
		s.send(res, 0, res.length, port, ip);
	});
}

function sendToID(id, msg) {
	var found = false;
	peers.forEach(function(v) {
		if (v.id == id) {
			sendToIP(v.ip, v.port, msg);
			found = true;
		}
	});
	if (!found) {
		debug("Failed to send message to " + id);
		debug(msg);
	}
}

function registerPeer(addr, port, id) {
	sendToIP(addr, port, {
		cmd: "register",
		args: {
			ips: ips,
			from: nodeid,
			leech: cfg.leech,
			port: cfg.port
		},
		to: id
	});
}

function announcePeers(peer) {
	if (peer) {
		console.log(peer + " connected : " + peers.length + " total peer(s)");
	} else {
		console.log("Connected to " + peers.length + " peer(s)");
	}
}

function start() {
	s.bind(cfg.port, "0.0.0.0", function() {
		cfg.seeds.forEach(function(v) {
			registerPeer(v[0], v[1]);
		});
		console.log("Pinged " + cfg.seeds.length + " peers(s)");
		console.log("Now accepting incoming connections");
	});
}

tools.ipList(function(iplist) {
	ips = iplist;
	start();
});

var commands = {};

commands.ping = function(args, peer) {
	sendToID(peer.id, {
		cmd: "pong"
	});
};

commands.pong = function(args, peer) {
	peer.ping = true;
};

commands.register = function(args, rinfo) {
	if (args.ips && args.from && args.port) {
		if (peers.length >= cfg.maxPeers) { return; }
		peers.push({
			ping: true,
			ip: rinfo.address,
			ips: args.ips,
			id: args.from,
			leech: args.leech,
			port: args.port
		});
		registerPeer(rinfo.address);
		announcePeers(args.from);
		ev.emit("peer", args.from);
	}
};

commands.peerlist = function(args, peer) {
	if (args.peers && !cfg.leech) {
		args.peers.forEach(function(v) {
			var found = false;
			peers.forEach(function(vpeer) {
				if (vpeer.id == v.id) {
					found = true;
				}
			});
			if (!found) {
				v.ips.forEach(function(vip) {
					registerPeer(vip, v.id);
				});
			}
		});
	}
};

var msgs = {};

commands.spreadmessage = function(args, peer) {
	if (args["msg"] && args["msgid"]) {
		if (!msgs[args["msgid"]]) {
			msgs[args["msgid"]] = true;
			ev.emit("message", args["msg"], args["msgid"], args["core"]);
			peers.forEach(function(v) {
				sendToID(v.id, {
					cmd: "spreadmessage",
					args: args
				});
			});
			if (!args["core"]) {
				console.log(args["msg"]);
			}
		}
	}
};

commands.getpeerlist = function(args, peer) {
	var sendpeers = [];
	peers.forEach(function(v) {
		if (!v.leech && v.id != peer.id) {
			sendpeers.push(v);
		}
	});
	sendToID(peer.id, {
		cmd: "peerlist",
		args: sendpeers
	});
};

s.on("message", function(buff, rinfo) {
	tools.addDataUsage(buff, false);
	tools.unpack(buff, function(err, msg) {
		if (err) {
			console.log(err);
			return;
		}
		if (msg) {
			if (msg["octo"] && msg["cmd"] && msg["from"] && msg["version"] && msg["netname"]) {
				if (commands[msg["cmd"]] && msg["version"] == cfg.version && msg["netname"] == cfg.netname) {
					if(msg["to"]) {
						if(msg["to"] != nodeid) {
							debug("Received message ment for someone else");
							return;
						}
					}
					if (msg["cmd"] != "register") {
						peers.forEach(function(v) {
							if (v.ip == rinfo.address && v.id == msg["from"] && v.port == msg["port"]) {
								commands[msg["cmd"]](msg["args"], v);
							}
						});
					} else {
						var exit = false;
						peers.forEach(function(v) {
							if (v.ip == rinfo.address && v.port == msg["port"]) {
								exit = true;
							}
						});
						if (exit) { return; }
						commands.register(msg["args"], rinfo);
					}
				}
			}
		}
	});
});

setInterval(function() {
	var toRemove = [];
	peers.forEach(function(peer) {
		if (peer.ping) {
			peer.ping = false;
			sendToID(peer.id, {
				cmd: "ping"
			});
		} else {
			ev.emit("disconnect", peer.id);
			toRemove.push(peer.id);
		}
		if (toRemove.length > 0) {
			toRemove.forEach(function(id) {
				var newPeers = [];
				peers.forEach(function(peer) {
					if (peer.id != id) {
						newPeers.push(JSON.parse(JSON.stringify(peer)));
					}
				});
				peers = newPeers;
			});
			announcePeers();
		}
	});
}, 1000 * 5);

setInterval(function() {
	cfg.seeds.forEach(function(v) {
		registerPeer(v);
	});
}, 1000 * 10);

if (!cfg.leech) {
	setInterval(function() {
		peers.forEach(function(peer) {
			sendToID(peer.id, {
				cmd: "getpeerlist"
			});
		});
	}, 1000 * 60);
}

// API

function sendMessage(msg, core) {
	commands.spreadmessage({
		msg: msg,
		msgid: uuid(),
		core: core
	});
}

module.exports = ev;
module.exports.id = nodeid;
module.exports.ips = ips;
module.exports.sendMessage = sendMessage;
<|endoftext|>


<commit_before>var _      = require('underscore')
var async  = require('async')
var op     = require('object-path')
var router = require('express').Router()

var entu   = require('../helpers/entu')

router.get('/requests', function(req, res) {
    var top = req.query.top || 5
    var days = req.query.days || 7

    var today = new Date()
    var beginning = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (days - 1))

    async.waterfall([
        function(callback) {
            entu.dbConnection('entu', callback)
        },
        function(connection, callback) {
            connection.collection('request').aggregate([
            	{
            		'$match' : {
                		date: {
                    		$gte: beginning
                		},

            		}
            	},
            	{
            		'$group' : {
            			_id: {
                            host: '$host',
                            month: { $month: '$date' },
                            day: { $dayOfMonth: '$date' },
                            year: { $year: '$date' }
                        },
            			count: {
            				$sum: 1
            			}
            		}
            	}
            ]).toArray(callback)
        },
        function(result, callback) {
            var seriesTotals = {}
            var seriesData = {}
            for (var i in result) {
                if(!result.hasOwnProperty(i)) { continue }

                var host = op.get(result[i], '_id.host')
                var day = '00' + op.get(result[i], '_id.day')
                var day = day.substr(day.length - 2)
                var month = '00' + op.get(result[i], '_id.month')
                var month = month.substr(month.length - 2)
                var year = op.get(result[i], '_id.year')

                var date = [year, month, day].join('-')
                var count = op.get(result[i], 'count')

                op.set(seriesTotals, date, op.get(seriesTotals, date, 0) + count)
                op.set(seriesData, [host, 'sum'], op.get(seriesData, [host, 'sum'], 0) + count)
                op.set(seriesData, [host, 'name'], host)
                op.push(seriesData, [host, 'data'], [date, count])
                op.set(seriesData, [host, 'incomplete_from'], today.toISOString().substr(0, 10))
            }

            var graphData = {
                x_axis: {
                    type: 'datetime'
                },
                series: _.sortBy(_.values(seriesData), 'sum').reverse().slice(0, top)
            }
            graphData.series.unshift({
                name: 'all',
                data: _.map(seriesTotals, function(num, key){
                    return [key, num]
                }),
                incomplete_from: today.toISOString().substr(0, 10)
            })

            callback(null, graphData)
        },
    ], function(err, result) {
        if(err) {
            res.send({
                error: err,
                version: APP_VERSION,
                started: APP_STARTED
            })
        } else {
            res.send(result)
        }
    })
})

router.get('/test', function() {
    throw new Error('böö')
})

module.exports = router
<commit_msg>Group by hour<commit_after>var _      = require('underscore')
var async  = require('async')
var op     = require('object-path')
var router = require('express').Router()

var entu   = require('../helpers/entu')

router.get('/requests', function(req, res) {
    var top = req.query.top || 5
    var days = req.query.days || 7

    var today = new Date()
    var beginning = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (days - 1))

    async.waterfall([
        function(callback) {
            entu.dbConnection('entu', callback)
        },
        function(connection, callback) {
            connection.collection('request').aggregate([
            	{
            		'$match' : {
                		date: {
                    		$gte: beginning
                		},

            		}
            	},
            	{
            		'$group' : {
            			_id: {
                            host: '$host',
                            date: { $dateToString: { format: "%Y-%m-%d %H", date: "$date" } },
                        },
            			count: {
            				$sum: 1
            			}
            		}
            	}
            ]).toArray(callback)
        },
        function(result, callback) {
            var seriesTotals = {}
            var seriesData = {}
            for (var i in result) {
                if(!result.hasOwnProperty(i)) { continue }

                var host = op.get(result[i], '_id.host')
                var date = op.get(result[i], '_id.date')
                var count = op.get(result[i], 'count')

                op.set(seriesTotals, date, op.get(seriesTotals, date, 0) + count)
                op.set(seriesData, [host, 'sum'], op.get(seriesData, [host, 'sum'], 0) + count)
                op.set(seriesData, [host, 'name'], host)
                op.push(seriesData, [host, 'data'], [date, count])
                op.set(seriesData, [host, 'incomplete_from'], today.toISOString().substr(0, 10))
            }

            var graphData = {
                x_axis: {
                    type: 'datetime'
                },
                series: _.sortBy(_.values(seriesData), 'sum').reverse().slice(0, top)
            }
            graphData.series.unshift({
                name: 'all',
                data: _.map(seriesTotals, function(num, key){
                    return [key, num]
                }),
                incomplete_from: today.toISOString().substr(0, 10)
            })

            callback(null, graphData)
        },
    ], function(err, result) {
        if(err) {
            res.send({
                error: err,
                version: APP_VERSION,
                started: APP_STARTED
            })
        } else {
            res.send(result)
        }
    })
})

router.get('/test', function() {
    throw new Error('böö')
})

module.exports = router
<|endoftext|>


<commit_before>"use strict";
// external deps
var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

module.exports = class BaseManager {
    constructor(db, user, locale) {
        this.db = db;
        this.user = user;
        this.locale = locale;

        this.collection = null;
    }

    _beforeInsert(data) {
        return Promise.resolve(data);
    }

    _afterInsert(id) {
        return Promise.resolve(id);
    }

    _beforeUpdate(data) {
        return Promise.resolve(data);
    }

    _afterUpdate(id) {
        return Promise.resolve(id);
    }

    _validate(data) {
        throw new Error("_validate(data) not implemented");
    }

    _getQuery(paging) {
        throw new Error("_getQuery(paging) not implemented");
    }

    _createIndexes() {
        return Promise.resolve(true);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: {},
            filter: {},
            select: []
        }, paging);
        // var start = process.hrtime();

        return this._createIndexes()
            .then((createIndexResults) => {
                var query = this._getQuery(_paging);
                return this.collection
                    .where(query)
                    .select(_paging.select)
                    .page(_paging.page, _paging.size)
                    .order(_paging.order)
                    .execute();
            });
    }

    _pre(data) {
        return this._createIndexes()
            .then((createIndexResults) => {
                return this._validate(data);
            });
    }

    create(data) {
        var now = new Date();

        return this._pre(data)
            .then((validData) => {
                return this._beforeInsert(validData);
            })
            .then((processedData) => {
                processedData._createdDate = now;

                return this.collection.insert(processedData);
            })
            .then((id) => {
                return this._afterInsert(id);
            });
    }

    update(data) {
        return this._pre(data)

            .then((validData) => {
                return this._beforeUpdate(validData);
            })
            .then((processedData) => {
                return this.collection.update(processedData);
            })
            .then((id) => {
                return this._afterUpdate(id);
            });
    }

    delete(data) {
        data._deleted = true;
        return this.collection.update(data);
    }

    destroy(id) {
        return this.collection.deleteOne({
                _id: ObjectId.isValid(id) ? new ObjectId(id) : {}
            })
            .then((result) => {
                return Promise.resolve(result.deletedCount === 1);
            });
    }

    getSingleById(id, fields) {
        var query = {
            _id: ObjectId.isValid(id) ? new ObjectId(id) : {},
            _deleted: false
        };
        return this.getSingleByQuery(query, fields);
    }

    getSingleByIdOrDefault(id, fields) {
        var query = {
            _id: ObjectId.isValid(id) ? new ObjectId(id) : {},
            _deleted: false
        };
        return this.getSingleByQueryOrDefault(query, fields);
    }

    getSingleByQuery(where, fields) {
        this.collection.select(fields);
        return this.collection.single(where);
    }

    getSingleByQueryOrDefault(where, fields) {
        this.collection.select(fields);
        return this.collection.singleOrDefault(where);
    }
};
<commit_msg>Update Delete Method<commit_after>"use strict";
// external deps
var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

module.exports = class BaseManager {
    constructor(db, user, locale) {
        this.db = db;
        this.user = user;
        this.locale = locale;

        this.collection = null;
    }

    _beforeInsert(data) {
        return Promise.resolve(data);
    }

    _afterInsert(id) {
        return Promise.resolve(id);
    }

    _beforeUpdate(data) {
        return Promise.resolve(data);
    }

    _afterUpdate(id) {
        return Promise.resolve(id);
    }

    _validate(data) {
        throw new Error("_validate(data) not implemented");
    }

    _getQuery(paging) {
        throw new Error("_getQuery(paging) not implemented");
    }

    _createIndexes() {
        return Promise.resolve(true);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: {},
            filter: {},
            select: []
        }, paging);
        // var start = process.hrtime();

        return this._createIndexes()
            .then((createIndexResults) => {
                var query = this._getQuery(_paging);
                return this.collection
                    .where(query)
                    .select(_paging.select)
                    .page(_paging.page, _paging.size)
                    .order(_paging.order)
                    .execute();
            });
    }

    _pre(data) {
        return this._createIndexes()
            .then((createIndexResults) => {
                return this._validate(data);
            });
    }

    create(data) {
        var now = new Date();

        return this._pre(data)
            .then((validData) => {
                return this._beforeInsert(validData);
            })
            .then((processedData) => {
                processedData._createdDate = now;

                return this.collection.insert(processedData);
            })
            .then((id) => {
                return this._afterInsert(id);
            });
    }

    update(data) {
        return this._pre(data)

            .then((validData) => {
                return this._beforeUpdate(validData);
            })
            .then((processedData) => {
                return this.collection.update(processedData);
            })
            .then((id) => {
                return this._afterUpdate(id);
            });
    }

    delete(data) {
        data._deleted = true;
        data._updatedDate = new Date();
        return this.collection.update(data);
    }

    destroy(id) {
        return this.collection.deleteOne({
                _id: ObjectId.isValid(id) ? new ObjectId(id) : {}
            })
            .then((result) => {
                return Promise.resolve(result.deletedCount === 1);
            });
    }

    getSingleById(id, fields) {
        var query = {
            _id: ObjectId.isValid(id) ? new ObjectId(id) : {},
            _deleted: false
        };
        return this.getSingleByQuery(query, fields);
    }

    getSingleByIdOrDefault(id, fields) {
        var query = {
            _id: ObjectId.isValid(id) ? new ObjectId(id) : {},
            _deleted: false
        };
        return this.getSingleByQueryOrDefault(query, fields);
    }

    getSingleByQuery(where, fields) {
        this.collection.select(fields);
        return this.collection.single(where);
    }

    getSingleByQueryOrDefault(where, fields) {
        this.collection.select(fields);
        return this.collection.singleOrDefault(where);
    }
};
<|endoftext|>


<commit_before>var asyncMap = require('slide').asyncMap
var drompii = require('./drompii.js')
var pjs = require('./paper-core.js')
var upload = require('./upload.js')
var through = require('through2')
var D = require('./dombii.js')
var path = require('path')
var fs = require('fs')

var r = require('./router.js')
var _ = require('underscore')

var LOGIN = fs.readFileSync(__dirname + '/login.hogan', 'utf8')
var ERROR = fs.readFileSync(__dirname + '/error.hogan', 'utf8')
var OMNI = fs.readFileSync(__dirname + '/omni.hogan', 'utf8')
var GRIFTER = fs.readFileSync(__dirname + '/grifter.hogan', 'utf8')

module.exports = function Omni (opts) {
  var frameList = null
  var frame = null
  var svg = null
  var blob
  var metaBlob
  var scale = 0.45

  function url () {
    return window.location.pathname.replace('/','')
  }

  var s = through.obj(IO)

  var db = r()
             .on('data', function (d) {  s.push(d) })

  if (!localStorage[opts.id]) {
    var dx = {x : 10, y : 10}
    localStorage[opts.id] = JSON.stringify({data:dx})
  } else
    var dx = JSON.parse(localStorage[opts.id]).data

  dx.showSettings = false
  dx.lib = _.values(opts.lib)
  dx.cvs = (window.location.pathname==='/@'||window.location.pathname==='/')
    ? 'home'
    : window.location.pathname.replace('/','')

  var editor = new D({
    template : GRIFTER,
    name : 'grifter',
    parent : document.body,
    drag : true,
    events : [
      ['.tags','keydown',editIN],
      ['.tags','keyup',editOUT],
      ['.grifter textarea', 'keyup', editOUT],
      ['.grifter textarea', 'keydown', editIN],
      ['.grifter .del', 'click', function (e) {
        cancel(e); s.push('-'+blob.cuid); editor.erase()
      }],
      ['.grifter .reset', 'click', function (e) {
        cancel(e); s.push('!'+blob.cuid); editor.erase()
      }]
    ]
  })

  var err = new D({
    name : 'error',
    template : ERROR,
    parent : document.body,
    events : [
      ['span','click', function (e) { e.preventDefault(); err.erase() } ]
    ]
  })

  var login = new D({
    name : 'login',
    id : opts.id,
    drag : true,
    template : LOGIN,
    parent : document.body,
    events : [['.login', 'submit', function (e) {
      e.preventDefault()
      s.push('+@edit '+e.target[0].value+'/'+opts.id)
      e.target[0].value = ''
    }]]
  })

  var omni = new D({
    name : 'omni',
    id : opts.id,
    drag : true,
    template : OMNI,
    parent : document.body,
    events : [
      ['.lib li','dragstart',dragModule],
      ['.settings .favicon','keyup',updateSettings],
      ['.settings .title','keyup',updateSettings],
      ['.settings .save','keyup',saveCanvas],
      ['.file','click',toggleSettings],
      ['.blackbox input','keyup',blackbox],
      ['.canvasName','keyup',saveCanvas],
      [window,'contextmenu', grifter],
      ['.exit','click', function (e) { cancel(e);s.push('-@edit/'+opts.id) }]
    ]
  })

  function toggleSettings (e) {
    cancel(e)
    var el = e.target
    if (!dx.showSettings) db.get('?$settings', function (e,d) {
      dx.showSettings = true
      dx.title = d.title
      dx.favicon = d.favicon
      omni.draw(dx)
      el.style.background = '#CBD4DD'
      blob = {
        cuid : 'settings',
        edit : { key : 'favicon' },
        data : d
      }
    })
    if (dx.showSettings) {
      dx.showSettings = false
      omni.draw(dx)
      el.style.background = 'transparent'
    }
  }

  function updateSettings (e) {
    if (e.keyCode === 13) {
      cancel(e)
      var type = e.target.className
      blob.data[type] = e.target.value
      if (type==='title' || type==='favicon')
        s.push({key:'+$settings',value:blob.data})
    }
  }

  function dragModule (e) {
    cmd = '+'+e.target.innerHTML.split('')[1]
    e.dataTransfer.setData('cmd',cmd)
  }
  document.addEventListener('drop', function (e) { // symbols ◼ ψ
    cancel(e)
    cmd = null
    if (e.dataTransfer.files.length > 0) {
      editor.erase()
      upload(e, blob, function (d) {
        if (d.cuid==='settings'&&dx.showSettings) {
          dx.favicon = d.data.favicon
          dx.title = d.data.title
          omni.draw(dx)
        }
        updateData()
      })
    } else cmd = e.dataTransfer.getData('cmd')
    if (cmd) s.push(cmd+'/'+opts.id)
    else return false
  },false)
  document.addEventListener('dragover', cancel, false)

  if (sessionStorage['edit']) // LOGIN
    s.push('+@edit '+sessionStorage['edit']+'/'+opts.id)

  window.addEventListener('keydown', function (e) { // KEYS
    if (e.keyCode === 13 && e.ctrlKey) {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault()
        if(!document.querySelector('.login')&&!document.querySelector('.omni')){
          login.draw(JSON.parse(localStorage[opts.id]).data)
          document.querySelector('.login input').focus()
        } else login.erase()
      }
    }
  })

  function pjsInit () {
    pjs.setup(document.querySelector('.bones'))

    var LtabBG = new pjs.Path([
      [0,0],
      [0,15],
      [130,15],
      [115,0]
    ])

    var LtabTXT = new pjs.PointText({
      point : [0,0],
      content : 'Pallette',
      fontFamily : 'Andale Mono',
      fontSize : 10,
      opacity : 0.75
    })

    var Ltab = new pjs.Group([LtabBG,LtabTXT])
    Ltab.children[1].position = tabCenter(Ltab)

    var Rtab = Ltab.clone()
    Rtab.children[0].segments = [
      [85,0],
      [70,15],
      [200,15],
      [200,0]
    ]
    Rtab.children[1].content = 'Skeleton'
    Rtab.children[1].position = tabCenter(Rtab)

    Rtab.onClick = function (e) {tablle(Rtab)}
    Ltab.onClick = function (e) {tablle(Ltab)}

    var skeleton

    var bbg = new pjs.Shape.Rectangle({
      point : [35, 45],
      size : [130, window.innerHeight*(130/window.innerWidth)]
    })
    bbg.sendToBack()

    function drawSkeleton () {
      var scaleX = 130/window.innerWidth
      // 15 = tabHeight

      if (skeleton) skeleton.remove()

      skeleton = new pjs.Group({
        position : [0.0]
      })

      var bg = new pjs.Shape.Rectangle({
        point : [35, 45],
        size : [130, window.innerHeight*scaleX],
        clipMask : true
     })

      window.s = skeleton

      var Xoff = window.innerWidth/bg.bounds.width
      var Yoff = window.innerHeight/bg.bounds.height

      var view = new pjs.Group({
        position : [0,0]
      })
      view.addChild(skeleton)
      view.addChild(bg)

      skeleton.visible = true
      _.each(frame, function (v,k) {

        var el = document.getElementById(k).firstChild

        // draw page witihin skeleton view
        // use shortest side to calc scale

        // single scale value use diag?

        var bounds = [
          (el.offsetTop*scaleX)+45,
          el.offsetLeft*scaleX+35,
          el.offsetHeight*scaleX,
          el.offsetWidth*scaleX
        ]

        // var m = new pjs.Shape.Circle({
        //   center : pos,
        //   radius : 3,
        //   fillColor : 'blue',
        //   strokeWidth : 0
        // })

        var r = new pjs.Shape.Rectangle({
          point : [bounds[1],bounds[0]],
          size : [bounds[3],bounds[2]],
          strokeColor : '#EBEEFB',
          fillColor : '#CBD5DF',
          strokeWidth : 1
        })

        window.r = r

        // skeleton.addChild(m)
        skeleton.addChild(r)
      })

      var sTop = skeleton.position.y

      window.onscroll = function (e) {
        var y = ((e.pageY*scaleX) * (-1)) + sTop
        skeleton.position.y = y
        console.log(y,sTop)
        pjs.view.draw()
      }

      pjs.view.draw()
    }

    function scrollSkeleton (e) {

    }

    window.s = skeleton
    window.pjs = pjs

    function tabCenter (group) {
      var segs = group.children[0].segments
      var x = ((segs[2].point.x - segs[1].point.x)/2) + segs[1].point.x
      var y = segs[1].point.y/2
      return [x,y]
    }

    function tablle (group) {
      var selected, unselected

      if (group.children[1].content === 'Skeleton') {
        selected = Rtab
        unselected = Ltab
        document.querySelector('.omni .lib').style.display = 'none'
        drawSkeleton()
      } else {
        selected = Ltab
        unselected = Rtab
        document.querySelector('.omni .lib').style.display = 'block'
        skeleton.visible = false
      }

      selected.children[0].fillColor = '#EBEEFB'
      selected.children[1].fillColor = 'black'
      unselected.children[0].fillColor = '#CBD5DF'
      unselected.children[1].fillColor = '#333'
      selected.bringToFront()
      pjs.view.draw()
    }

    tablle(Rtab)
  }

  var lastModified

  function IO (d, enc, next) {
    var self = this

    if (d.cmd && d.cmd[1]==='#') frame = d.value

    if (d.cmd && typeof d.cmd === 'string' && d.cmd.slice(0,2)==='!#')
      if (document.querySelector('.omni')) {
        dx.cvs = d.cmd.slice(2).split('/')[0]
        omni.draw(dx)
      }

    if (!lastModified && d.timestamp){lastModified = d.timestamp;saveCanvas()}
    if (d.timestamp && d.timestamp !== lastModified) saveCanvas()

    db.write(d)

    if (d.code === 1) { // ERROR
      next()

      if (!login.data)
        login.draw(JSON.parse(localStorage[opts.id]).data)

      err.draw({x : login.data.x+8, y : login.data.y + 36, msg : d.message})

      _.delay(err.erase,2200)

      return null
    } else if (!d.key) { next(); return null }

    var tkn = (d.key.split(':').length > 1)
      ? d.key.split(':')[1]
      : d.key

    if (tkn && tkn === opts.id) {
      if (d.key.split(':')[0] === '@edit') {
        sessionStorage['edit'] = d.value
        login.erase()
        omni.draw(dx, pjsInit)
        document.body.className = 'edit'
      } else if (d.value==='-edit') {
        omni.erase()
        grifter.erase()
        document.body.className=''
      }
    }

    next()
  }

  function saveCanvas (e) {
    var c
    if (e && e.keyCode === 13) {
      cancel(e)
      dx.cvs = e.target.value
      db.get('?#'+e.target.value, function (err, d) {
        if (err) {
          s.push('+#'+e.target.value+'/'+opts.id)
          openUrl.write('/'+e.target.value)
          e.target.blur()
        } else {
          openUrl.write('/'+e.target.value)
          e.target.blur()
        }
      })
    } else if (!e) {
      s.push('+#'+dx.cvs+'/'+opts.id)
    }
  }

  function blackbox (e) {
    var val = e.target.value
    if (e.keyCode === 13 || e.key === 'Enter') {
      e.preventDefault()
      e.target.value = ''
      s.push(val+'/'+opts.id)
    }
  }

  function grifter (e) {
    cancel(e)
    blob = {}
    metaBlob = {}

    editor.erase()

    var d = {
      x : e.clientX+window.pageXOffset,
      y : (e.clientY-20)+window.pageYOffset,
      props : []
    }

    if (e.target.className !== 'canvasName' || e.target.tagName !== 'HTML') {
      blob = drompii(e)

      if (!blob) return false

      if (typeof blob.edit.index === 'number') {
        for (p in blob.edit.value) {
          var prop = {key:p,value:blob.edit.value[p]}
          d.props.push(prop)
        }
      } else d.props.push(blob.edit)

      d.name = blob.name
      d.cuid = blob.cuid
      d.tags = metaBlob.tags

      db.get('?~'+blob.cuid, function (e, data) {
        console.log(e)
        console.log(data)
        if (!e) { metaBlob = data; d.tags = metaBlob.tags }
        editor.draw(d)
      })
    }
  }

  function editOUT (e) { // some intelligent feedback / filtering
    var cmd

    var key = e.target.parentElement.children[1].innerHTML
    var val = e.target.value.replace(/[\n\r]/g,'')

    if (e.keyCode === 13) {
      cancel(e)
      if (key === 'tags') {
        metaBlob.tags = val
        updateData(true)
        editor.erase()
      } else {
        if (typeof blob.edit.index === 'number') {
          blob.data[blob.edit.key][blob.edit.index][key] = val
        } else blob.data[key] = val
        updateData()
        editor.erase()
      }
    }
  }

  function editIN (e) { if (e.keyCode === 13) cancel(e) }

  function updateData (pip) {
    metaBlob.freshness = new Date().getTime()
    metaBlob.name = blob.name
    if (!pip) s.push({key:'+$'+blob.cuid+'/'+opts.id,value:blob.data})
    s.push({key:'+~'+blob.cuid+'/'+opts.id,value:metaBlob})
  }

  return s
}

function cancel (e) { e.preventDefault() }
<commit_msg>set default to pallette<commit_after>var asyncMap = require('slide').asyncMap
var drompii = require('./drompii.js')
var pjs = require('./paper-core.js')
var upload = require('./upload.js')
var through = require('through2')
var D = require('./dombii.js')
var path = require('path')
var fs = require('fs')

var r = require('./router.js')
var _ = require('underscore')

var LOGIN = fs.readFileSync(__dirname + '/login.hogan', 'utf8')
var ERROR = fs.readFileSync(__dirname + '/error.hogan', 'utf8')
var OMNI = fs.readFileSync(__dirname + '/omni.hogan', 'utf8')
var GRIFTER = fs.readFileSync(__dirname + '/grifter.hogan', 'utf8')

module.exports = function Omni (opts) {
  var frameList = null
  var frame = null
  var svg = null
  var blob
  var metaBlob
  var scale = 0.45

  function url () {
    return window.location.pathname.replace('/','')
  }

  var s = through.obj(IO)

  var db = r()
             .on('data', function (d) {  s.push(d) })

  if (!localStorage[opts.id]) {
    var dx = {x : 10, y : 10}
    localStorage[opts.id] = JSON.stringify({data:dx})
  } else
    var dx = JSON.parse(localStorage[opts.id]).data

  dx.showSettings = false
  dx.lib = _.values(opts.lib)
  dx.cvs = (window.location.pathname==='/@'||window.location.pathname==='/')
    ? 'home'
    : window.location.pathname.replace('/','')

  var editor = new D({
    template : GRIFTER,
    name : 'grifter',
    parent : document.body,
    drag : true,
    events : [
      ['.tags','keydown',editIN],
      ['.tags','keyup',editOUT],
      ['.grifter textarea', 'keyup', editOUT],
      ['.grifter textarea', 'keydown', editIN],
      ['.grifter .del', 'click', function (e) {
        cancel(e); s.push('-'+blob.cuid); editor.erase()
      }],
      ['.grifter .reset', 'click', function (e) {
        cancel(e); s.push('!'+blob.cuid); editor.erase()
      }]
    ]
  })

  var err = new D({
    name : 'error',
    template : ERROR,
    parent : document.body,
    events : [
      ['span','click', function (e) { e.preventDefault(); err.erase() } ]
    ]
  })

  var login = new D({
    name : 'login',
    id : opts.id,
    drag : true,
    template : LOGIN,
    parent : document.body,
    events : [['.login', 'submit', function (e) {
      e.preventDefault()
      s.push('+@edit '+e.target[0].value+'/'+opts.id)
      e.target[0].value = ''
    }]]
  })

  var omni = new D({
    name : 'omni',
    id : opts.id,
    drag : true,
    template : OMNI,
    parent : document.body,
    events : [
      ['.lib li','dragstart',dragModule],
      ['.settings .favicon','keyup',updateSettings],
      ['.settings .title','keyup',updateSettings],
      ['.settings .save','keyup',saveCanvas],
      ['.file','click',toggleSettings],
      ['.blackbox input','keyup',blackbox],
      ['.canvasName','keyup',saveCanvas],
      [window,'contextmenu', grifter],
      ['.exit','click', function (e) { cancel(e);s.push('-@edit/'+opts.id) }]
    ]
  })

  function toggleSettings (e) {
    cancel(e)
    var el = e.target
    if (!dx.showSettings) db.get('?$settings', function (e,d) {
      dx.showSettings = true
      dx.title = d.title
      dx.favicon = d.favicon
      omni.draw(dx)
      el.style.background = '#CBD4DD'
      blob = {
        cuid : 'settings',
        edit : { key : 'favicon' },
        data : d
      }
    })
    if (dx.showSettings) {
      dx.showSettings = false
      omni.draw(dx)
      el.style.background = 'transparent'
    }
  }

  function updateSettings (e) {
    if (e.keyCode === 13) {
      cancel(e)
      var type = e.target.className
      blob.data[type] = e.target.value
      if (type==='title' || type==='favicon')
        s.push({key:'+$settings',value:blob.data})
    }
  }

  function dragModule (e) {
    cmd = '+'+e.target.innerHTML.split('')[1]
    e.dataTransfer.setData('cmd',cmd)
  }
  document.addEventListener('drop', function (e) { // symbols ◼ ψ
    cancel(e)
    cmd = null
    if (e.dataTransfer.files.length > 0) {
      editor.erase()
      upload(e, blob, function (d) {
        if (d.cuid==='settings'&&dx.showSettings) {
          dx.favicon = d.data.favicon
          dx.title = d.data.title
          omni.draw(dx)
        }
        updateData()
      })
    } else cmd = e.dataTransfer.getData('cmd')
    if (cmd) s.push(cmd+'/'+opts.id)
    else return false
  },false)
  document.addEventListener('dragover', cancel, false)

  if (sessionStorage['edit']) // LOGIN
    s.push('+@edit '+sessionStorage['edit']+'/'+opts.id)

  window.addEventListener('keydown', function (e) { // KEYS
    if (e.keyCode === 13 && e.ctrlKey) {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault()
        if(!document.querySelector('.login')&&!document.querySelector('.omni')){
          login.draw(JSON.parse(localStorage[opts.id]).data)
          document.querySelector('.login input').focus()
        } else login.erase()
      }
    }
  })

  function pjsInit () {
    pjs.setup(document.querySelector('.bones'))

    var LtabBG = new pjs.Path([
      [0,0],
      [0,15],
      [130,15],
      [115,0]
    ])

    var LtabTXT = new pjs.PointText({
      point : [0,0],
      content : 'Pallette',
      fontFamily : 'Andale Mono',
      fontSize : 10,
      opacity : 0.75
    })

    var Ltab = new pjs.Group([LtabBG,LtabTXT])
    Ltab.children[1].position = tabCenter(Ltab)

    var Rtab = Ltab.clone()
    Rtab.children[0].segments = [
      [85,0],
      [70,15],
      [200,15],
      [200,0]
    ]
    Rtab.children[1].content = 'Skeleton'
    Rtab.children[1].position = tabCenter(Rtab)

    Rtab.onClick = function (e) {tablle(Rtab)}
    Ltab.onClick = function (e) {tablle(Ltab)}

    var skeleton

    var bbg = new pjs.Shape.Rectangle({
      point : [35, 45],
      size : [130, window.innerHeight*(130/window.innerWidth)]
    })
    bbg.sendToBack()

    function drawSkeleton () {
      var scaleX = 130/window.innerWidth

      if (skeleton) skeleton.remove()

      skeleton = new pjs.Group({
        position : [0.0]
      })

      var bg = new pjs.Shape.Rectangle({
        point : [35, 45],
        size : [130, window.innerHeight*scaleX],
        clipMask : true
     })

      var Xoff = window.innerWidth/bg.bounds.width
      var Yoff = window.innerHeight/bg.bounds.height

      var view = new pjs.Group({
        position : [0,0]
      })
      view.addChild(skeleton)
      view.addChild(bg)

      skeleton.visible = true
      _.each(frame, function (v,k) {

        var el = document.getElementById(k).firstChild

        var bounds = [
          (el.offsetTop*scaleX)+45,
          el.offsetLeft*scaleX+35,
          el.offsetHeight*scaleX,
          el.offsetWidth*scaleX
        ]

        var r = new pjs.Shape.Rectangle({
          point : [bounds[1],bounds[0]],
          size : [bounds[3],bounds[2]],
          strokeColor : '#EBEEFB',
          fillColor : '#CBD5DF',
          strokeWidth : 1
        })

        skeleton.addChild(r)
      })

      var sTop = skeleton.position.y

      window.onscroll = function (e) {
        var y = ((e.pageY*scaleX) * (-1)) + sTop
        skeleton.position.y = y
        console.log(y,sTop)
        pjs.view.draw()
      }

      pjs.view.draw()
    }

    window.s = skeleton
    window.pjs = pjs

    function tabCenter (group) {
      var segs = group.children[0].segments
      var x = ((segs[2].point.x - segs[1].point.x)/2) + segs[1].point.x
      var y = segs[1].point.y/2
      return [x,y]
    }

    function tablle (group) {
      var selected, unselected

      if (group.children[1].content === 'Skeleton') {
        selected = Rtab
        unselected = Ltab
        document.querySelector('.omni .lib').style.display = 'none'
        drawSkeleton()
      } else {
        selected = Ltab
        unselected = Rtab
        document.querySelector('.omni .lib').style.display = 'block'
        skeleton.visible = false
      }

      selected.children[0].fillColor = '#EBEEFB'
      selected.children[1].fillColor = 'black'
      unselected.children[0].fillColor = '#CBD5DF'
      unselected.children[1].fillColor = '#333'
      selected.bringToFront()
      pjs.view.draw()
    }

    tablle(Ltab)
  }

  var lastModified

  function IO (d, enc, next) {
    var self = this

    if (d.cmd && d.cmd[1]==='#') frame = d.value

    if (d.cmd && typeof d.cmd === 'string' && d.cmd.slice(0,2)==='!#')
      if (document.querySelector('.omni')) {
        dx.cvs = d.cmd.slice(2).split('/')[0]
        omni.draw(dx)
      }

    if (!lastModified && d.timestamp){lastModified = d.timestamp;saveCanvas()}
    if (d.timestamp && d.timestamp !== lastModified) saveCanvas()

    db.write(d)

    if (d.code === 1) { // ERROR
      next()

      if (!login.data)
        login.draw(JSON.parse(localStorage[opts.id]).data)

      err.draw({x : login.data.x+8, y : login.data.y + 36, msg : d.message})

      _.delay(err.erase,2200)

      return null
    } else if (!d.key) { next(); return null }

    var tkn = (d.key.split(':').length > 1)
      ? d.key.split(':')[1]
      : d.key

    if (tkn && tkn === opts.id) {
      if (d.key.split(':')[0] === '@edit') {
        sessionStorage['edit'] = d.value
        login.erase()
        omni.draw(dx, pjsInit)
        document.body.className = 'edit'
      } else if (d.value==='-edit') {
        omni.erase()
        grifter.erase()
        document.body.className=''
      }
    }

    next()
  }

  function saveCanvas (e) {
    var c
    if (e && e.keyCode === 13) {
      cancel(e)
      dx.cvs = e.target.value
      db.get('?#'+e.target.value, function (err, d) {
        if (err) {
          s.push('+#'+e.target.value+'/'+opts.id)
          openUrl.write('/'+e.target.value)
          e.target.blur()
        } else {
          openUrl.write('/'+e.target.value)
          e.target.blur()
        }
      })
    } else if (!e) {
      s.push('+#'+dx.cvs+'/'+opts.id)
    }
  }

  function blackbox (e) {
    var val = e.target.value
    if (e.keyCode === 13 || e.key === 'Enter') {
      e.preventDefault()
      e.target.value = ''
      s.push(val+'/'+opts.id)
    }
  }

  function grifter (e) {
    cancel(e)
    blob = {}
    metaBlob = {}

    editor.erase()

    var d = {
      x : e.clientX+window.pageXOffset,
      y : (e.clientY-20)+window.pageYOffset,
      props : []
    }

    if (e.target.className !== 'canvasName' || e.target.tagName !== 'HTML') {
      blob = drompii(e)

      if (!blob) return false

      if (typeof blob.edit.index === 'number') {
        for (p in blob.edit.value) {
          var prop = {key:p,value:blob.edit.value[p]}
          d.props.push(prop)
        }
      } else d.props.push(blob.edit)

      d.name = blob.name
      d.cuid = blob.cuid
      d.tags = metaBlob.tags

      db.get('?~'+blob.cuid, function (e, data) {
        console.log(e)
        console.log(data)
        if (!e) { metaBlob = data; d.tags = metaBlob.tags }
        editor.draw(d)
      })
    }
  }

  function editOUT (e) { // some intelligent feedback / filtering
    var cmd

    var key = e.target.parentElement.children[1].innerHTML
    var val = e.target.value.replace(/[\n\r]/g,'')

    if (e.keyCode === 13) {
      cancel(e)
      if (key === 'tags') {
        metaBlob.tags = val
        updateData(true)
        editor.erase()
      } else {
        if (typeof blob.edit.index === 'number') {
          blob.data[blob.edit.key][blob.edit.index][key] = val
        } else blob.data[key] = val
        updateData()
        editor.erase()
      }
    }
  }

  function editIN (e) { if (e.keyCode === 13) cancel(e) }

  function updateData (pip) {
    metaBlob.freshness = new Date().getTime()
    metaBlob.name = blob.name
    if (!pip) s.push({key:'+$'+blob.cuid+'/'+opts.id,value:blob.data})
    s.push({key:'+~'+blob.cuid+'/'+opts.id,value:metaBlob})
  }

  return s
}

function cancel (e) { e.preventDefault() }
<|endoftext|>


<commit_before>var _      = require('underscore')
var async  = require('async')
var op     = require('object-path')
var router = require('express').Router()

var entu   = require('../helpers/entu')

router.get('/requests', function(req, res) {
    var today = new Date();
    var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);

    async.waterfall([
        function(callback) {
            entu.dbConnection('entu', callback)
        },
        function(connection, callback) {
            connection.collection('request').aggregate([
            	{
            		'$match' : {
                		date: {
                    		$gt: lastWeek
                		}
            		}
            	},
            	{
            		'$group' : {
            			_id: {
                            host: '$host',
                            month: { $month: '$date' },
                            day: { $dayOfMonth: '$date' },
                            year: { $year: '$date' }
                        },
            			count: {
            				$sum: 1
            			}
            		}
            	}
            ]).toArray(callback)
        },
        function(result, callback) {
            var seriesData = {}
            var seriesSum = {}

            for (var i in result) {
                if(!result.hasOwnProperty(i)) { continue }

                var host = op.get(result[i], '_id.host')
                var day = '00' + op.get(result[i], '_id.day')
                var day = day.substr(day.length - 2)
                var month = '00' + op.get(result[i], '_id.month')
                var month = month.substr(month.length - 2)
                var year = op.get(result[i], '_id.year')

                var date = [year, month, day].join('-')
                var count = op.get(result[i], 'count')

                op.set(seriesData, [host, 'sum'], op.get(seriesData, [host, 'sum'], 0) + count)
                op.set(seriesData, [host, 'name'], host)
                op.push(seriesData, [host, 'data'], [date, count])
                op.set(seriesData, [host, 'incomplete_from'], today.toISOString().substr(0, 10))

            }
            var graphData = {
                x_axis: {
                    type: 'datetime'
                },
                series: _.sortBy(_.values(seriesData), 'sum').slice(0, 5)
            }

            callback(null, graphData)
        },
    ], function(err, result) {
        if(err) {
            res.send({
                error: err,
                version: APP_VERSION,
                started: APP_STARTED
            })
        } else {
            res.send(result)
        }
    })
})

router.get('/test', function() {
    throw new Error('böö')
})

module.exports = router
<commit_msg>Use Limit and Days query parameters<commit_after>var _      = require('underscore')
var async  = require('async')
var op     = require('object-path')
var router = require('express').Router()

var entu   = require('../helpers/entu')

router.get('/requests', function(req, res) {
    var limit = req.query.limit || 5
    var days = req.query.days || 7

    var today = new Date();
    var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - days);

    async.waterfall([
        function(callback) {
            entu.dbConnection('entu', callback)
        },
        function(connection, callback) {
            connection.collection('request').aggregate([
            	{
            		'$match' : {
                		date: {
                    		$gt: lastWeek
                		}
            		}
            	},
            	{
            		'$group' : {
            			_id: {
                            host: '$host',
                            month: { $month: '$date' },
                            day: { $dayOfMonth: '$date' },
                            year: { $year: '$date' }
                        },
            			count: {
            				$sum: 1
            			}
            		}
            	}
            ]).toArray(callback)
        },
        function(result, callback) {
            var seriesData = {}
            var seriesSum = {}

            for (var i in result) {
                if(!result.hasOwnProperty(i)) { continue }

                var host = op.get(result[i], '_id.host')
                var day = '00' + op.get(result[i], '_id.day')
                var day = day.substr(day.length - 2)
                var month = '00' + op.get(result[i], '_id.month')
                var month = month.substr(month.length - 2)
                var year = op.get(result[i], '_id.year')

                var date = [year, month, day].join('-')
                var count = op.get(result[i], 'count')

                op.set(seriesData, [host, 'sum'], op.get(seriesData, [host, 'sum'], 0) + count)
                op.set(seriesData, [host, 'name'], host)
                op.push(seriesData, [host, 'data'], [date, count])
                op.set(seriesData, [host, 'incomplete_from'], today.toISOString().substr(0, 10))

            }
            var graphData = {
                x_axis: {
                    type: 'datetime'
                },
                series: _.sortBy(_.values(seriesData), 'sum').slice(0, limit)
            }

            callback(null, graphData)
        },
    ], function(err, result) {
        if(err) {
            res.send({
                error: err,
                version: APP_VERSION,
                started: APP_STARTED
            })
        } else {
            res.send(result)
        }
    })
})

router.get('/test', function() {
    throw new Error('böö')
})

module.exports = router
<|endoftext|>


<commit_before>'use strict';

var assert = require('chai').assert;
var sinon = require('sinon');
var path = require('path');
var fixture = path.resolve.bind(path, __dirname, 'fixtures');

sinon.assert.expose(assert, { prefix: '' });

var expand = require('..');

describe('expand', function(){

    describe('constructor', function(){
        it('should provide a DEFAULTS object', function(){
            assert.isObject(expand.DEFAULTS);
        });
    });
});<commit_msg>fix test<commit_after>'use strict';

var assert = require('chai').assert;
var sinon = require('sinon');
var path = require('path');
var fixture = path.resolve.bind(path, __dirname, 'fixtures');

sinon.assert.expose(assert, { prefix: '' });

var solve = require('..');

describe('solve', function(){

    describe('constructor', function(){
        it('should provide a DEFAULTS object', function(){
            assert.isObject(solve.DEFAULTS);
        });
    });
});
<|endoftext|>


<commit_before>var asyncMap = require('slide').asyncMap
var drompii = require('./drompii.js')
var upload = require('./upload.js')
var through = require('through2')
var D = require('./dombii.js')
var path = require('path')
var fs = require('fs')

var r = require('./router.js')
var _ = require('underscore')

var LOGIN = fs.readFileSync(__dirname + '/login.hogan', 'utf8')
var ERROR = fs.readFileSync(__dirname + '/error.hogan', 'utf8')
var OMNI = fs.readFileSync(__dirname + '/omni.hogan', 'utf8')
var GRIFTER = fs.readFileSync(__dirname + '/grifter.hogan', 'utf8')

module.exports = function Omni (opts) {
  var frameList = null
  var frame = null
  var svg = null
  var blob = {}
  var scale = 0.45
  function url () { return window.location.pathname.replace('/','') }

  var s = through.obj(IO)

  var db = r()
             .on('data', function (d) {  s.push(d) })

  if (!localStorage[opts.id]) {
    var dx = {x:10,y:10}
    localStorage[opts.id] = JSON.stringify({data:dx})
  } else
    var dx = JSON.parse(localStorage[opts.id]).data

  dx.lib = _.values(opts.lib)
  dx.cvs = (window.location.pathname==='/@'||window.location.pathname==='/')
    ? 'home'
    : window.location.pathname.replace('/','')

  var editor = new D({
    template : GRIFTER,
    parent : document.body,
    drag : true,
    events : [
      ['.grifter textarea', 'keyup', editOUT],
      ['.grifter textarea', 'keydown', editIN],
      ['.grifter .rm', 'click', function (e) {
        cancel(e); s.push('-'+blob.cuid); editor.erase()
      }],
      ['.grifter .reup', 'click', function (e) {
        cancel(e); s.push('!'+blob.cuid); editor.erase()
      }]
    ]
  })

  var err = new D({
    name : 'error',
    template : ERROR,
    parent : document.body,
    events : [
      ['span','click',function (e){e.preventDefault();err.erase()}]
    ]
  })

  var login = new D({
    name : 'login',
    id : opts.id,
    drag : true,
    template : LOGIN,
    parent : document.body,
    events : [['.login', 'submit', function (e) {
      e.preventDefault()
      s.push('+@edit '+e.target[0].value+'/'+opts.id)
      e.target[0].value = ''
    }]]
  })

  var omni = new D({
    name : 'omni',
    id : opts.id,
    drag : true,
    template : OMNI,
    parent : document.body,
    events : [
      ['.lib li','dragstart',dragModule],
      ['.blackbox input','keyup',blackbox],
      ['.canvasName','keyup',saveCanvas],
      [window,'contextmenu', grifter],
      ['.exit','click', function (e) { cancel(e);s.push('-@edit/'+opts.id) }]
    ]
  })

  // MODULE DRAG+DROP
  function dragModule (e) {
    cmd = '+'+e.target.innerHTML.split('')[1]
    e.dataTransfer.setData('cmd',cmd)
  }
  document.addEventListener('drop', function (e) { // symbols ◼ ψ
    cancel(e)
    cmd = null
    if (e.dataTransfer.files.length > 0) {
      editor.erase()
      upload(e, blob, function (d) {
        _.delay(function () { s.push({key : '+$'+d.cuid+'/'+opts.id, value:d.data})},200)
      })
    } else cmd = e.dataTransfer.getData('cmd')
    if (cmd) s.push(cmd+'/'+opts.id)
    else return false
  },false)
  document.addEventListener('dragover', cancel, false)

  // LOGIN
  if (sessionStorage['edit'])
    s.push('+@edit '+sessionStorage['edit']+'/'+opts.id)

  // GLOBAL KEY SHORTCUTS
  window.addEventListener('keydown', function (e) {
    if (e.keyCode === 13 && e.ctrlKey) {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault()
        if(!document.querySelector('.login')&&!document.querySelector('.omni')){
          login.draw(JSON.parse(localStorage[opts.id]).data)
          document.querySelector('.login input').focus()
        } else login.erase()
      }
    }
  })

  // EVENTS
  var lastModified
  function IO (d, enc, next) {  // USE MUXDEMUX HERE TOO!
    var self = this

    console.log(d)

    if (d.timestamp) console.log(d.timestamp)

    if (!lastModified && d.timestamp){ lastModified = d.timestamp; saveCanvas() }
    if (d.timestamp && d.timestamp !== lastModified) saveCanvas()

    db.write(d)

    if (d.code === 1) { // ERROR
      next()
      if (!login.data) login.draw(JSON.parse(localStorage[opts.id]).data)
      err.draw({x : login.data.x+8, y : login.data.y + 36, msg : d.message})
      _.delay(err.erase,2200)
      return null
    } else if (!d.key) { next(); return null }

    var tkn = (d.key.split(':').length > 1)
      ? d.key.split(':')[1]
      : d.key

    if (tkn && tkn === opts.id) { // smart routing or filtering carbuncle needed
      if (d.key.split(':')[0] === '@edit') { // LOGIN
        sessionStorage['edit'] = d.value
        login.erase()
        omni.draw(dx)
      } else if (d.value === '-edit') omni.erase() // LOGOUT
    }

    next()
  }

  function saveCanvas (e) {
    var c
    if (e && e.keyCode === 13) { // try to grab data first!
      cancel(e)
      dx.cvs = e.target.value
      db.get('?#'+e.target.value, function (d) {
        if (d instanceof Error) {
          s.push('+#'+e.target.value+'/'+opts.id)
          ps(e.target.value)
          e.target.blur()
        } else {
          s.push('!#'+e.target.value+'/'+opts.id)
          ps(e.target.value)
          e.target.blur()
        }
      })
    } else if (!e) {
      console.log('saving '+dx.cvs)
      s.push('+#'+dx.cvs+'/'+opts.id)
    }
  }

  function blackbox (e) {
    var val = e.target.value
    if (e.keyCode === 13 || e.key === 'Enter') {
      e.preventDefault()
      e.target.value = ''
      s.push(val+'/'+opts.id)
    }
  }

  function grifter (e) {
    cancel(e)
    blob = {}

    editor.erase()

    var d = {
      x : e.clientX+window.pageXOffset,
      y : (e.clientY-20)+window.pageYOffset,
      props : []
    }

    if (e.target.className === 'canvasName') {
      d.props.push({key : '+copy', value : ''})
      editor.draw(d)
      return false
    } else if (e.target.tagName === 'HTML') {
      db.get('?$settings', function (d) { // use this to pull canvas!
        d.props = []
        d.type = 'canvas'
        d.props.push({key:'icon',value:'/files/1x1.png'})
        editor.draw(d)
      })
    } else {
      blob = drompii(e)

      if (!blob) return false

      console.log(blob)

      if (typeof blob.edit.index === 'number') {
        _.each(blob.edit.value,function (v,k) {
          console.log(v,k)
          var prop = {key:k,value:v}
          d.props.push(prop)
        })
      } else d.props.push(blob.edit)

      d.name = blob.name
      d.cuid = blob.cuid
      d.rm = true
      d.reup = true
    }

    editor.draw(d)
  }

  function editOUT (e) { // some intelligent feedback / filtering
    var cmd

    var key = e.target.parentElement.children[1].innerHTML
    var val = e.target.value.replace(/[\n\r]/g,'')

    if (e.keyCode === 13) {
      if (key==='+copy') {
        var c = window.location.pathname.replace('/','')
        s.push('&#'+c+' '+val)
        editor.erase()
      } else {
        // look at blob.edit
        blob.data[key] = val
        s.push({key : '+$'+blob.cuid+'/'+opts.id, value:blob.data})
        editor.erase()
      }
    }

    // break a function out to correctly modify the origin data

    function moldigar (toMash) {
      // receive origin + new in an object and return the mashed version
      // toMash.orig
      // toMash.nu

      return mashed
    }

  }
  function editIN (e) { if (e.keyCode === 13) cancel(e) }

  function ps (link) {
    dx.cvs = link
    if (link==='home') link = '/'
    history.pushState({'cmd':'!#'+dx.cvs},'',link)
  }

  return s
}

function cancel (e) { e.preventDefault() }
<commit_msg>name grifter template<commit_after>var asyncMap = require('slide').asyncMap
var drompii = require('./drompii.js')
var upload = require('./upload.js')
var through = require('through2')
var D = require('./dombii.js')
var path = require('path')
var fs = require('fs')

var r = require('./router.js')
var _ = require('underscore')

var LOGIN = fs.readFileSync(__dirname + '/login.hogan', 'utf8')
var ERROR = fs.readFileSync(__dirname + '/error.hogan', 'utf8')
var OMNI = fs.readFileSync(__dirname + '/omni.hogan', 'utf8')
var GRIFTER = fs.readFileSync(__dirname + '/grifter.hogan', 'utf8')

module.exports = function Omni (opts) {
  var frameList = null
  var frame = null
  var svg = null
  var blob = {}
  var scale = 0.45
  function url () { return window.location.pathname.replace('/','') }

  var s = through.obj(IO)

  var db = r()
             .on('data', function (d) {  s.push(d) })

  if (!localStorage[opts.id]) {
    var dx = {x:10,y:10}
    localStorage[opts.id] = JSON.stringify({data:dx})
  } else
    var dx = JSON.parse(localStorage[opts.id]).data

  dx.lib = _.values(opts.lib)
  dx.cvs = (window.location.pathname==='/@'||window.location.pathname==='/')
    ? 'home'
    : window.location.pathname.replace('/','')

  var editor = new D({
    template : GRIFTER,
    name : 'grifter',
    parent : document.body,
    drag : true,
    events : [
      ['.grifter textarea', 'keyup', editOUT],
      ['.grifter textarea', 'keydown', editIN],
      ['.grifter .rm', 'click', function (e) {
        cancel(e); s.push('-'+blob.cuid); editor.erase()
      }],
      ['.grifter .reup', 'click', function (e) {
        cancel(e); s.push('!'+blob.cuid); editor.erase()
      }]
    ]
  })

  var err = new D({
    name : 'error',
    template : ERROR,
    parent : document.body,
    events : [
      ['span','click',function (e){e.preventDefault();err.erase()}]
    ]
  })

  var login = new D({
    name : 'login',
    id : opts.id,
    drag : true,
    template : LOGIN,
    parent : document.body,
    events : [['.login', 'submit', function (e) {
      e.preventDefault()
      s.push('+@edit '+e.target[0].value+'/'+opts.id)
      e.target[0].value = ''
    }]]
  })

  var omni = new D({
    name : 'omni',
    id : opts.id,
    drag : true,
    template : OMNI,
    parent : document.body,
    events : [
      ['.lib li','dragstart',dragModule],
      ['.blackbox input','keyup',blackbox],
      ['.canvasName','keyup',saveCanvas],
      [window,'contextmenu', grifter],
      ['.exit','click', function (e) { cancel(e);s.push('-@edit/'+opts.id) }]
    ]
  })

  // MODULE DRAG+DROP
  function dragModule (e) {
    cmd = '+'+e.target.innerHTML.split('')[1]
    e.dataTransfer.setData('cmd',cmd)
  }
  document.addEventListener('drop', function (e) { // symbols ◼ ψ
    cancel(e)
    cmd = null
    if (e.dataTransfer.files.length > 0) {
      editor.erase()
      upload(e, blob, function (d) {
         _.delay(function () { s.push({key : '+$'+d.cuid+'/'+opts.id, value:d.data})},200)
      })
    } else cmd = e.dataTransfer.getData('cmd')
    if (cmd) s.push(cmd+'/'+opts.id)
    else return false
  },false)
  document.addEventListener('dragover', cancel, false)

  // LOGIN
  if (sessionStorage['edit'])
    s.push('+@edit '+sessionStorage['edit']+'/'+opts.id)

  // GLOBAL KEY SHORTCUTS
  window.addEventListener('keydown', function (e) {
    if (e.keyCode === 13 && e.ctrlKey) {
      if (e.ctrlKey || e.metaKey) {
        e.preventDefault()
        if(!document.querySelector('.login')&&!document.querySelector('.omni')){
          login.draw(JSON.parse(localStorage[opts.id]).data)
          document.querySelector('.login input').focus()
        } else login.erase()
      }
    }
  })

  // EVENTS
  var lastModified
  function IO (d, enc, next) {  // USE MUXDEMUX HERE TOO!
    var self = this

    console.log(d)

    if (d.timestamp) console.log(d.timestamp)

    if (!lastModified && d.timestamp){ lastModified = d.timestamp; saveCanvas() }
    if (d.timestamp && d.timestamp !== lastModified) saveCanvas()

    db.write(d)

    if (d.code === 1) { // ERROR
      next()
      if (!login.data) login.draw(JSON.parse(localStorage[opts.id]).data)
      err.draw({x : login.data.x+8, y : login.data.y + 36, msg : d.message})
      _.delay(err.erase,2200)
      return null
    } else if (!d.key) { next(); return null }

    var tkn = (d.key.split(':').length > 1)
      ? d.key.split(':')[1]
      : d.key

    if (tkn && tkn === opts.id) { // smart routing or filtering carbuncle needed
      if (d.key.split(':')[0] === '@edit') { // LOGIN
        sessionStorage['edit'] = d.value
        login.erase()
        omni.draw(dx)
      } else if (d.value === '-edit') omni.erase() // LOGOUT
    }

    next()
  }

  function saveCanvas (e) {
    var c
    if (e && e.keyCode === 13) { // try to grab data first!
      cancel(e)
      dx.cvs = e.target.value
      db.get('?#'+e.target.value, function (d) {
        if (d instanceof Error) {
          s.push('+#'+e.target.value+'/'+opts.id)
          ps(e.target.value)
          e.target.blur()
        } else {
          s.push('!#'+e.target.value+'/'+opts.id)
          ps(e.target.value)
          e.target.blur()
        }
      })
    } else if (!e) {
      console.log('saving '+dx.cvs)
      s.push('+#'+dx.cvs+'/'+opts.id)
    }
  }

  function blackbox (e) {
    var val = e.target.value
    if (e.keyCode === 13 || e.key === 'Enter') {
      e.preventDefault()
      e.target.value = ''
      s.push(val+'/'+opts.id)
    }
  }

  function grifter (e) {
    cancel(e)
    blob = {}

    editor.erase()

    var d = {
      x : e.clientX+window.pageXOffset,
      y : (e.clientY-20)+window.pageYOffset,
      props : []
    }

    if (e.target.className === 'canvasName') {
      d.props.push({key : '+copy', value : ''})
      editor.draw(d)
      return false
    } else if (e.target.tagName === 'HTML') {
      db.get('?$settings', function (d) { // use this to pull canvas!
        d.props = []
        d.type = 'canvas'
        d.props.push({key:'icon',value:'/files/1x1.png'})
        editor.draw(d)
      })
    } else {
      blob = drompii(e)

      if (!blob) return false

      if (typeof blob.edit.index === 'number') {
        for (p in blob.edit.value) {
          var prop = {key:p,value:blob.edit.value[p]}
          d.props.push(prop)
        }
      } else d.props.push(blob.edit)

      d.name = blob.name
      d.cuid = blob.cuid
      d.rm = true
      d.reup = true
    }

    editor.draw(d)
  }

  function editOUT (e) { // some intelligent feedback / filtering
    var cmd

    var key = e.target.parentElement.children[1].innerHTML
    var val = e.target.value.replace(/[\n\r]/g,'')

    if (e.keyCode === 13) {
      if (key==='+copy') {
        var c = window.location.pathname.replace('/','')
        s.push('&#'+c+' '+val)
        editor.erase()
      } else {
        // look at blob.edit
        if (typeof blob.edit.index === 'number') {
          blob.data[blob.edit.key][blob.edit.index][key] = val
        } else blob.data[key] = val
        s.push({key : '+$'+blob.cuid+'/'+opts.id, value:blob.data})
        editor.erase()
      }
    }

    // break a function out to correctly modify the origin data

    function moldigar (toMash) {
      // receive origin + new in an object and return the mashed version
      // toMash.orig
      // toMash.nu

      return mashed
    }

  }
  function editIN (e) { if (e.keyCode === 13) cancel(e) }

  function ps (link) {
    dx.cvs = link
    if (link==='home') link = '/'
    history.pushState({'cmd':'!#'+dx.cvs},'',link)
  }

  return s
}

function cancel (e) { e.preventDefault() }
<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const Log = require('../controls/judgelog');

const submitPath = path.join(process.cwd(), 'data', 'submit', 'logs');

router.post('/', (req, res, next) => {
	if (!req.user) {
		let err = new Error('You have to login first');
		err.code = 403;
		return next(err);
	}
	let q = req.body;
	if (!q.problem || !q.ext || !q.content) {
		return next(new Error('Invalid request'));
	}
	// Clean logs before writing
	Log.setLog(req.user.username, q.problem, q.ext, {
		created: new Date(),
		content: {
			verdict: '',
			details: []
		}
	});
	fs.writeFile(path.join(submitPath, `0[${req.user.username}][${q.problem}]${q.ext}`), q.content, err => {
		if (err) return next(err);
		res.json(true);
	});
});

module.exports = router;
<commit_msg>Properly uploads the file<commit_after>const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const Log = require('../controls/judgelog');

const submitPath = path.join(process.cwd(), 'data', 'submit');

router.post('/', (req, res, next) => {
	if (!req.user) {
		let err = new Error('You have to login first');
		err.code = 403;
		return next(err);
	}
	let q = req.body;
	if (!q.problem || !q.ext || !q.content) {
		return next(new Error('Invalid request'));
	}
	// Clean logs before writing
	Log.setLog(req.user.username, q.problem, q.ext, {
		created: new Date(),
		content: {
			verdict: '',
			details: []
		}
	});
	fs.writeFile(path.join(submitPath, `0[${req.user.username}][${q.problem}]${q.ext}`), q.content, err => {
		if (err) return next(err);
		res.json(true);
	});
});

module.exports = router;
<|endoftext|>


<commit_before>import stringify from '../lib/stringify';
import parse     from '../lib/parse';

import { expect } from 'chai';
import   cases    from 'postcss-parser-tests';

describe('stringify', () => {

    cases.each( (name, css) => {
        it('stringifies ' + name, () => {
            let root = parse(css);
            let result = '';
            stringify(root, i => result += i );
            expect(result).to.eql(css);
        });
    });

});
<commit_msg>Clean code style in stringify test<commit_after>import stringify from '../lib/stringify';
import parse     from '../lib/parse';

import { expect } from 'chai';
import   cases    from 'postcss-parser-tests';

describe('stringify', () => {

    cases.each( (name, css) => {
        it('stringifies ' + name, () => {
            let result = '';
            let root   = parse(css);
            stringify(root, i => result += i );
            expect(result).to.eql(css);
        });
    });

});
<|endoftext|>