<commit_before>/**
Copyright (c) 2010 Dennis Hotson

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

(function() {

jQuery.fn.springy = function(params) {
	var graph = this.graph = params.graph || new Graph();

	var stiffness = params.stiffness || 400.0;
	var repulsion = params.repulsion || 400.0;
	var damping = params.damping || 0.5;

	var canvas = this[0];
	var ctx = canvas.getContext("2d");

	var layout = this.layout = new Layout.ForceDirected(graph, stiffness, repulsion, damping);

	// calculate bounding box of graph layout.. with ease-in
	var currentBB = layout.getBoundingBox();
	var targetBB = {bottomleft: new Vector(-2, -2), topright: new Vector(2, 2)};

	// auto adjusting bounding box
	Layout.requestAnimationFrame(function adjust() {
		targetBB = layout.getBoundingBox();
		// current gets 20% closer to target every iteration
		currentBB = {
			bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
				.divide(10)),
			topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
				.divide(10))
		};

		Layout.requestAnimationFrame(adjust);
	});

	// convert to/from screen coordinates
	toScreen = function(p) {
		var size = currentBB.topright.subtract(currentBB.bottomleft);
		var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
		var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
		return new Vector(sx, sy);
	};

	fromScreen = function(s) {
		var size = currentBB.topright.subtract(currentBB.bottomleft);
		var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
		var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
		return new Vector(px, py);
	};

	// half-assed drag and drop
	var selected = null;
	var nearest = null;
	var dragged = null;

	jQuery(canvas).mousedown(function(e) {
		jQuery('.actions').hide();

		var pos = jQuery(this).offset();
		var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
		selected = nearest = dragged = layout.nearest(p);

		if (selected.node !== null) {
			// Part of the same bug mentioned later. Store the previous mass
			// before upscaling it for dragging.
			dragged.point.m = 10000.0;
		}

		renderer.start();
	});

	jQuery(canvas).mousemove(function(e) {
		var pos = jQuery(this).offset();
		var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
		nearest = layout.nearest(p);

		if (dragged !== null && dragged.node !== null) {
			dragged.point.p.x = p.x;
			dragged.point.p.y = p.y;
		}

		renderer.start();
	});

	jQuery(window).bind('mouseup',function(e) {
		// Bug! Node's mass isn't reset on mouseup. Nodes which have been
		// dragged don't repulse very well. Store the initial mass in mousedown
		// and then restore it here.
		dragged = null;
	});

	Node.prototype.getWidth = function() {
		var text = typeof(this.data.label) !== 'undefined' ? this.data.label : this.id;
		if (this._width && this._width[text])
			return this._width[text];

		ctx.save();
		ctx.font = "16px Verdana, sans-serif";
		var width = ctx.measureText(text).width + 10;
		ctx.restore();

		this._width || (this._width = {});
		this._width[text] = width;

		return width;
	};

	Node.prototype.getHeight = function() {
		// Magic number with no explanation.
		return 20;
	};

	var renderer = new Renderer(1, layout,
		function clear() {
			ctx.clearRect(0,0,canvas.width,canvas.height);
		},
		function drawEdge(edge, p1, p2) {
			var x1 = toScreen(p1).x;
			var y1 = toScreen(p1).y;
			var x2 = toScreen(p2).x;
			var y2 = toScreen(p2).y;

			var direction = new Vector(x2-x1, y2-y1);
			var normal = direction.normal().normalise();

			var from = graph.getEdges(edge.source, edge.target);
			var to = graph.getEdges(edge.target, edge.source);

			var total = from.length + to.length;

			// Figure out edge's position in relation to other edges between the same nodes
			var n = 0;
			for (var i=0; i<from.length; i++) {
				if (from[i].id === edge.id) {
					n = i;
				}
			}

			var spacing = 6.0;

			// Figure out how far off center the line should be drawn
			var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));

			var s1 = toScreen(p1).add(offset);
			var s2 = toScreen(p2).add(offset);

			var boxWidth = edge.target.getWidth();
			var boxHeight = edge.target.getHeight();

			var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);

			if (!intersection) {
				intersection = s2;
			}

			var stroke = typeof(edge.data.color) !== 'undefined' ? edge.data.color : '#000000';

			var arrowWidth;
			var arrowLength;

			var weight = typeof(edge.data.weight) !== 'undefined' ? edge.data.weight : 1.0;

			ctx.lineWidth = Math.max(weight *  2, 0.1);
			arrowWidth = 1 + ctx.lineWidth;
			arrowLength = 8;

			var directional = typeof(edge.data.directional) !== 'undefined' ? edge.data.directional : true;

			// line
			var lineEnd;
			if (directional) {
				lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
			} else {
				lineEnd = s2;
			}

			ctx.strokeStyle = stroke;
			ctx.beginPath();
			ctx.moveTo(s1.x, s1.y);
			ctx.lineTo(lineEnd.x, lineEnd.y);
			ctx.stroke();

			// arrow

			if (directional) {
				ctx.save();
				ctx.fillStyle = stroke;
				ctx.translate(intersection.x, intersection.y);
				ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
				ctx.beginPath();
				ctx.moveTo(-arrowLength, arrowWidth);
				ctx.lineTo(0, 0);
				ctx.lineTo(-arrowLength, -arrowWidth);
				ctx.lineTo(-arrowLength * 0.8, -0);
				ctx.closePath();
				ctx.fill();
				ctx.restore();
			}

      // label

      if (text = typeof(edge.data.label) !== 'undefined') {
        ctx.save();
        ctx.textAlign = "center";
        ctx.textBaseline = "top";
        ctx.font = "10px Helvetica, sans-serif";
        ctx.fillStyle = "#5BA6EC";
        ctx.fillText(text, (x1+x2)/2, (y1+y2)/2);
        ctx.restore();
      }

		},
		function drawNode(node, p) {
			var s = toScreen(p);

			ctx.save();

			var boxWidth = node.getWidth();
			var boxHeight = node.getHeight();

			// fill background
			ctx.clearRect(s.x - boxWidth/2, s.y - 10, boxWidth, 20);

			// fill background
			if (selected !== null && nearest.node !== null && selected.node.id === node.id) {
				ctx.fillStyle = "#FFFFE0";
			} else if (nearest !== null && nearest.node !== null && nearest.node.id === node.id) {
				ctx.fillStyle = "#EEEEEE";
			} else {
				ctx.fillStyle = "#FFFFFF";
			}

			ctx.fillRect(s.x - boxWidth/2, s.y - 10, boxWidth, 20);

			ctx.textAlign = "left";
			ctx.textBaseline = "top";
			ctx.font = "16px Verdana, sans-serif";
			ctx.fillStyle = "#000000";
			ctx.font = "16px Verdana, sans-serif";
			var text = typeof(node.data.label) !== 'undefined' ? node.data.label : node.id;
			ctx.fillText(text, s.x - boxWidth/2 + 5, s.y - 8);

			ctx.restore();
		}
	);

	renderer.start();

	// helpers for figuring out where to draw arrows
	function intersect_line_line(p1, p2, p3, p4) {
		var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));

		// lines are parallel
		if (denom === 0) {
			return false;
		}

		var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
		var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;

		if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
			return false;
		}

		return new Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
	}

	function intersect_line_box(p1, p2, p3, w, h) {
		var tl = {x: p3.x, y: p3.y};
		var tr = {x: p3.x + w, y: p3.y};
		var bl = {x: p3.x, y: p3.y + h};
		var br = {x: p3.x + w, y: p3.y + h};

		var result;
		if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
		if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
		if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
		if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left

		return false;
	}

	return this;
}

})();
<commit_msg>label: fixing text<commit_after>/**
Copyright (c) 2010 Dennis Hotson

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

(function() {

jQuery.fn.springy = function(params) {
	var graph = this.graph = params.graph || new Graph();

	var stiffness = params.stiffness || 400.0;
	var repulsion = params.repulsion || 400.0;
	var damping = params.damping || 0.5;

	var canvas = this[0];
	var ctx = canvas.getContext("2d");

	var layout = this.layout = new Layout.ForceDirected(graph, stiffness, repulsion, damping);

	// calculate bounding box of graph layout.. with ease-in
	var currentBB = layout.getBoundingBox();
	var targetBB = {bottomleft: new Vector(-2, -2), topright: new Vector(2, 2)};

	// auto adjusting bounding box
	Layout.requestAnimationFrame(function adjust() {
		targetBB = layout.getBoundingBox();
		// current gets 20% closer to target every iteration
		currentBB = {
			bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
				.divide(10)),
			topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
				.divide(10))
		};

		Layout.requestAnimationFrame(adjust);
	});

	// convert to/from screen coordinates
	toScreen = function(p) {
		var size = currentBB.topright.subtract(currentBB.bottomleft);
		var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
		var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
		return new Vector(sx, sy);
	};

	fromScreen = function(s) {
		var size = currentBB.topright.subtract(currentBB.bottomleft);
		var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
		var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
		return new Vector(px, py);
	};

	// half-assed drag and drop
	var selected = null;
	var nearest = null;
	var dragged = null;

	jQuery(canvas).mousedown(function(e) {
		jQuery('.actions').hide();

		var pos = jQuery(this).offset();
		var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
		selected = nearest = dragged = layout.nearest(p);

		if (selected.node !== null) {
			// Part of the same bug mentioned later. Store the previous mass
			// before upscaling it for dragging.
			dragged.point.m = 10000.0;
		}

		renderer.start();
	});

	jQuery(canvas).mousemove(function(e) {
		var pos = jQuery(this).offset();
		var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
		nearest = layout.nearest(p);

		if (dragged !== null && dragged.node !== null) {
			dragged.point.p.x = p.x;
			dragged.point.p.y = p.y;
		}

		renderer.start();
	});

	jQuery(window).bind('mouseup',function(e) {
		// Bug! Node's mass isn't reset on mouseup. Nodes which have been
		// dragged don't repulse very well. Store the initial mass in mousedown
		// and then restore it here.
		dragged = null;
	});

	Node.prototype.getWidth = function() {
		var text = typeof(this.data.label) !== 'undefined' ? this.data.label : this.id;
		if (this._width && this._width[text])
			return this._width[text];

		ctx.save();
		ctx.font = "16px Verdana, sans-serif";
		var width = ctx.measureText(text).width + 10;
		ctx.restore();

		this._width || (this._width = {});
		this._width[text] = width;

		return width;
	};

	Node.prototype.getHeight = function() {
		// Magic number with no explanation.
		return 20;
	};

	var renderer = new Renderer(1, layout,
		function clear() {
			ctx.clearRect(0,0,canvas.width,canvas.height);
		},
		function drawEdge(edge, p1, p2) {
			var x1 = toScreen(p1).x;
			var y1 = toScreen(p1).y;
			var x2 = toScreen(p2).x;
			var y2 = toScreen(p2).y;

			var direction = new Vector(x2-x1, y2-y1);
			var normal = direction.normal().normalise();

			var from = graph.getEdges(edge.source, edge.target);
			var to = graph.getEdges(edge.target, edge.source);

			var total = from.length + to.length;

			// Figure out edge's position in relation to other edges between the same nodes
			var n = 0;
			for (var i=0; i<from.length; i++) {
				if (from[i].id === edge.id) {
					n = i;
				}
			}

			var spacing = 6.0;

			// Figure out how far off center the line should be drawn
			var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));

			var s1 = toScreen(p1).add(offset);
			var s2 = toScreen(p2).add(offset);

			var boxWidth = edge.target.getWidth();
			var boxHeight = edge.target.getHeight();

			var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);

			if (!intersection) {
				intersection = s2;
			}

			var stroke = typeof(edge.data.color) !== 'undefined' ? edge.data.color : '#000000';

			var arrowWidth;
			var arrowLength;

			var weight = typeof(edge.data.weight) !== 'undefined' ? edge.data.weight : 1.0;

			ctx.lineWidth = Math.max(weight *  2, 0.1);
			arrowWidth = 1 + ctx.lineWidth;
			arrowLength = 8;

			var directional = typeof(edge.data.directional) !== 'undefined' ? edge.data.directional : true;

			// line
			var lineEnd;
			if (directional) {
				lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
			} else {
				lineEnd = s2;
			}

			ctx.strokeStyle = stroke;
			ctx.beginPath();
			ctx.moveTo(s1.x, s1.y);
			ctx.lineTo(lineEnd.x, lineEnd.y);
			ctx.stroke();

			// arrow

			if (directional) {
				ctx.save();
				ctx.fillStyle = stroke;
				ctx.translate(intersection.x, intersection.y);
				ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
				ctx.beginPath();
				ctx.moveTo(-arrowLength, arrowWidth);
				ctx.lineTo(0, 0);
				ctx.lineTo(-arrowLength, -arrowWidth);
				ctx.lineTo(-arrowLength * 0.8, -0);
				ctx.closePath();
				ctx.fill();
				ctx.restore();
			}

      // label

      if (typeof(edge.data.label) !== 'undefined') {
        text = edge.data.label
        ctx.save();
        ctx.textAlign = "center";
        ctx.textBaseline = "top";
        ctx.font = "10px Helvetica, sans-serif";
        ctx.fillStyle = "#5BA6EC";
        ctx.fillText(text, (x1+x2)/2, (y1+y2)/2);
        ctx.restore();
      }

		},
		function drawNode(node, p) {
			var s = toScreen(p);

			ctx.save();

			var boxWidth = node.getWidth();
			var boxHeight = node.getHeight();

			// fill background
			ctx.clearRect(s.x - boxWidth/2, s.y - 10, boxWidth, 20);

			// fill background
			if (selected !== null && nearest.node !== null && selected.node.id === node.id) {
				ctx.fillStyle = "#FFFFE0";
			} else if (nearest !== null && nearest.node !== null && nearest.node.id === node.id) {
				ctx.fillStyle = "#EEEEEE";
			} else {
				ctx.fillStyle = "#FFFFFF";
			}

			ctx.fillRect(s.x - boxWidth/2, s.y - 10, boxWidth, 20);

			ctx.textAlign = "left";
			ctx.textBaseline = "top";
			ctx.font = "16px Verdana, sans-serif";
			ctx.fillStyle = "#000000";
			ctx.font = "16px Verdana, sans-serif";
			var text = typeof(node.data.label) !== 'undefined' ? node.data.label : node.id;
			ctx.fillText(text, s.x - boxWidth/2 + 5, s.y - 8);

			ctx.restore();
		}
	);

	renderer.start();

	// helpers for figuring out where to draw arrows
	function intersect_line_line(p1, p2, p3, p4) {
		var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));

		// lines are parallel
		if (denom === 0) {
			return false;
		}

		var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
		var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;

		if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
			return false;
		}

		return new Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
	}

	function intersect_line_box(p1, p2, p3, w, h) {
		var tl = {x: p3.x, y: p3.y};
		var tr = {x: p3.x + w, y: p3.y};
		var bl = {x: p3.x, y: p3.y + h};
		var br = {x: p3.x + w, y: p3.y + h};

		var result;
		if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
		if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
		if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
		if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left

		return false;
	}

	return this;
}

})();
<|endoftext|>


<commit_before>Onion.widget.Frame = function(jwin, parent, controlid) {
    Onion.widget.Container.apply(this, arguments);
    this.name = "frame";
}

Onion.widget.Frame.prototype = new Onion.widget.Container();

Onion.widget.Frame.prototype.create = function(data) {
    var controlid = "ctrl"+this.controlid;

    // possibly request position, (open) state from the WindowManager
    var config = {'autoOpen':true, 'modal':false, 'resize':false, 'position':'top'};
    if('position' in data && data.position) {
        config.position = data.position; // see http://jqueryui.com/demos/dialog/#option-position
    }

    this.jwin.factory.append('

');
    this.control = $("#"+controlid);
    this.control.dialog(config);
    this.control = $("#"+controlid).parent();
    this.container = $("#"+controlid);
    // dialogBox class not currently used
    this.container.addClass(this.cssclass);
    this.container.addClass(this.name);

    // windows aren't appended, they appear immediately
    this.control.appendTo(this.jwin.toplevels);
    this.set_properties(data);
}

Onion.widget.Frame.prototype.setLayout = function(type, config) {
    Onion.widget.Container.prototype.setLayout.apply(this, arguments);
    // dialogInner class not currently used
    //this.layout.layoutcontrol.addClass("dialogInner");
}

Onion.widget.Frame.prototype.update = function(data) {
    Onion.widget.Container.prototype.update.apply(this, arguments);
    if(data.state) {
        Onion.util.log("Window state update", data);
        if(data.state == "open") {
            this.container.dialog('open');
        }
        else if(data.state == "close") {
            Onion.util.log("Closing");
            this.container.dialog('close');
        }
    }
}

Onion.widget.Frame.prototype.resize = function(width, height) {
    this.container.dialog({width:width, height: height});
    //this.container.dialog({minWidth:width, minHeight: height});
}

Onion.widget.register("window", Onion.widget.Frame);
<commit_msg>support sync. of title<commit_after>Onion.widget.Frame = function(jwin, parent, controlid) {
    Onion.widget.Container.apply(this, arguments);
    this.name = "frame";
}

Onion.widget.Frame.prototype = new Onion.widget.Container();

Onion.widget.Frame.prototype.create = function(data) {
    var controlid = "ctrl"+this.controlid;

    // possibly request position, (open) state from the WindowManager
    var config = {'autoOpen':true, 'modal':false, 'resize':false, 'position':'top'};
    if('position' in data && data.position) {
        config.position = data.position; // see http://jqueryui.com/demos/dialog/#option-position
    }

    this.jwin.factory.append('

');
    this.control = $("#"+controlid);
    this.control.dialog(config);
    this.control = $("#"+controlid).parent();
    this.container = $("#"+controlid);
    // dialogBox class not currently used
    this.container.addClass(this.cssclass);
    this.container.addClass(this.name);

    // windows aren't appended, they appear immediately
    this.control.appendTo(this.jwin.toplevels);
    this.set_properties(data);
}

Onion.widget.Frame.prototype.setLayout = function(type, config) {
    Onion.widget.Container.prototype.setLayout.apply(this, arguments);
    // dialogInner class not currently used
    //this.layout.layoutcontrol.addClass("dialogInner");
}

Onion.widget.Frame.prototype.update = function(data) {
    Onion.widget.Container.prototype.update.apply(this, arguments);
    if(data.state) {
        Onion.util.log("Window state update", data);
        if(data.state == "open") {
            this.container.dialog('open');
        }
        else if(data.state == "close") {
            Onion.util.log("Closing");
            this.container.dialog('close');
        }
    }
    if('title' in data && data.title) {
        this.container.dialog({title:data.title});
    }
}

Onion.widget.Frame.prototype.resize = function(width, height) {
    this.container.dialog({width:width, height: height});
    //this.container.dialog({minWidth:width, minHeight: height});
}

Onion.widget.register("window", Onion.widget.Frame);
<|endoftext|>


<commit_before>var express = require('express');
var config = require('../../config');
var path = require('path');
var fs = require('fs');
var temp = require('temp');
var spawn = require('child_process').spawn;
var rimraf = require('rimraf');

function prepareOptionsWebM(target, targetWidth) {
	var options = ['-i', target, '-f', 'webm', '-vf', 'scale=min(' + targetWidth + '\\, iw):-1', 'pipe:1'];
	options.splice.apply(options, [options.length - 1, 0].concat(config.transcodeParameters.misc));
	return options;
}

var h264Options = ['-acodec', 'libvo_aacenc', '-ac', '2', '-map', 0, '-vcodec', 'libx264', '-x264opts', 'level=3.1',
	'-profile:v', 'main', '-preset:v', 'fast', '-ar', 44100].concat(config.transcodeParameters.misc);

function prepareOptionsHls(target, targetWidth) {
	var options = ['-i', target,
		'-async', 1, /*'-vf', 'scale=min(' + targetWidth + '\\, iw):-1',*/ '-ac', '2', //TODO: Need to check if height would be odd (impossible)
		'-flags', '-global_header', '-f', 'segment', '-segment_time', '10',
		'-segment_list', 'playlist.m3u8', '-segment_format', 'mpegts', '-segment_list_flags', 'live',
		'HLS%05d.ts'];

	options.splice.apply(options, [2, 0].concat(h264Options));
	options.splice.apply(options, [options.length - 1, 0].concat(config.transcodeParameters.misc));
	return options;
}

function prepareOptionsFlv(target, targetWidth) {
	var options = ['-i', target, '-f', 'flv',
		'-vf', 'scale=min(' + targetWidth + '\\, iw):-1', 'pipe:1'];

	options.splice.apply(options, [2, 0].concat(h264Options));
	options.splice.apply(options, [options.length - 1, 0].concat(config.transcodeParameters.misc));
	return options;
}

function killEncode() {
	for (var target in runningEncodes) {
		var encode = runningEncodes[target];
		if (encode.lastAccess < Date.now() - 30000) {
			encode.ffmpeg.kill();
			rimraf(encode.tmpPath, function () { });
			delete runningEncodes[target];
		}
	}
}

function deliverHLSPath(reqPath, encode, res, retries) {
	var isPlaylist = reqPath.substring(reqPath.length - 4) === 'm3u8';
	var idx = reqPath.lastIndexOf('/hls/');
	fs.readFile(encode.tmpPath + '/' + reqPath.substring(idx + 5), function (err, data) {
		var match;
		if (err || (isPlaylist && (!(match = data.toString().match(/.ts/g)) || match.length < 2))) {
			if (retries) {
				setTimeout(function () {
					deliverHLSPath(reqPath, encode, res, retries - 1);
				}, 1000);
			} else {
				res.send(500);
			}
			return;
		}

		encode.lastAccess = Date.now();
		if (isPlaylist) {
			res.type('application/vnd.apple.mpegurl');
		} else {
			res.type('video/mp2t');
		}
		res.send(206, data);
	});
}

var runningEncodes = [];

setInterval(killEncode, 1000);

module.exports = function () {
	var handler = express.static(config.mediaPath);
	if (config.transcode) {
		handler = function (req, res, next) {
			var targetWidth = parseInt(req.query.size, 10) ? req.query.size : 1920;

			var uri = decodeURI(req.path);
			var splitted = uri.split('/');
			var idx, codec, target;
			if ((idx = uri.lastIndexOf('/webm/')) !== -1) {
				codec = 'webm';
			} else if ((idx = uri.lastIndexOf('/hls/')) !== -1) {
				codec = 'hls';
			} else if ((idx = uri.lastIndexOf('/flv/')) !== -1) {
				codec = 'flv';
			}

			if (codec) {
				target = path.join(config.mediaPath, uri.substring(0, idx));
			}

			if (codec === 'webm') {
				var options = prepareOptionsWebM(target, targetWidth);

				var ffmpeg = spawn(__dirname + '/ffmpeg', options, { cwd: __dirname });

				req.on('close', function () {
					ffmpeg.kill();
				});

				res.writeHead(200, {
					'Transfer-Encoding': 'chunked',
					'Content-Type': 'video/webm'
				});
				ffmpeg.stdout.pipe(res);
			} else if (codec === 'flv') {
				var options = prepareOptionsFlv(target, targetWidth);

				var ffmpeg = spawn(__dirname + '/ffmpeg', options, { cwd: __dirname });

				req.on('close', function () {
					ffmpeg.kill();
				});

				res.writeHead(200, {
					'Transfer-Encoding': 'chunked',
					'Content-Type': 'video/x-flv'
				});
				ffmpeg.stdout.pipe(res);
			} else if (codec === 'hls') {
				if (runningEncodes[target]) {
					deliverHLSPath(uri, runningEncodes[target], res, 20);
				} else {
					temp.mkdir(null, function (err, tmpPath) {
						if (err) {
							res.send(500);
							return;
						}

						var options = prepareOptionsHls(target, targetWidth);

						var ffmpeg = spawn(__dirname + '/ffmpeg', options, { cwd: tmpPath });
						runningEncodes[target] = { lastAccess: Date.now(), tmpPath: tmpPath, ffmpeg: ffmpeg };

						deliverHLSPath(uri, runningEncodes[target], res, 20);
					});
				}
			} else {
				res.sendfile(path.join(config.mediaPath, uri));
			}
		};
	}

	return {
		use: {
			'': handler
		}
	};
};<commit_msg>Ensure multiple of 2 height<commit_after>var express = require('express');
var config = require('../../config');
var path = require('path');
var fs = require('fs');
var temp = require('temp');
var spawn = require('child_process').spawn;
var rimraf = require('rimraf');

function prepareOptionsWebM(target, targetWidth) {
	var options = ['-i', target, '-f', 'webm', '-vf', 'scale=min(' + targetWidth + '\\, iw):-1', 'pipe:1'];
	options.splice.apply(options, [options.length - 1, 0].concat(config.transcodeParameters.misc));
	return options;
}

var h264Options = ['-acodec', 'libvo_aacenc', '-ac', '2', '-map', 0, '-vcodec', 'libx264', '-x264opts', 'level=3.1',
	'-profile:v', 'main', '-preset:v', 'fast', '-ar', 44100].concat(config.transcodeParameters.misc);

function prepareOptionsHls(target, targetWidth) {
	var options = ['-i', target,
		'-async', 1, '-vf', 'scale=min(' + targetWidth + '\\, iw):trunc(ow/a/2)*2', '-ac', '2',
		'-flags', '-global_header', '-f', 'segment', '-segment_time', '10',
		'-segment_list', 'playlist.m3u8', '-segment_format', 'mpegts', '-segment_list_flags', 'live',
		'HLS%05d.ts'];

	options.splice.apply(options, [2, 0].concat(h264Options));
	options.splice.apply(options, [options.length - 1, 0].concat(config.transcodeParameters.misc));
	return options;
}

function prepareOptionsFlv(target, targetWidth) {
	var options = ['-i', target, '-f', 'flv',
		'-vf', 'scale=min(' + targetWidth + '\\, iw):-1', 'pipe:1'];

	options.splice.apply(options, [2, 0].concat(h264Options));
	options.splice.apply(options, [options.length - 1, 0].concat(config.transcodeParameters.misc));
	return options;
}

function killEncode() {
	for (var target in runningEncodes) {
		var encode = runningEncodes[target];
		if (encode.lastAccess < Date.now() - 30000) {
			encode.ffmpeg.kill();
			rimraf(encode.tmpPath, function () { });
			delete runningEncodes[target];
		}
	}
}

function deliverHLSPath(reqPath, encode, res, retries) {
	var isPlaylist = reqPath.substring(reqPath.length - 4) === 'm3u8';
	var idx = reqPath.lastIndexOf('/hls/');
	fs.readFile(encode.tmpPath + '/' + reqPath.substring(idx + 5), function (err, data) {
		var match;
		if (err || (isPlaylist && (!(match = data.toString().match(/.ts/g)) || match.length < 2))) {
			if (retries) {
				setTimeout(function () {
					deliverHLSPath(reqPath, encode, res, retries - 1);
				}, 1000);
			} else {
				res.send(500);
			}
			return;
		}

		encode.lastAccess = Date.now();
		if (isPlaylist) {
			res.type('application/vnd.apple.mpegurl');
		} else {
			res.type('video/mp2t');
		}
		res.send(206, data);
	});
}

var runningEncodes = [];

setInterval(killEncode, 1000);

module.exports = function () {
	var handler = express.static(config.mediaPath);
	if (config.transcode) {
		handler = function (req, res, next) {
			var targetWidth = parseInt(req.query.size, 10) ? req.query.size : 1920;

			var uri = decodeURI(req.path);
			var splitted = uri.split('/');
			var idx, codec, target;
			if ((idx = uri.lastIndexOf('/webm/')) !== -1) {
				codec = 'webm';
			} else if ((idx = uri.lastIndexOf('/hls/')) !== -1) {
				codec = 'hls';
			} else if ((idx = uri.lastIndexOf('/flv/')) !== -1) {
				codec = 'flv';
			}

			if (codec) {
				target = path.join(config.mediaPath, uri.substring(0, idx));
			}

			if (codec === 'webm') {
				var options = prepareOptionsWebM(target, targetWidth);

				var ffmpeg = spawn(__dirname + '/ffmpeg', options, { cwd: __dirname });

				req.on('close', function () {
					ffmpeg.kill();
				});

				res.writeHead(200, {
					'Transfer-Encoding': 'chunked',
					'Content-Type': 'video/webm'
				});
				ffmpeg.stdout.pipe(res);
			} else if (codec === 'flv') {
				var options = prepareOptionsFlv(target, targetWidth);

				var ffmpeg = spawn(__dirname + '/ffmpeg', options, { cwd: __dirname });

				req.on('close', function () {
					ffmpeg.kill();
				});

				res.writeHead(200, {
					'Transfer-Encoding': 'chunked',
					'Content-Type': 'video/x-flv'
				});
				ffmpeg.stdout.pipe(res);
			} else if (codec === 'hls') {
				if (runningEncodes[target]) {
					deliverHLSPath(uri, runningEncodes[target], res, 20);
				} else {
					temp.mkdir(null, function (err, tmpPath) {
						if (err) {
							res.send(500);
							return;
						}

						var options = prepareOptionsHls(target, targetWidth);

						var ffmpeg = spawn(__dirname + '/ffmpeg', options, { cwd: tmpPath });
						runningEncodes[target] = { lastAccess: Date.now(), tmpPath: tmpPath, ffmpeg: ffmpeg };

						deliverHLSPath(uri, runningEncodes[target], res, 20);
					});
				}
			} else {
				res.sendfile(path.join(config.mediaPath, uri));
			}
		};
	}

	return {
		use: {
			'': handler
		}
	};
};<|endoftext|>


<commit_before>'use strict';

var events = require('events');
var util = require('util');
var ReplyError = require('../redis').ReplyError;

function Packet(type, size) {
  this.type = type;
  this.size = +size;
}

function ReplyParser(options) {
  this.options = options || { };

  this._buffer            = null;
  this._offset            = 0;
  this._encoding          = 'utf-8';
  this._reply_type        = null;
}

util.inherits(ReplyParser, events.EventEmitter);

module.exports = ReplyParser;

function IncompleteReadBuffer(message) {
  Error.call(this);
  Error.captureStackTrace(this, this.constructor);

  this.name = this.constructor.name;
  this.message = message;
}
util.inherits(IncompleteReadBuffer, Error);

// Buffer.toString() is quite slow for small strings
function small_toString(buf, start, end) {
  var tmp = '', i;

  for (i = start; i < end; i++) {
    tmp += String.fromCharCode(buf[i]);
  }

  return tmp;
}

ReplyParser.prototype._parseResult = function (type) {
  var start, end, offset, packetHeader;

  if (type === 43 || type === 45) { // + or -
    // up to the delimiter
    end = this._packetEndOffset() - 1;
    start = this._offset;

    // include the delimiter
    this._offset = end + 2;

    if (end > this._buffer.length) {
      this._offset = start;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    if (type === 45) {
      return new ReplyError(this._buffer.toString(this._encoding, start, end));
    }
    if (this.options.returnBuffers) {
      return this._buffer.slice(start, end);
    } else {
      if (end - start < 65536) { // completely arbitrary
        return small_toString(this._buffer, start, end);
      } else {
        return this._buffer.toString(this._encoding, start, end);
      }
    }
  } else if (type === 58) { // :
    // up to the delimiter
    end = this._packetEndOffset() - 1;
    start = this._offset;

    // include the delimiter
    this._offset = end + 2;

    if (end > this._buffer.length) {
      this._offset = start;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    // TODO number?
    // if (this.options.returnBuffers) {
    //   return this._buffer.slice(start, end);
    // }

    // return the coerced numeric value
    return +small_toString(this._buffer, start, end);
  } else if (type === 36) { // $
    // set a rewind point, as the packet could be larger than the
    // buffer in memory
    offset = this._offset - 1;

    packetHeader = new Packet(type, this.parseHeader());

    // packets with a size of -1 are considered null
    if (packetHeader.size === -1) {
      return undefined;
    }

    end = this._offset + packetHeader.size;
    start = this._offset;

    // set the offset to after the delimiter
    this._offset = end + 2;

    if (end > this._buffer.length) {
      this._offset = offset;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    if (this.options.returnBuffers) {
      return this._buffer.slice(start, end);
    } else {
      return this._buffer.toString(this._encoding, start, end);
    }
  } else if (type === 42) { // *
    offset = this._offset;
    packetHeader = new Packet(type, this.parseHeader());

    if (packetHeader.size < 0) {
      return null;
    }

    if (packetHeader.size > this._bytesRemaining()) {
      this._offset = offset - 1;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    var reply = [ ];
    var ntype, i, res;

    offset = this._offset - 1;

    for (i = 0; i < packetHeader.size; i++) {
      ntype = this._buffer[this._offset++];

      if (this._offset > this._buffer.length) {
        throw new IncompleteReadBuffer('Wait for more data.');
      }
      res = this._parseResult(ntype);
      if (res === undefined) {
        res = null;
      }
      reply.push(res);
    }

    return reply;
  }
};

ReplyParser.prototype.execute = function (buffer) {
  this.append(buffer);

  var type, ret, offset;

  while (true) {
    offset = this._offset;
    try {
      // at least 4 bytes: :1\r\n
      if (this._bytesRemaining() < 4) {
        break;
      }

      type = this._buffer[this._offset++];

      if (type === 43) { // +
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        this.send_reply(ret);
      } else  if (type === 45) { // -
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        this.send_error(ret);
      } else if (type === 58) { // :
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        this.send_reply(ret);
      } else if (type === 36) { // $
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        // check the state for what is the result of
        // a -1, set it back up for a null reply
        if (ret === undefined) {
          ret = null;
        }

        this.send_reply(ret);
      } else if (type === 42) { // *
        // set a rewind point. if a failure occurs,
        // wait for the next execute()/append() and try again
        offset = this._offset - 1;

        ret = this._parseResult(type);

        this.send_reply(ret);
      }
    } catch (err) {
      // catch the error (not enough data), rewind, and wait
      // for the next packet to appear
      if (! (err instanceof IncompleteReadBuffer)) {
        throw err;
      }
      this._offset = offset;
      break;
    }
  }
};

ReplyParser.prototype.append = function (newBuffer) {
  if (!newBuffer) {
    return;
  }

  // first run
  if (this._buffer === null) {
    this._buffer = newBuffer;

    return;
  }

  // out of data
  if (this._offset >= this._buffer.length) {
    this._buffer = newBuffer;
    this._offset = 0;

    return;
  }

  // very large packet
  // check for concat, if we have it, use it
  if (Buffer.concat !== undefined) {
    this._buffer = Buffer.concat([this._buffer.slice(this._offset), newBuffer]);
  } else {
    var remaining = this._bytesRemaining(),
      newLength = remaining + newBuffer.length,
      tmpBuffer = new Buffer(newLength);

    this._buffer.copy(tmpBuffer, 0, this._offset);
    newBuffer.copy(tmpBuffer, remaining, 0);

    this._buffer = tmpBuffer;
  }

  this._offset = 0;
};

ReplyParser.prototype.parseHeader = function () {
  var end   = this._packetEndOffset(),
    value = small_toString(this._buffer, this._offset, end - 1);

  this._offset = end + 1;

  return value;
};

ReplyParser.prototype._packetEndOffset = function () {
  var offset = this._offset;

  while (this._buffer[offset] !== 0x0d && this._buffer[offset + 1] !== 0x0a) {
    offset++;

    if (offset >= this._buffer.length) {
      throw new IncompleteReadBuffer('didn\'t see LF after NL reading multi bulk count (' + offset + ' => ' + this._buffer.length + ', ' + this._offset + ')');
    }
  }

  offset++;
  return offset;
};

ReplyParser.prototype._bytesRemaining = function () {
  return (this._buffer.length - this._offset) < 0 ? 0 : (this._buffer.length - this._offset);
};

ReplyParser.prototype.parser_error = function (message) {
  this.emit('error', message);
};

ReplyParser.prototype.send_error = function (reply) {
  this.emit('reply error', reply);
};

ReplyParser.prototype.send_reply = function (reply) {
  this.emit('reply', reply);
};
<commit_msg>rename function<commit_after>'use strict';

var events = require('events');
var util = require('util');
var ReplyError = require('../redis').ReplyError;

function Packet(type, size) {
  this.type = type;
  this.size = +size;
}

function ReplyParser(options) {
  this.options = options || { };

  this._buffer            = null;
  this._offset            = 0;
  this._encoding          = 'utf-8';
  this._reply_type        = null;
}

util.inherits(ReplyParser, events.EventEmitter);

module.exports = ReplyParser;

function IncompleteReadBuffer(message) {
  Error.call(this);
  Error.captureStackTrace(this, this.constructor);

  this.name = this.constructor.name;
  this.message = message;
}
util.inherits(IncompleteReadBuffer, Error);

// Buffer.toString() is quite slow for small strings
function smallToString(buf, start, end) {
  var tmp = '', i;

  for (i = start; i < end; i++) {
    tmp += String.fromCharCode(buf[i]);
  }

  return tmp;
}

ReplyParser.prototype._parseResult = function (type) {
  var start, end, offset, packetHeader;

  if (type === 43 || type === 45) { // + or -
    // up to the delimiter
    end = this._packetEndOffset() - 1;
    start = this._offset;

    // include the delimiter
    this._offset = end + 2;

    if (end > this._buffer.length) {
      this._offset = start;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    if (type === 45) {
      return new ReplyError(this._buffer.toString(this._encoding, start, end));
    }
    if (this.options.returnBuffers) {
      return this._buffer.slice(start, end);
    } else {
      if (end - start < 65536) { // completely arbitrary
        return smallToString(this._buffer, start, end);
      } else {
        return this._buffer.toString(this._encoding, start, end);
      }
    }
  } else if (type === 58) { // :
    // up to the delimiter
    end = this._packetEndOffset() - 1;
    start = this._offset;

    // include the delimiter
    this._offset = end + 2;

    if (end > this._buffer.length) {
      this._offset = start;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    // TODO number?
    // if (this.options.returnBuffers) {
    //   return this._buffer.slice(start, end);
    // }

    // return the coerced numeric value
    return +smallToString(this._buffer, start, end);
  } else if (type === 36) { // $
    // set a rewind point, as the packet could be larger than the
    // buffer in memory
    offset = this._offset - 1;

    packetHeader = new Packet(type, this.parseHeader());

    // packets with a size of -1 are considered null
    if (packetHeader.size === -1) {
      return undefined;
    }

    end = this._offset + packetHeader.size;
    start = this._offset;

    // set the offset to after the delimiter
    this._offset = end + 2;

    if (end > this._buffer.length) {
      this._offset = offset;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    if (this.options.returnBuffers) {
      return this._buffer.slice(start, end);
    } else {
      return this._buffer.toString(this._encoding, start, end);
    }
  } else if (type === 42) { // *
    offset = this._offset;
    packetHeader = new Packet(type, this.parseHeader());

    if (packetHeader.size < 0) {
      return null;
    }

    if (packetHeader.size > this._bytesRemaining()) {
      this._offset = offset - 1;
      throw new IncompleteReadBuffer('Wait for more data.');
    }

    var reply = [ ];
    var ntype, i, res;

    offset = this._offset - 1;

    for (i = 0; i < packetHeader.size; i++) {
      ntype = this._buffer[this._offset++];

      if (this._offset > this._buffer.length) {
        throw new IncompleteReadBuffer('Wait for more data.');
      }
      res = this._parseResult(ntype);
      if (res === undefined) {
        res = null;
      }
      reply.push(res);
    }

    return reply;
  }
};

ReplyParser.prototype.execute = function (buffer) {
  this.append(buffer);

  var type, ret, offset;

  while (true) {
    offset = this._offset;
    try {
      // at least 4 bytes: :1\r\n
      if (this._bytesRemaining() < 4) {
        break;
      }

      type = this._buffer[this._offset++];

      if (type === 43) { // +
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        this.send_reply(ret);
      } else  if (type === 45) { // -
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        this.send_error(ret);
      } else if (type === 58) { // :
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        this.send_reply(ret);
      } else if (type === 36) { // $
        ret = this._parseResult(type);

        if (ret === null) {
          break;
        }

        // check the state for what is the result of
        // a -1, set it back up for a null reply
        if (ret === undefined) {
          ret = null;
        }

        this.send_reply(ret);
      } else if (type === 42) { // *
        // set a rewind point. if a failure occurs,
        // wait for the next execute()/append() and try again
        offset = this._offset - 1;

        ret = this._parseResult(type);

        this.send_reply(ret);
      }
    } catch (err) {
      // catch the error (not enough data), rewind, and wait
      // for the next packet to appear
      if (! (err instanceof IncompleteReadBuffer)) {
        throw err;
      }
      this._offset = offset;
      break;
    }
  }
};

ReplyParser.prototype.append = function (newBuffer) {
  if (!newBuffer) {
    return;
  }

  // first run
  if (this._buffer === null) {
    this._buffer = newBuffer;

    return;
  }

  // out of data
  if (this._offset >= this._buffer.length) {
    this._buffer = newBuffer;
    this._offset = 0;

    return;
  }

  // very large packet
  // check for concat, if we have it, use it
  if (Buffer.concat !== undefined) {
    this._buffer = Buffer.concat([this._buffer.slice(this._offset), newBuffer]);
  } else {
    var remaining = this._bytesRemaining(),
      newLength = remaining + newBuffer.length,
      tmpBuffer = new Buffer(newLength);

    this._buffer.copy(tmpBuffer, 0, this._offset);
    newBuffer.copy(tmpBuffer, remaining, 0);

    this._buffer = tmpBuffer;
  }

  this._offset = 0;
};

ReplyParser.prototype.parseHeader = function () {
  var end   = this._packetEndOffset(),
    value = smallToString(this._buffer, this._offset, end - 1);

  this._offset = end + 1;

  return value;
};

ReplyParser.prototype._packetEndOffset = function () {
  var offset = this._offset;

  while (this._buffer[offset] !== 0x0d && this._buffer[offset + 1] !== 0x0a) {
    offset++;

    if (offset >= this._buffer.length) {
      throw new IncompleteReadBuffer('didn\'t see LF after NL reading multi bulk count (' + offset + ' => ' + this._buffer.length + ', ' + this._offset + ')');
    }
  }

  offset++;
  return offset;
};

ReplyParser.prototype._bytesRemaining = function () {
  return (this._buffer.length - this._offset) < 0 ? 0 : (this._buffer.length - this._offset);
};

ReplyParser.prototype.parser_error = function (message) {
  this.emit('error', message);
};

ReplyParser.prototype.send_error = function (reply) {
  this.emit('reply error', reply);
};

ReplyParser.prototype.send_reply = function (reply) {
  this.emit('reply', reply);
};
<|endoftext|>


<commit_before>import { sizes } from "./availableSizes";

function getSpacing(spacing, themeData) {
  return themeData[`density.spacings.${sizes[spacing]}`];
}

export default function stylesheet(props, themeData) {
  return {
    spacer: {
      width: props.size ? props.size : getSpacing(props.spacing, themeData),
      height: props.size ? props.size : getSpacing(props.spacing, themeData)
    }
  };
}
<commit_msg>fix: account for flex containers<commit_after>import { sizes } from "./availableSizes";

function getSpacing(spacing, themeData) {
  return themeData[`density.spacings.${sizes[spacing]}`];
}

export default function stylesheet(props, themeData) {
  return {
    spacer: {
      width: props.size ? props.size : getSpacing(props.spacing, themeData),
      height: props.size ? props.size : getSpacing(props.spacing, themeData),
      flex: props.size ? `0 0 ${props.size}` : `0 0 ${getSpacing(props.spacing, themeData)}`
    }
  };
}
<|endoftext|>


<commit_before>TRAFFICSIM_APP.WorldRenderer = function (worldController) {
    var renderer;
    var worldController = worldController;
    var drawDebugInfo = {
        "roadRouteLines": false,
        "collisionMasks": false,
        "vehicleCollisionPredictionPoints": false
    };

    var roadRouteDebugLines = [];
    var roadRouteDebugPoints = [];
    var vehicleCollisionMaskLines = [];
    var vehicleCollisionPredictionMaskLines = [];
    var editModeRectangle = [];

    initialize();
    addEventListeners();

    function addEventListeners() {
        $(window).resize(function() {
            if (worldController.getCamera) {
                worldController.getCamera().aspect = window.innerWidth / window.innerHeight;
                worldController.getCamera().updateProjectionMatrix();

                renderer.setSize(window.innerWidth, window.innerHeight);
            }
        });
    }

    function initialize() {
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;
        renderer.shadowMapSoft = true;
        document.body.appendChild(renderer.domElement);
    }

    this.render = function () {
        updateDebugLines();
        updateEditModeRectangle();
        renderer.render(worldController.getThreeJSScene(), worldController.getCamera());
    };

    function updateDebugLines() {
        if (drawDebugInfo.roadRouteLines) {
            updateRoadRouteDebugLinesAndPoints();
        }

        if (drawDebugInfo.collisionMasks) {
            updateCarMaskDebugLines();
        }

        if (drawDebugInfo.vehicleCollisionPredictionPoints) {
            updateVehicleCollisionPredictionPoints();
        }
    }

    function updateEditModeRectangle() {
        updateLinesInScene();
        updateLinePositions();

        function updateLinePositions() {
            if (editModeRectangle.length > 0) {
                var tileSize = worldController.getMap().getTileSize();
                editModeRectangle[0].geometry.vertices[0] = new THREE.Vector3(
                    Math.floor(worldController.getMouseWorldCoordinates().x / tileSize) * tileSize,
                    1,
                    (Math.floor(worldController.getMouseWorldCoordinates().z  / tileSize) * tileSize));
                editModeRectangle[0].geometry.verticesNeedUpdate = true;
                editModeRectangle[0].geometry.vertices[1] = new THREE.Vector3(
                    Math.floor((worldController.getMouseWorldCoordinates().x + tileSize) / tileSize) * tileSize,
                    1,
                    (Math.floor(worldController.getMouseWorldCoordinates().z / tileSize) * tileSize));
                editModeRectangle[0].geometry.verticesNeedUpdate = true;

                editModeRectangle[1].geometry.vertices[0] = new THREE.Vector3(
                    Math.floor((worldController.getMouseWorldCoordinates().x + tileSize) / tileSize) * tileSize,
                    1,
                    (Math.floor(worldController.getMouseWorldCoordinates().z / tileSize) * tileSize));
                editModeRectangle[1].geometry.verticesNeedUpdate = true;
                editModeRectangle[1].geometry.vertices[1] = new THREE.Vector3(
                    Math.floor((worldController.getMouseWorldCoordinates().x + tileSize) / tileSize) * tileSize,
                    1,
                    (Math.floor((worldController.getMouseWorldCoordinates().z + tileSize) / tileSize) * tileSize));
                editModeRectangle[1].geometry.verticesNeedUpdate = true;

                editModeRectangle[2].geometry.vertices[0] = new THREE.Vector3(
                    Math.floor((worldController.getMouseWorldCoordinates().x + tileSize) / tileSize) * tileSize,
                    1,
                    (Math.floor((worldController.getMouseWorldCoordinates().z + tileSize) / tileSize) * tileSize));
                editModeRectangle[2].geometry.verticesNeedUpdate = true;
                editModeRectangle[2].geometry.vertices[1] = new THREE.Vector3(
                    Math.floor(worldController.getMouseWorldCoordinates().x / tileSize) * tileSize,
                    1,
                    (Math.floor((worldController.getMouseWorldCoordinates().z + tileSize) / tileSize) * tileSize));
                editModeRectangle[2].geometry.verticesNeedUpdate = true;

                editModeRectangle[3].geometry.vertices[0] = new THREE.Vector3(
                    Math.floor(worldController.getMouseWorldCoordinates().x / tileSize) * tileSize,
                    1,
                    (Math.floor((worldController.getMouseWorldCoordinates().z + tileSize) / tileSize) * tileSize));
                editModeRectangle[3].geometry.verticesNeedUpdate = true;
                editModeRectangle[3].geometry.vertices[1] = new THREE.Vector3(
                    Math.floor(worldController.getMouseWorldCoordinates().x / tileSize) * tileSize,
                    1,
                    (Math.floor(worldController.getMouseWorldCoordinates().z / tileSize) * tileSize));
                editModeRectangle[3].geometry.verticesNeedUpdate = true;
            }
        }

        function updateLinesInScene() {
            if (worldController.isEditModeOn() && worldController.isMouseOnMap()) {
                if (editModeRectangle.length === 0) {
                    // TOP

                    var rectangleTop = new THREE.Geometry();
                    rectangleTop.vertices.push(new THREE.Vector3(0, 1, 0));
                    rectangleTop.vertices.push(new THREE.Vector3(8, 1, 0));
                    var topMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleTop = new THREE.Line(rectangleTop, topMaterial);
                    editModeRectangle.push(rectangleTop);
                    worldController.getThreeJSScene().add(rectangleTop);

                    // RIGHT

                    var rectangleRight = new THREE.Geometry();
                    rectangleRight.vertices.push(new THREE.Vector3(8, 1, 0));
                    rectangleRight.vertices.push(new THREE.Vector3(8, 1, 8));
                    var rightMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleRight = new THREE.Line(rectangleRight, rightMaterial);
                    editModeRectangle.push(rectangleRight);
                    worldController.getThreeJSScene().add(rectangleRight);

                    // BOTTOM

                    var rectangleBottom = new THREE.Geometry();
                    rectangleBottom.vertices.push(new THREE.Vector3(8, 1, 8));
                    rectangleBottom.vertices.push(new THREE.Vector3(0, 1, 8));
                    var bottomMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleBottom = new THREE.Line(rectangleBottom, bottomMaterial);
                    editModeRectangle.push(rectangleBottom);
                    worldController.getThreeJSScene().add(rectangleBottom);

                    // LEFT

                    var rectangleLeft = new THREE.Geometry();
                    rectangleLeft.vertices.push(new THREE.Vector3(0, 1, 8));
                    rectangleLeft.vertices.push(new THREE.Vector3(0, 1, 0));
                    var leftMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleLeft = new THREE.Line(rectangleLeft, leftMaterial);
                    editModeRectangle.push(rectangleLeft);
                    worldController.getThreeJSScene().add(rectangleLeft);
                }
            } else {
                editModeRectangle.forEach(function(line) {
                    worldController.getThreeJSScene().remove(line);
                });

                editModeRectangle = [];
            }
        }

    }

    function updateCarMaskDebugLines() {
        // FIXME VERY SLOW, but used only in development machines so proably there is no immediate need to fix this
        vehicleCollisionMaskLines.forEach(function(line) {
            worldController.getThreeJSScene().remove(line)
        });

        vehicleCollisionMaskLines = [];

        worldController.getVehicleController().getVehicles().forEach(function(vehicle) {
            var collisionMaskPoints = vehicle.getCollisionMaskInWorld();

            for (var i = 0; i < collisionMaskPoints.length; i++) {
                var startPoint, endPoint = null;
                if (i < collisionMaskPoints.length - 1) {
                    startPoint = collisionMaskPoints[i];
                    endPoint = collisionMaskPoints[i + 1];
                } else {
                    startPoint = collisionMaskPoints[i];
                    endPoint = collisionMaskPoints[0];
                }

                var debugLine = new THREE.Geometry();
                debugLine.vertices.push(new THREE.Vector3(
                    startPoint.x,
                    1,
                    startPoint.z));
                debugLine.vertices.push(new THREE.Vector3(
                    endPoint.x,
                    1,
                    endPoint.z));
                var material = new THREE.LineBasicMaterial({color: 0xffff00, linewidth: 2});
                debugLine = new THREE.Line(debugLine, material);
                vehicleCollisionMaskLines.push(debugLine);
                worldController.getThreeJSScene().add(debugLine);
            }

        });
    }

    function updateVehicleCollisionPredictionPoints() {
        // FIXME VERY SLOW, but used only in development machines so proably there is no immediate need to fix this
        vehicleCollisionPredictionMaskLines.forEach(function(line) {
            worldController.getThreeJSScene().remove(line)
        });

        vehicleCollisionPredictionMaskLines = [];

        worldController.getVehicleController().getVehicles().forEach(function(vehicle) {
            var collisionPredictionPolygon = vehicle.getCollisionPredictionPolygon();

            if (collisionPredictionPolygon) {
                for (var i = 0; i < collisionPredictionPolygon.length; i++) {
                    var startPoint, endPoint = null;
                    if (i < collisionPredictionPolygon.length - 1) {
                        startPoint = collisionPredictionPolygon[i];
                        endPoint = collisionPredictionPolygon[i + 1];
                    } else {
                        startPoint = collisionPredictionPolygon[i];
                        endPoint = collisionPredictionPolygon[0];
                    }

                    var debugLine = new THREE.Geometry();
                    debugLine.vertices.push(new THREE.Vector3(
                        startPoint.x,
                        1,
                        startPoint.z));
                    debugLine.vertices.push(new THREE.Vector3(
                        endPoint.x,
                        1,
                        endPoint.z));
                    var material = new THREE.LineBasicMaterial({color: 0xff0f00, linewidth: 2});
                    debugLine = new THREE.Line(debugLine, material);
                    vehicleCollisionPredictionMaskLines.push(debugLine);
                    worldController.getThreeJSScene().add(debugLine);
                }
            }
        });
    }

    function  updateRoadRouteDebugLinesAndPoints() {
        // FIXME VERY SLOW, but used only in development machines so proably there is no immediate need to fix this
        roadRouteDebugLines.forEach(function(line) {
            worldController.getThreeJSScene().remove(line)
        });

        roadRouteDebugPoints.forEach(function(point) {
            worldController.getThreeJSScene().remove(point)
        });

        roadRouteDebugLines = [];
        roadRouteDebugPoints = [];

        worldController.getRoadController().getRoutes().forEach(function (route) {
            var debugLine = new THREE.Geometry();
            debugLine.vertices.push(new THREE.Vector3(
                route.startNode.position.x,
                0.15,
                route.startNode.position.z));
            debugLine.vertices.push(new THREE.Vector3(
                route.endNode.position.x,
                0.15,
                route.endNode.position.z));
            var material = new THREE.LineBasicMaterial({color: resolveRouteLineColor(route), linewidth: 2});
            debugLine = new THREE.Line(debugLine, material);
            roadRouteDebugLines.push(debugLine);
            worldController.getThreeJSScene().add(debugLine);
        });

        worldController.getRoadController().getNodes().forEach(function (node) {
            var debugPoint = new THREE.Geometry();
            debugPoint.vertices.push(new THREE.Vector3(
                node.position.x,
                0,
                node.position.z));
            debugPoint.vertices.push(new THREE.Vector3(
                node.position.x,
                0.50,
                node.position.z));
            var material = new THREE.LineBasicMaterial({color: 0xff0000, linewidth: 4});
            debugPoint = new THREE.Line(debugPoint, material);
            roadRouteDebugPoints.push(debugPoint);
            worldController.getThreeJSScene().add(debugPoint);
        });

        function resolveRouteLineColor(route) {
            if (route.isFree()) {
                return 0x00ff00;
            }

            return 0xff0000;
        }
    }
};<commit_msg>Refactor code<commit_after>TRAFFICSIM_APP.WorldRenderer = function (worldController) {
    var renderer;
    var worldController = worldController;
    var drawDebugInfo = {
        "roadRouteLines": false,
        "collisionMasks": false,
        "vehicleCollisionPredictionPoints": false
    };

    var roadRouteDebugLines = [];
    var roadRouteDebugPoints = [];
    var vehicleCollisionMaskLines = [];
    var vehicleCollisionPredictionMaskLines = [];
    var editModeRectangle = [];

    initialize();
    addEventListeners();

    function addEventListeners() {
        $(window).resize(function() {
            if (worldController.getCamera) {
                worldController.getCamera().aspect = window.innerWidth / window.innerHeight;
                worldController.getCamera().updateProjectionMatrix();

                renderer.setSize(window.innerWidth, window.innerHeight);
            }
        });
    }

    function initialize() {
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMapEnabled = true;
        renderer.shadowMapSoft = true;
        document.body.appendChild(renderer.domElement);
    }

    this.render = function () {
        updateDebugLines();
        updateEditModeRectangle();
        renderer.render(worldController.getThreeJSScene(), worldController.getCamera());
    };

    function updateDebugLines() {
        if (drawDebugInfo.roadRouteLines) {
            updateRoadRouteDebugLinesAndPoints();
        }

        if (drawDebugInfo.collisionMasks) {
            updateCarMaskDebugLines();
        }

        if (drawDebugInfo.vehicleCollisionPredictionPoints) {
            updateVehicleCollisionPredictionPoints();
        }
    }

    function updateEditModeRectangle() {
        updateLinesInScene();
        updateLinePositions();

        function updateLinePositions() {
            if (editModeRectangle.length > 0) {
                var tileSize = worldController.getMap().getTileSize();
                var mouseXGrid = Math.floor(worldController.getMouseWorldCoordinates().x / tileSize) * tileSize;
                var mouseZGrid = Math.floor(worldController.getMouseWorldCoordinates().z / tileSize) * tileSize;

                // TOP

                editModeRectangle[0].geometry.vertices[0] = new THREE.Vector3(
                    mouseXGrid,
                    1,
                    mouseZGrid);
                editModeRectangle[0].geometry.verticesNeedUpdate = true;
                editModeRectangle[0].geometry.vertices[1] = new THREE.Vector3(
                    mouseXGrid + tileSize,
                    1,
                    mouseZGrid);
                editModeRectangle[0].geometry.verticesNeedUpdate = true;

                // RIGHT

                editModeRectangle[1].geometry.vertices[0] = new THREE.Vector3(
                    mouseXGrid + tileSize,
                    1,
                    mouseZGrid);
                editModeRectangle[1].geometry.verticesNeedUpdate = true;
                editModeRectangle[1].geometry.vertices[1] = new THREE.Vector3(
                    mouseXGrid + tileSize,
                    1,
                    mouseZGrid + tileSize);
                editModeRectangle[1].geometry.verticesNeedUpdate = true;

                // BOTTOM

                editModeRectangle[2].geometry.vertices[0] = new THREE.Vector3(
                    mouseXGrid + tileSize,
                    1,
                    mouseZGrid + tileSize);
                editModeRectangle[2].geometry.verticesNeedUpdate = true;
                editModeRectangle[2].geometry.vertices[1] = new THREE.Vector3(
                    mouseXGrid,
                    1,
                    mouseZGrid + tileSize);
                editModeRectangle[2].geometry.verticesNeedUpdate = true;

                // LEFT

                editModeRectangle[3].geometry.vertices[0] = new THREE.Vector3(
                    mouseXGrid,
                    1,
                    mouseZGrid + tileSize);
                editModeRectangle[3].geometry.verticesNeedUpdate = true;
                editModeRectangle[3].geometry.vertices[1] = new THREE.Vector3(
                    mouseXGrid,
                    1,
                    mouseZGrid);
                editModeRectangle[3].geometry.verticesNeedUpdate = true;
            }
        }

        function updateLinesInScene() {
            if (worldController.isEditModeOn() && worldController.isMouseOnMap()) {
                if (editModeRectangle.length === 0) {
                    // TOP

                    var rectangleTop = new THREE.Geometry();
                    rectangleTop.vertices.push(new THREE.Vector3(0, 1, 0));
                    rectangleTop.vertices.push(new THREE.Vector3(8, 1, 0));
                    var topMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleTop = new THREE.Line(rectangleTop, topMaterial);
                    editModeRectangle.push(rectangleTop);
                    worldController.getThreeJSScene().add(rectangleTop);

                    // RIGHT

                    var rectangleRight = new THREE.Geometry();
                    rectangleRight.vertices.push(new THREE.Vector3(8, 1, 0));
                    rectangleRight.vertices.push(new THREE.Vector3(8, 1, 8));
                    var rightMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleRight = new THREE.Line(rectangleRight, rightMaterial);
                    editModeRectangle.push(rectangleRight);
                    worldController.getThreeJSScene().add(rectangleRight);

                    // BOTTOM

                    var rectangleBottom = new THREE.Geometry();
                    rectangleBottom.vertices.push(new THREE.Vector3(8, 1, 8));
                    rectangleBottom.vertices.push(new THREE.Vector3(0, 1, 8));
                    var bottomMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleBottom = new THREE.Line(rectangleBottom, bottomMaterial);
                    editModeRectangle.push(rectangleBottom);
                    worldController.getThreeJSScene().add(rectangleBottom);

                    // LEFT

                    var rectangleLeft = new THREE.Geometry();
                    rectangleLeft.vertices.push(new THREE.Vector3(0, 1, 8));
                    rectangleLeft.vertices.push(new THREE.Vector3(0, 1, 0));
                    var leftMaterial = new THREE.LineBasicMaterial({color: 0x00ffff, linewidth: 2});
                    rectangleLeft = new THREE.Line(rectangleLeft, leftMaterial);
                    editModeRectangle.push(rectangleLeft);
                    worldController.getThreeJSScene().add(rectangleLeft);
                }
            } else {
                editModeRectangle.forEach(function(line) {
                    worldController.getThreeJSScene().remove(line);
                });

                editModeRectangle = [];
            }
        }

    }

    function updateCarMaskDebugLines() {
        // FIXME VERY SLOW, but used only in development machines so proably there is no immediate need to fix this
        vehicleCollisionMaskLines.forEach(function(line) {
            worldController.getThreeJSScene().remove(line)
        });

        vehicleCollisionMaskLines = [];

        worldController.getVehicleController().getVehicles().forEach(function(vehicle) {
            var collisionMaskPoints = vehicle.getCollisionMaskInWorld();

            for (var i = 0; i < collisionMaskPoints.length; i++) {
                var startPoint, endPoint = null;
                if (i < collisionMaskPoints.length - 1) {
                    startPoint = collisionMaskPoints[i];
                    endPoint = collisionMaskPoints[i + 1];
                } else {
                    startPoint = collisionMaskPoints[i];
                    endPoint = collisionMaskPoints[0];
                }

                var debugLine = new THREE.Geometry();
                debugLine.vertices.push(new THREE.Vector3(
                    startPoint.x,
                    1,
                    startPoint.z));
                debugLine.vertices.push(new THREE.Vector3(
                    endPoint.x,
                    1,
                    endPoint.z));
                var material = new THREE.LineBasicMaterial({color: 0xffff00, linewidth: 2});
                debugLine = new THREE.Line(debugLine, material);
                vehicleCollisionMaskLines.push(debugLine);
                worldController.getThreeJSScene().add(debugLine);
            }

        });
    }

    function updateVehicleCollisionPredictionPoints() {
        // FIXME VERY SLOW, but used only in development machines so proably there is no immediate need to fix this
        vehicleCollisionPredictionMaskLines.forEach(function(line) {
            worldController.getThreeJSScene().remove(line)
        });

        vehicleCollisionPredictionMaskLines = [];

        worldController.getVehicleController().getVehicles().forEach(function(vehicle) {
            var collisionPredictionPolygon = vehicle.getCollisionPredictionPolygon();

            if (collisionPredictionPolygon) {
                for (var i = 0; i < collisionPredictionPolygon.length; i++) {
                    var startPoint, endPoint = null;
                    if (i < collisionPredictionPolygon.length - 1) {
                        startPoint = collisionPredictionPolygon[i];
                        endPoint = collisionPredictionPolygon[i + 1];
                    } else {
                        startPoint = collisionPredictionPolygon[i];
                        endPoint = collisionPredictionPolygon[0];
                    }

                    var debugLine = new THREE.Geometry();
                    debugLine.vertices.push(new THREE.Vector3(
                        startPoint.x,
                        1,
                        startPoint.z));
                    debugLine.vertices.push(new THREE.Vector3(
                        endPoint.x,
                        1,
                        endPoint.z));
                    var material = new THREE.LineBasicMaterial({color: 0xff0f00, linewidth: 2});
                    debugLine = new THREE.Line(debugLine, material);
                    vehicleCollisionPredictionMaskLines.push(debugLine);
                    worldController.getThreeJSScene().add(debugLine);
                }
            }
        });
    }

    function  updateRoadRouteDebugLinesAndPoints() {
        // FIXME VERY SLOW, but used only in development machines so proably there is no immediate need to fix this
        roadRouteDebugLines.forEach(function(line) {
            worldController.getThreeJSScene().remove(line)
        });

        roadRouteDebugPoints.forEach(function(point) {
            worldController.getThreeJSScene().remove(point)
        });

        roadRouteDebugLines = [];
        roadRouteDebugPoints = [];

        worldController.getRoadController().getRoutes().forEach(function (route) {
            var debugLine = new THREE.Geometry();
            debugLine.vertices.push(new THREE.Vector3(
                route.startNode.position.x,
                0.15,
                route.startNode.position.z));
            debugLine.vertices.push(new THREE.Vector3(
                route.endNode.position.x,
                0.15,
                route.endNode.position.z));
            var material = new THREE.LineBasicMaterial({color: resolveRouteLineColor(route), linewidth: 2});
            debugLine = new THREE.Line(debugLine, material);
            roadRouteDebugLines.push(debugLine);
            worldController.getThreeJSScene().add(debugLine);
        });

        worldController.getRoadController().getNodes().forEach(function (node) {
            var debugPoint = new THREE.Geometry();
            debugPoint.vertices.push(new THREE.Vector3(
                node.position.x,
                0,
                node.position.z));
            debugPoint.vertices.push(new THREE.Vector3(
                node.position.x,
                0.50,
                node.position.z));
            var material = new THREE.LineBasicMaterial({color: 0xff0000, linewidth: 4});
            debugPoint = new THREE.Line(debugPoint, material);
            roadRouteDebugPoints.push(debugPoint);
            worldController.getThreeJSScene().add(debugPoint);
        });

        function resolveRouteLineColor(route) {
            if (route.isFree()) {
                return 0x00ff00;
            }

            return 0xff0000;
        }
    }
};<|endoftext|>


<commit_before>require('dotenv').load();

var Botkit        = require('botkit'),
    redisConfig   = { url: process.env.REDIS_URL },
    redisStorage  = require('botkit-storage-redis')(redisConfig),
    github        = require('octonode'),
    _bots         = {};

const queryString = require('query-string');

if (!process.env.clientId || !process.env.clientSecret || !process.env.PORT) {
  console.log('Error: Specify clientId clientSecret and port in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
  storage: redisStorage
}).configureSlackApp({
 clientId: process.env.clientId,
 clientSecret: process.env.clientSecret,
 scopes: ['bot']
});

var oauth2 = require('simple-oauth2')({
  clientID: process.env.githubClientId,
  clientSecret: process.env.githubClientSecret,
  site: 'https://github.com/login',
  tokenPath: '/oauth/access_token',
  authorizationPath: '/oauth/authorize'
});

controller.setupWebserver(process.env.PORT, function(err, webserver) {

  controller.createOauthEndpoints(controller.webserver, function(err, req, res) {
    if (err) {
      res.status(500).send('ERROR: ' + err);
    } else {
      res.send('Success!');
    }
  });

  // Redirects user to github
  webserver.get('/github-auth', function (req, res) {
    var state_str = req.query.user_id + '#' + req.query.team_id;
    var authorizationURI = oauth2.authCode.authorizeURL({
      redirect_uri: process.env.baseBotUri + '/callback',
      scope: 'notifications, admin:repo_hook',
      // this is the user id
      // might also need the team id
      state: state_str
    });
    res.redirect(authorizationURI);
  });

  webserver.get('/callback', function (req, res) {
    var code = req.query.code;
    var state = req.query.state;
    var slackUserId = state.split('#')[0];
    var slackTeamId = state.split('#')[1];

    oauth2.authCode.getToken({
      code: code,
      redirect_uri: process.env.baseBotUri + '/callback'
    }, saveToken);

    function saveToken(error, result) {
      if (error) { console.log('Access Token Error', error.message); }
      var token = oauth2.accessToken.create(result);
      var parsedQueryString = queryString.parse(token.token);

      controller.storage.users.get(slackUserId, function(err, userData) {
        if (userData == null) {
          controller.storage.users.save({
            id: slackUserId,
            github_access_token: parsedQueryString.access_token,
            team_id: slackTeamId
          }, function(err) {
            saveGithubUsername(slackUserId);
          });
        } else {
          storeNew(userData, 'github_access_token', parsedQueryString.access_token);
          saveGithubUsername(slackUserId);
        }
      });

      res.send(token);
    }
  });

  // Message users that are identified in the pull request body
  webserver.post('/webhooks/pull-request', function(req, res) {
    var prBody = req.body.pull_request.body;
    var ghUsernameArray = prBody.match(/\B@([a-z0-9](?:-?[a-z0-9]){0,38})/gi);
    if (ghUsernameArray == null) { return res.send(''); }

    controller.storage.teams.get(req.query.slack_team_id, function(err, team) {
      var existingBot = _bots[team.bot.token];

      existingBot.api.users.list({}, function(err, response) {
        localUsersMatchingSlackUsers(response.members, function(redisUsers) {
          localUsersMatchingGithubUsernames(ghUsernameArray, redisUsers, function(ghSlackUsers) {
            sendPrMessage(ghSlackUsers, prBody, existingBot, function() {
              res.send('done');
            });
          });
        });
      });
    });
  });
});

controller.storage.teams.all(function(err, teams) {
  for (var t in teams) {
    controller.spawn(teams[t]).startRTM(function(err, bot) {
      if (err) {
        console.log('Error connecting DevBot to Slack:', err);
      } else {
        trackBot(bot);
      }
    });
  }
});

controller.on('create_bot',function(bot, config) {
  if (_bots[config.token]) {
    // already online!
  } else {
    bot.startRTM(function(err) {
      if (!err) {
        trackBot(bot);
      }
    });
  }
});

controller.on('direct_mention',function(bot, message) {
  if (message.text == 'login to github') {
    bot.api.auth.test({}, function(err, response) {
      var link_github = process.env.baseBotUri + '/github-auth?user_id=' + message.user + '&team_id=' + response.team_id;
      bot.reply(message, {
        "text": "<" + link_github + "|connect to your github account>",
        "attachments": []
      });
    });
  } else if (message.text.indexOf('repo:') > -1) {
    var repoName = message.text.split(':')[1];
    var repoOwner = message.user;
    controller.storage.users.get(repoOwner, function(err, userData) {
      var githubClient = github.client(userData.github_access_token);
      var repoLocation = userData.github_username + '/' + repoName;
      var repo = githubClient.repo(repoLocation);
      var callback = process.env.baseBotUri + '/webhooks/pull-request?slack_team_id=' + userData.team_id;
      repo.hook({
        'name': 'web',
        'active': true,
        'events': ['pull_request'],
        'config': {
          'url': callback,
          'content_type': 'json'
        }
      }, function(err, data, headers) {
        if (typeof data == 'undefined') {
          bot.reply(message, 'Could not find any repo by name: ' + repoName);
        } else {
          bot.reply(message, 'Notification set up for: ' + repoName);
        }
      });
    });
  }
});

function trackBot(bot) {
  _bots[bot.config.token] = bot;
}

function sendPrMessage(slackUserArray, prBody, existingBot, callbackFunc) {
  if (slackUserArray.length > 0) {
    for (var i = 0; i < slackUserArray.length; i++) {
      existingBot.startPrivateConversation({ user: slackUserArray[i].id }, function(err, convo) {
        convo.say(prBody);
        if (i == slackUserArray.length) {
          callbackFunc();
        }
      });
    }
  } else {
    return null;
  }
}

function saveGithubUsername(slackId) {
  controller.storage.users.get(slackId, function(err, userData) {
    var github_client = github.client(userData.github_access_token);
    github_client.get('/user', {}, function (err, status, body, headers) {
      storeNew(userData, 'github_username', body.login);
    });
  });
}

function storeNew(existing, key, value) {
  existing[key] = value;
  controller.storage.users.save(existing, function(err) {
    console.log(err);
  });
}

function localUsersMatchingSlackUsers(members, callback) {
  var redisUsersArray = [];
  var callbackCount = 0;
  for (var i = 0; i < members.length; i++) {
    controller.storage.users.get(members[i].id, function(err, userData) {
      if (userData != null) {
        redisUsersArray.push(userData);
      }
      if (++callbackCount == members.length) {
        callback(redisUsersArray);
      }
    });
  }
}

function localUsersMatchingGithubUsernames(ghUsernameArray, redisUsers, callback) {
  var slackUsersWithGithubArray = [];
  for (var i = 0; i < ghUsernameArray.length; i++) {
    var ghUsernameStripped = ghUsernameArray[i].slice(1); // stripped of @ symbol
    for (var ind = 0; ind < redisUsers.length; ind++) {
      if (ghUsernameStripped == redisUsers[ind].github_username) {
        slackUsersWithGithubArray.push(redisUsers[ind]);
      }
      if (ind == (redisUsers.length - 1) && i == (ghUsernameArray.length - 1)) {
        callback(slackUsersWithGithubArray);
      }
    }
  }
}
<commit_msg>no comments<commit_after>require('dotenv').load();

var Botkit        = require('botkit'),
    redisConfig   = { url: process.env.REDIS_URL },
    redisStorage  = require('botkit-storage-redis')(redisConfig),
    github        = require('octonode'),
    _bots         = {};

const queryString = require('query-string');

if (!process.env.clientId || !process.env.clientSecret || !process.env.PORT) {
  console.log('Error: Specify clientId clientSecret and port in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
  storage: redisStorage
}).configureSlackApp({
 clientId: process.env.clientId,
 clientSecret: process.env.clientSecret,
 scopes: ['bot']
});

var oauth2 = require('simple-oauth2')({
  clientID: process.env.githubClientId,
  clientSecret: process.env.githubClientSecret,
  site: 'https://github.com/login',
  tokenPath: '/oauth/access_token',
  authorizationPath: '/oauth/authorize'
});

controller.setupWebserver(process.env.PORT, function(err, webserver) {

  controller.createOauthEndpoints(controller.webserver, function(err, req, res) {
    if (err) {
      res.status(500).send('ERROR: ' + err);
    } else {
      res.send('Success!');
    }
  });

  // Redirects user to github
  webserver.get('/github-auth', function (req, res) {
    var state_str = req.query.user_id + '#' + req.query.team_id;
    var authorizationURI = oauth2.authCode.authorizeURL({
      redirect_uri: process.env.baseBotUri + '/callback',
      scope: 'notifications, admin:repo_hook',
      state: state_str
    });
    res.redirect(authorizationURI);
  });

  webserver.get('/callback', function (req, res) {
    var code = req.query.code;
    var state = req.query.state;
    var slackUserId = state.split('#')[0];
    var slackTeamId = state.split('#')[1];

    oauth2.authCode.getToken({
      code: code,
      redirect_uri: process.env.baseBotUri + '/callback'
    }, saveToken);

    function saveToken(error, result) {
      if (error) { console.log('Access Token Error', error.message); }
      var token = oauth2.accessToken.create(result);
      var parsedQueryString = queryString.parse(token.token);

      controller.storage.users.get(slackUserId, function(err, userData) {
        if (userData == null) {
          controller.storage.users.save({
            id: slackUserId,
            github_access_token: parsedQueryString.access_token,
            team_id: slackTeamId
          }, function(err) {
            saveGithubUsername(slackUserId);
          });
        } else {
          storeNew(userData, 'github_access_token', parsedQueryString.access_token);
          saveGithubUsername(slackUserId);
        }
      });

      res.send(token);
    }
  });

  // Message users that are identified in the pull request body
  webserver.post('/webhooks/pull-request', function(req, res) {
    var prBody = req.body.pull_request.body;
    var ghUsernameArray = prBody.match(/\B@([a-z0-9](?:-?[a-z0-9]){0,38})/gi);
    if (ghUsernameArray == null) { return res.send(''); }

    controller.storage.teams.get(req.query.slack_team_id, function(err, team) {
      var existingBot = _bots[team.bot.token];

      existingBot.api.users.list({}, function(err, response) {
        localUsersMatchingSlackUsers(response.members, function(redisUsers) {
          localUsersMatchingGithubUsernames(ghUsernameArray, redisUsers, function(ghSlackUsers) {
            sendPrMessage(ghSlackUsers, prBody, existingBot, function() {
              res.send('done');
            });
          });
        });
      });
    });
  });
});

controller.storage.teams.all(function(err, teams) {
  for (var t in teams) {
    controller.spawn(teams[t]).startRTM(function(err, bot) {
      if (err) {
        console.log('Error connecting DevBot to Slack:', err);
      } else {
        trackBot(bot);
      }
    });
  }
});

controller.on('create_bot',function(bot, config) {
  if (_bots[config.token]) {
    // already online!
  } else {
    bot.startRTM(function(err) {
      if (!err) {
        trackBot(bot);
      }
    });
  }
});

controller.on('direct_mention',function(bot, message) {
  if (message.text == 'login to github') {
    bot.api.auth.test({}, function(err, response) {
      var link_github = process.env.baseBotUri + '/github-auth?user_id=' + message.user + '&team_id=' + response.team_id;
      bot.reply(message, {
        "text": "<" + link_github + "|connect to your github account>",
        "attachments": []
      });
    });
  } else if (message.text.indexOf('repo:') > -1) {
    var repoName = message.text.split(':')[1];
    var repoOwner = message.user;
    controller.storage.users.get(repoOwner, function(err, userData) {
      var githubClient = github.client(userData.github_access_token);
      var repoLocation = userData.github_username + '/' + repoName;
      var repo = githubClient.repo(repoLocation);
      var callback = process.env.baseBotUri + '/webhooks/pull-request?slack_team_id=' + userData.team_id;
      repo.hook({
        'name': 'web',
        'active': true,
        'events': ['pull_request'],
        'config': {
          'url': callback,
          'content_type': 'json'
        }
      }, function(err, data, headers) {
        if (typeof data == 'undefined') {
          bot.reply(message, 'Could not find any repo by name: ' + repoName);
        } else {
          bot.reply(message, 'Notification set up for: ' + repoName);
        }
      });
    });
  }
});

function trackBot(bot) {
  _bots[bot.config.token] = bot;
}

function sendPrMessage(slackUserArray, prBody, existingBot, callbackFunc) {
  if (slackUserArray.length > 0) {
    for (var i = 0; i < slackUserArray.length; i++) {
      existingBot.startPrivateConversation({ user: slackUserArray[i].id }, function(err, convo) {
        convo.say(prBody);
        if (i == slackUserArray.length) {
          callbackFunc();
        }
      });
    }
  } else {
    return null;
  }
}

function saveGithubUsername(slackId) {
  controller.storage.users.get(slackId, function(err, userData) {
    var github_client = github.client(userData.github_access_token);
    github_client.get('/user', {}, function (err, status, body, headers) {
      storeNew(userData, 'github_username', body.login);
    });
  });
}

function storeNew(existing, key, value) {
  existing[key] = value;
  controller.storage.users.save(existing, function(err) {
    console.log(err);
  });
}

function localUsersMatchingSlackUsers(members, callback) {
  var redisUsersArray = [];
  var callbackCount = 0;
  for (var i = 0; i < members.length; i++) {
    controller.storage.users.get(members[i].id, function(err, userData) {
      if (userData != null) {
        redisUsersArray.push(userData);
      }
      if (++callbackCount == members.length) {
        callback(redisUsersArray);
      }
    });
  }
}

function localUsersMatchingGithubUsernames(ghUsernameArray, redisUsers, callback) {
  var slackUsersWithGithubArray = [];
  for (var i = 0; i < ghUsernameArray.length; i++) {
    var ghUsernameStripped = ghUsernameArray[i].slice(1); // stripped of @ symbol
    for (var ind = 0; ind < redisUsers.length; ind++) {
      if (ghUsernameStripped == redisUsers[ind].github_username) {
        slackUsersWithGithubArray.push(redisUsers[ind]);
      }
      if (ind == (redisUsers.length - 1) && i == (ghUsernameArray.length - 1)) {
        callback(slackUsersWithGithubArray);
      }
    }
  }
}
<|endoftext|>


<commit_before>import {formatPercentage} from 'common/format';
import Module from 'Parser/Core/Module';
import SPELLS from 'common/SPELLS';
import Combatants from 'Parser/Core/Modules/Combatants';

import {ABILITIES_AFFECTED_BY_HEALING_INCREASES} from '../../Constants';
import {HEALS_MASTERY_STACK} from '../../Constants';

const MASTERY_BONUS_FROM_ONE_RATING = 1 / 66666.6666666;
const BASE_MASTERY_PERCENT = 0.048;

class Mastery extends Module {
  static dependencies = {
    combatants: Combatants,
  };

  totalNoMasteryHealing = 0;
  druidSpellNoMasteryHealing = 0;
  masteryTimesHealing = 0;

  hotHealingMap = null;
  masteryBuffs = null;

  on_initialized() {
    // TODO use JS objects instead of Maps for hotHealingMap and masteryBuffs?
    this.hotHealingMap = new Map();
    for(const healId of HEALS_MASTERY_STACK) {
      this.hotHealingMap.set(healId, {'name':SPELLS[healId].name, 'direct':0, 'mastery':0});
    }

    this.masteryBuffs = new Map([
        [ SPELLS.ASTRAL_HARMONY.id, { 'spell':SPELLS.ASTRAL_HARMONY, 'amount':4000 } ],
        [ SPELLS.JACINS_RUSE.id, { 'spell':SPELLS.JACINS_RUSE, 'amount':3000 } ],
    ]);
    for(const buffObj of this.masteryBuffs.values()) {
  		buffObj.attributableHealing = 0;
  	}
  }

  // TODO handle pre proc mastery buffs? Looks like pre-hots are already handled by the system.

  on_byPlayer_heal(event) {
    const spellId = event.ability.guid;
    const target = this.combatants.getEntity(event);
    const amount = event.amount + (event.absorbed === undefined ? 0 : event.absorbed);

    if(target === null) {
      return;
    }

    if(this.hotHealingMap.has(spellId)) {
      this.hotHealingMap.get(spellId).direct += amount;
    }

    if(ABILITIES_AFFECTED_BY_HEALING_INCREASES.includes(spellId)) {
      const hotsOn = target.activeBuffs()
          .map(buffObj => buffObj.ability.guid)
          .filter(buffId => HEALS_MASTERY_STACK.includes(buffId));
      const numHotsOn = hotsOn.length;
      const decomposedHeal = this._decompHeal(amount, numHotsOn);

      this.totalNoMasteryHealing += decomposedHeal.noMastery;
      this.druidSpellNoMasteryHealing += decomposedHeal.noMastery;
      this.masteryTimesHealing += decomposedHeal.noMastery * numHotsOn;

      hotsOn
          .filter(hotOn => hotOn !== spellId) // don't double count
          .forEach(hotOn => this.hotHealingMap.get(hotOn).mastery += decomposedHeal.oneStack);

/*
      for(let hotOn of hotsOn) {
        if(hotOn != spellId) { // don't double count
          this.hotHealingMap.get(hotOn).mastery += decomposedHeal.oneStack;
        }
      }
*/

      // TODO implement this part functionally too
      for(const [buffId, buffObj] of this.masteryBuffs.entries()) {
        if(this.combatants.selected.hasBuff(buffId)) {
          const attributableHealing = decomposedHeal.oneRating * buffObj.amount;
          buffObj.attributableHealing += attributableHealing;
        }
      }

    } else {
      this.totalNoMasteryHealing += amount;
    }
  }

  on_byPlayer_absorbed(event) {
    this.totalNoMasteryHealing += event.amount;
  }

  on_finished() {
    console.log("Mastery results: ");
    for(const hotObj of this.hotHealingMap.values()) {
      const directPerc = this.owner.getPercentageOfTotalHealingDone(hotObj.direct);
      const masteryPerc = this.owner.getPercentageOfTotalHealingDone(hotObj.mastery);
      console.log(hotObj.name + " - Direct:" + formatPercentage(directPerc) +
          "% Mastery:" + formatPercentage(masteryPerc) + "%");
    }

    const avgMasteryStacksAllHealing = this.masteryTimesHealing / this.totalNoMasteryHealing;
    const avgMasteryStacksDruidHealing = this.masteryTimesHealing / this.druidSpellNoMasteryHealing;

    console.log("Avg Mastery Stacks - All Healing:" + avgMasteryStacksAllHealing + " Druid Healing:" + avgMasteryStacksDruidHealing);
  }

  /* accessors for computed values */

  getDirectHealing(healId) {
    return this.hotHealingMap.get(healId).direct;
  }

  getMasteryHealing(healId) {
    return this.hotHealingMap.get(healId).mastery;
  }

  getBuffBenefit(buffId) {
    return this.masteryBuffs.get(buffId).attributableHealing;
  }

  _decompHeal(amount, hotCount) {
    const masteryBonus = this._getCurrMasteryBonus();
    const healMasteryMult = 1 + (hotCount * masteryBonus);

    const noMasteryHealing = amount / healMasteryMult;
    const oneStackMasteryHealing = noMasteryHealing * masteryBonus;
    const oneRatingMasteryHealing = noMasteryHealing * MASTERY_BONUS_FROM_ONE_RATING * hotCount;

    return {
      'noMastery': noMasteryHealing,
      'oneStack': oneStackMasteryHealing,
      'oneRating': oneRatingMasteryHealing,
    };
  }

  _getCurrMasteryBonus() {
    let baseMasteryRating = this.combatants.selected.masteryRating;
    for(const [buffId, buffObj] of this.masteryBuffs.entries()) {
      if(this.combatants.selected.hasBuff(buffId)) {
        baseMasteryRating += buffObj.amount;
      }
    }
    return BASE_MASTERY_PERCENT + (baseMasteryRating * MASTERY_BONUS_FROM_ONE_RATING);
  }

}

export default Mastery;
<commit_msg>Cleaned up commented code<commit_after>import {formatPercentage} from 'common/format';
import Module from 'Parser/Core/Module';
import SPELLS from 'common/SPELLS';
import Combatants from 'Parser/Core/Modules/Combatants';

import {ABILITIES_AFFECTED_BY_HEALING_INCREASES} from '../../Constants';
import {HEALS_MASTERY_STACK} from '../../Constants';

const MASTERY_BONUS_FROM_ONE_RATING = 1 / 66666.6666666;
const BASE_MASTERY_PERCENT = 0.048;

class Mastery extends Module {
  static dependencies = {
    combatants: Combatants,
  };

  totalNoMasteryHealing = 0;
  druidSpellNoMasteryHealing = 0;
  masteryTimesHealing = 0;

  hotHealingMap = null;
  masteryBuffs = null;

  on_initialized() {
    // TODO use JS objects instead of Maps for hotHealingMap and masteryBuffs?
    this.hotHealingMap = new Map();
    for(const healId of HEALS_MASTERY_STACK) {
      this.hotHealingMap.set(healId, {'name':SPELLS[healId].name, 'direct':0, 'mastery':0});
    }

    this.masteryBuffs = new Map([
        [ SPELLS.ASTRAL_HARMONY.id, { 'spell':SPELLS.ASTRAL_HARMONY, 'amount':4000 } ],
        [ SPELLS.JACINS_RUSE.id, { 'spell':SPELLS.JACINS_RUSE, 'amount':3000 } ],
    ]);
    for(const buffObj of this.masteryBuffs.values()) {
  		buffObj.attributableHealing = 0;
  	}
  }

  // TODO handle pre proc mastery buffs? Looks like pre-hots are already handled by the system.

  on_byPlayer_heal(event) {
    const spellId = event.ability.guid;
    const target = this.combatants.getEntity(event);
    const amount = event.amount + (event.absorbed === undefined ? 0 : event.absorbed);

    if(target === null) {
      return;
    }

    if(this.hotHealingMap.has(spellId)) {
      this.hotHealingMap.get(spellId).direct += amount;
    }

    if(ABILITIES_AFFECTED_BY_HEALING_INCREASES.includes(spellId)) {
      const hotsOn = target.activeBuffs()
          .map(buffObj => buffObj.ability.guid)
          .filter(buffId => HEALS_MASTERY_STACK.includes(buffId));
      const numHotsOn = hotsOn.length;
      const decomposedHeal = this._decompHeal(amount, numHotsOn);

      this.totalNoMasteryHealing += decomposedHeal.noMastery;
      this.druidSpellNoMasteryHealing += decomposedHeal.noMastery;
      this.masteryTimesHealing += decomposedHeal.noMastery * numHotsOn;

      hotsOn
          .filter(hotOn => hotOn !== spellId) // don't double count
          .forEach(hotOn => this.hotHealingMap.get(hotOn).mastery += decomposedHeal.oneStack);

      // TODO implement this part functionally too
      for(const [buffId, buffObj] of this.masteryBuffs.entries()) {
        if(this.combatants.selected.hasBuff(buffId)) {
          const attributableHealing = decomposedHeal.oneRating * buffObj.amount;
          buffObj.attributableHealing += attributableHealing;
        }
      }

    } else {
      this.totalNoMasteryHealing += amount;
    }
  }

  on_byPlayer_absorbed(event) {
    this.totalNoMasteryHealing += event.amount;
  }

  on_finished() {
    console.log("Mastery results: ");
    for(const hotObj of this.hotHealingMap.values()) {
      const directPerc = this.owner.getPercentageOfTotalHealingDone(hotObj.direct);
      const masteryPerc = this.owner.getPercentageOfTotalHealingDone(hotObj.mastery);
      console.log(hotObj.name + " - Direct:" + formatPercentage(directPerc) +
          "% Mastery:" + formatPercentage(masteryPerc) + "%");
    }

    const avgMasteryStacksAllHealing = this.masteryTimesHealing / this.totalNoMasteryHealing;
    const avgMasteryStacksDruidHealing = this.masteryTimesHealing / this.druidSpellNoMasteryHealing;

    console.log("Avg Mastery Stacks - All Healing:" + avgMasteryStacksAllHealing + " Druid Healing:" + avgMasteryStacksDruidHealing);
  }

  /* accessors for computed values */

  getDirectHealing(healId) {
    return this.hotHealingMap.get(healId).direct;
  }

  getMasteryHealing(healId) {
    return this.hotHealingMap.get(healId).mastery;
  }

  getBuffBenefit(buffId) {
    return this.masteryBuffs.get(buffId).attributableHealing;
  }

  _decompHeal(amount, hotCount) {
    const masteryBonus = this._getCurrMasteryBonus();
    const healMasteryMult = 1 + (hotCount * masteryBonus);

    const noMasteryHealing = amount / healMasteryMult;
    const oneStackMasteryHealing = noMasteryHealing * masteryBonus;
    const oneRatingMasteryHealing = noMasteryHealing * MASTERY_BONUS_FROM_ONE_RATING * hotCount;

    return {
      'noMastery': noMasteryHealing,
      'oneStack': oneStackMasteryHealing,
      'oneRating': oneRatingMasteryHealing,
    };
  }

  _getCurrMasteryBonus() {
    let baseMasteryRating = this.combatants.selected.masteryRating;
    for(const [buffId, buffObj] of this.masteryBuffs.entries()) {
      if(this.combatants.selected.hasBuff(buffId)) {
        baseMasteryRating += buffObj.amount;
      }
    }
    return BASE_MASTERY_PERCENT + (baseMasteryRating * MASTERY_BONUS_FROM_ONE_RATING);
  }

}

export default Mastery;
<|endoftext|>