<commit_before>/**
 * Camera that flies to ray-picked point on scene object
 *
 * @author xeolabs / http://xeolabs.com
 *
 *
Usage example

 *
 *
someNode.addNode({
 *      type: "cameras/pickFlyOrbit",
 *      eye:{ x: y:0 },
 *      look:{ y:0 },
 *      yaw: 340,,
 *      pitch: -20,
 *      zoom: 350,
 *      zoomSensitivity:10.0,
 *      showCursor: true
 * });
 *

 *
 *
The camera is initially positioned at the given 'eye' and 'look', then the distance of 'eye' is zoomed out
 * away from 'look' by the amount given in 'zoom', and then 'eye' is rotated by 'yaw' and 'pitch'.

 *
 */
require([
    SceneJS.getConfigs("pluginPath") + "/lib/gl-matrix-min.js"
],
    function (glmat) {

        // Create target indicator div

        var label = (function () {
            var text;
            var body = document.getElementsByTagName("body")[0];
            var div = document.createElement('div');

            var style = div.style;
            style.display = "none";
            style.position = "absolute";
            style["font-family"] = "Helvetica";
            style["font-size"] = "14px";
            style.padding = "5px";
            style.margin = "4px";
            style["padding-left"] = "12px";
            style["border"] = "1px solid #000055";
            style.color = "black";
            style.background = "#AAFFAA";
            style.opacity = "0.8";
            style["border-radius"] = "3px";
            style["z-index"] = 100000;
            style["-moz-border-radius"] = "3px";
            style["box-shadow"] = "3px 3px 3px #444444";
            style.left = "0";
            style.top = "0";
            style.height = "auto";
            style.width = "auto";
            div.innerHTML += 'Foo';
            body.appendChild(div);
            return {

                // Shows label, but only if text has been set
                setShown: function (shown) {
                    style.display = shown && text ? "" : "none";
                },

                // Sets canvas position of label
                setPos: function (pos) {
                    style.left = "" + pos.x + "px";
                    style.top = "" + pos.y + "px";
                },

                // Sets text in label
                setText: function (t) {
                    text = t;
                    div.innerHTML = "" + text + "";
                }
            }
        })();

        SceneJS.Types.addType("cameras/pickFlyOrbit", {

            construct: function (params) {

                var self = this;

                var lookat = this.addNode({
                    type: "lookAt",

                    nodes: [
                        {
                            type: "name",
                            name: "noname",

                            // A plugin node type is responsible for attaching specified
                            // child nodes within itself
                            nodes: params.nodes
                        }
                    ]
                });

                var indicatorPos;
                var indicatorVis;
                var indicatorSize;

                if (params.showCursor) {

                    // Red sphere to indicate current point-of-interest. We'll update the
                    // position of this whenever a new 3D position has been ray-picked.
                    // This will be the position about which we'll orbit.

                    // Sphere position, with a ID so we can update this node:
                    indicatorPos = lookat.addNode({
                        type: "translate",
                        id: "__spherePOI"
                    });

                    indicatorVis = indicatorPos.addNode({
                        type: "flags",
                        flags: {
                            enabled: false,
                            transparent: true,
                            specular: true,
                            diffuse: false
                        }
                    });

                    var cursorSize = params.cursorSize || 1;

                    indicatorSize = indicatorVis.addNode({
                        type: "scale",
                        id: "__sphereSize",
                        x: cursorSize,
                        y: cursorSize,
                        z: cursorSize,
                        nodes: [
                            {
                                type: "material",
                                color: { r: 0.4, g: 1.0, b: 0.4 },
                                specularColor: { r: 1.0, g: 1.0, b: 1.0 },
                                emit: 0.2,
                                nodes: [
                                    {
                                        type: "style",
                                        lineWidth: 2,
                                        nodes: [

                                            // Sphere primitive implemented by plugin at
                                            // http://scenejs.org/api/latest/plugins/node/geometry/sphere.js
                                            {
                                                type: "geometry/sphere"
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    });

                    this.getScene().getNode("__sphereSize", function (n) {
                        n.on("rendered",
                            function (event) {
                                label.setPos(event.getCanvasPos());
                            });
                    });
                }

                var eye = params.eye || { x: 0, y: 0, z: 0 };
                var look = params.look || { x: 0, y: 0, z: 0};
                var zoom = params.zoom || 100;
                var zoomSensitivity = params.zoomSensitivity || 1.0;

                var lookatArgs = {
                    eye: { x: eye.x, y: eye.y, z: eye.z},
                    look: { x: look.x, y: look.y, z: look.z },
                    up: { x: 0, y: 1, z: -zoom }
                };
                lookat.setEye(lookatArgs.eye);
                lookat.setLook(lookatArgs.look);
                lookat.setUp(lookatArgs.up);
                this.publish("updated", lookatArgs);

                var canvas = this.getScene().getCanvas();

                var downX;
                var downY;
                var lastX;
                var lastY;
                var dragging;

                var yaw = params.yaw || 0;
                var pitch = params.pitch || 0;

                var startPivot;
                var currentPivot = glmat.vec3.fromValues(look.x || 0, look.y || 0, look.z || 0);
                var endPivot = glmat.vec3.fromValues(look.x || 0, look.y || 0, look.z || 0);

                var flightStartTime = null;
                var flightDist;
                var flightDuration;
                var flying = false;
                var orbiting = true;

                function mouseDown(event) {
                    lastX = downX = event.clientX;
                    lastY = downY = event.clientY;
                    dragging = true;
                }

                function touchStart(event) {
                    lastX = downX = event.targetTouches[0].clientX;
                    lastY = downY = event.targetTouches[0].clientY;
                    dragging = true;
                }

                function mouseUp(event) {

                    if (dragging && closeEnough(event.clientX, downX) && closeEnough(event.clientY, downY)) {
                        pick(event.clientX, event.clientY);
                    }
                    dragging = false;
                }

                function closeEnough(x, y) {
                    return (x > y) ? (x - y < 5) : (y - x < 5);
                }

                function touchEnd(event) {
                    if (dragging && event.targetTouches[0].clientX == downX && event.targetTouches[0].clientY == downY) {
                        pick(event.targetTouches[0].clientX, event.targetTouches[0].clientY);
                    }
                    dragging = false;
                }

                function mouseMove(event) {
                    var posX = event.clientX;
                    var posY = event.clientY;
                    actionMove(posX, posY);
                }

                function touchMove(event) {
                    var posX = event.targetTouches[0].clientX;
                    var posY = event.targetTouches[0].clientY;
                    actionMove(posX, posY);
                }

                function actionMove(posX, posY) {
                    if (dragging) {
                        yaw -= (posX - lastX) * 0.1 ;
                        pitch -= (posY - lastY) * 0.1;
                        orbiting = true;
                    }
                    lastX = posX;
                    lastY = posY;
                }

                function mouseWheel(event) {
                    var delta = 0;
                    if (!event) event = window.event;
                    if (event.wheelDelta) {
                        delta = event.wheelDelta / 120;
                        if (window.opera) delta = -delta;
                    } else if (event.detail) {
                        delta = -event.detail / 3;
                    }
                    if (delta) {
                        if (delta < 0) {
                            zoom -= zoomSensitivity;
                        } else {
                            zoom += zoomSensitivity;
                        }
                    }
                    if (event.preventDefault) {
                        event.preventDefault();
                    }
                    event.returnValue = false;
                    orbiting = true;
                }

                canvas.addEventListener('mousedown', mouseDown, true);
                canvas.addEventListener('mouseup', mouseUp, true);
                canvas.addEventListener('touchstart', touchStart, true);
                canvas.addEventListener('touchend', touchEnd, true);
                canvas.addEventListener('mousemove', mouseMove, true);
                canvas.addEventListener('touchmove', touchMove, true);
                canvas.addEventListener('mousewheel', mouseWheel, true);
                canvas.addEventListener('DOMMouseScroll', mouseWheel, true);

                function pick(canvasX, canvasY) {
                    scene.pick({ canvasPos :[canvasX, canvasY], rayPick: true });
                }

                var scene = this.getScene();

                scene.on("pick",
                    function (hit) {

                        // Some plugins wrap things in this name to
                        // avoid them being picked, such as skyboxes
                        if (!hit.worldPos || hit.name == "__SceneJS_dontPickMe") {
                            return;
                        }

                        startPivot = glmat.vec3.fromValues(currentPivot[0], currentPivot[1], currentPivot[2]);
                        endPivot = hit.worldPos;

                        if (indicatorVis) {
                            indicatorVis.setEnabled(true);
                            indicatorPos.setXYZ({x: endPivot[0], y: endPivot[1], z: endPivot[2] });
                            label.setShown(true);
                        }

                        var vec = glmat.vec3.create();
                        glmat.vec3.sub(vec, endPivot, startPivot);

                        flightDist = glmat.vec3.length(vec);
                        flightStartTime = null;
                        flightDuration = 1000.0 * ((flightDist / 15000) + 1); // extra seconds to ensure arrival
                        flying = true;

                        label.setText("[ " + Math.round(endPivot[0]) + ", " + Math.round(endPivot[1]) + ", " + Math.round(endPivot[2]) + " ]");

                        scene.getNode(hit.name + "geometry",function (material) {
                            if(hisPick.name){
                                scene.getNode(hisPick.name + "geometry", function (material) {
                                    material.setColor(hisPick.color);//之前点过的东西还原
                                });
                            }
                            hisPick = {name:hit.name,color:material.getColor()}
                            material.setColor({r: 0.03137255, g: 0.30980392, b: 0.62745098});
                            var pTableScope= $('#pTable').scope();
                            pTableScope.oid = hit.name ;
                            $.ajax({
                          	  url:'./model/queryProperty.do',
                          	  type:'GET',
                          	  data:{oid:hit.name,rid:string}
                            }).done(function(data){
                          	  pTableScope.list = data.data
                          	  $('#pTable').scope().$apply();
                            })

                        });

                    });

                scene.on("tick",
                    function () {

                        if (flying) {

                            if (flightStartTime == null) {
                                flightStartTime = (new Date()).getTime();
                            }

                            var timeNow = (new Date()).getTime();
                            var timeElapsed = timeNow - flightStartTime;

                            if (timeElapsed >= flightDuration) {
                                flying = false;
                                flying = false;
                                flightStartTime = null;

                                // Hide pick indicator
                                if (indicatorVis) {
//                                    indicatorVis.setEnabled(false);
//                                    label.setShown(false);
                                }
                            } else {

                                var easedTime = easeOut((timeNow - flightStartTime) / flightDuration, 0, 1, 1);

                                // Continue flight
                                // Find new pivot point, interpolated on path towards new point

                                glmat.vec3.lerp(currentPivot, startPivot, endPivot, easedTime);

                                // Need to rotate lookat
                                orbiting = true;
                            }
                        }

                        if (orbiting) {

                            // Update location of point-of-interest indicator
                            if (indicatorVis) {
                                indicatorVis.setEnabled(true);
                                label.setShown(true);
                            }

                            var eye = glmat.vec3.fromValues(0, 0, zoom);
                            var look = glmat.vec3.fromValues(currentPivot[0], currentPivot[1], currentPivot[2]);
                            //var up = glmat.vec3.fromValues(0, 1, 0);

                            var eyeVec = glmat.vec3.create();
                            glmat.vec3.sub(eyeVec, eye, look);

                            var mat = glmat.mat4.create();

                            glmat.mat4.rotateY(mat, mat, -yaw * 0.0174532925);
                            glmat.mat4.rotateX(mat, mat, -pitch * 0.0174532925);

                            var eye3 = glmat.vec3.create();

                            glmat.vec3.transformMat4(eye3, eye, mat);

                            // Update view transform
                            lookat.setLook({x: look[0], y: look[1], z: look[2] });
                            lookat.setEye({x: look[0] - eye3[0], y: look[1] - eye3[1], z: look[2] - eye3[2] });

                            var lookatArgs = {
                                eye: {x: look[0], y: look[1], z: look[2] },
                                look: {x: look[0] - eye3[0], y: look[1] - eye3[1], z: look[2] - eye3[2] }
                            };

                            self.publish("updated", lookatArgs);

                            // Rotate complete
                            orbiting = false;

                            if (indicatorVis) {
                                setTimeout(function () {
                                    indicatorVis.setEnabled(false);
                                    label.setShown(false);
                                }, 2000);
                            }
                        }
                    });
            },

            destruct: function () {
                // TODO: remove mouse handlers
            }
        });

        function easeOut(t, b, c, d) {
            var ts = (t /= d) * t;
            var tc = ts * t;
            return b + c * (-1 * ts * ts + 4 * tc + -6 * ts + 4 * t);
        }

        function easeIn(t, b, c, d) {
            var ts = (t /= d) * t;
            var tc = ts * t;
            return b + c * (tc * ts);
        }

    });<commit_msg>前端代码帮小华提交<commit_after>/**
 * Camera that flies to ray-picked point on scene object
 *
 * @author xeolabs / http://xeolabs.com
 *
 *
Usage example

 *
 *
someNode.addNode({
 *      type: "cameras/pickFlyOrbit",
 *      eye:{ x: y:0 },
 *      look:{ y:0 },
 *      yaw: 340,,
 *      pitch: -20,
 *      zoom: 350,
 *      zoomSensitivity:10.0,
 *      showCursor: true
 * });
 *

 *
 *
The camera is initially positioned at the given 'eye' and 'look', then the distance of 'eye' is zoomed out
 * away from 'look' by the amount given in 'zoom', and then 'eye' is rotated by 'yaw' and 'pitch'.

 *
 */
require([
    SceneJS.getConfigs("pluginPath") + "/lib/gl-matrix-min.js"
],
    function (glmat) {

        // Create target indicator div

        var label = (function () {
            var text;
            var body = document.getElementsByTagName("body")[0];
            var div = document.createElement('div');

            var style = div.style;
            style.display = "none";
            style.position = "absolute";
            style["font-family"] = "Helvetica";
            style["font-size"] = "14px";
            style.padding = "5px";
            style.margin = "4px";
            style["padding-left"] = "12px";
            style["border"] = "1px solid #000055";
            style.color = "black";
            style.background = "#AAFFAA";
            style.opacity = "0.8";
            style["border-radius"] = "3px";
            style["z-index"] = 100000;
            style["-moz-border-radius"] = "3px";
            style["box-shadow"] = "3px 3px 3px #444444";
            style.left = "0";
            style.top = "0";
            style.height = "auto";
            style.width = "auto";
            div.innerHTML += 'Foo';
            body.appendChild(div);
            return {

                // Shows label, but only if text has been set
                setShown: function (shown) {
                    style.display = shown && text ? "" : "none";
                },

                // Sets canvas position of label
                setPos: function (pos) {
                    style.left = "" + pos.x + "px";
                    style.top = "" + pos.y + "px";
                },

                // Sets text in label
                setText: function (t) {
                    text = t;
                    div.innerHTML = "" + text + "";
                }
            }
        })();

        SceneJS.Types.addType("cameras/pickFlyOrbit", {

            construct: function (params) {

                var self = this;

                var lookat = this.addNode({
                    type: "lookAt",

                    nodes: [
                        {
                            type: "name",
                            name: "noname",

                            // A plugin node type is responsible for attaching specified
                            // child nodes within itself
                            nodes: params.nodes
                        }
                    ]
                });

                var indicatorPos;
                var indicatorVis;
                var indicatorSize;

                if (params.showCursor) {

                    // Red sphere to indicate current point-of-interest. We'll update the
                    // position of this whenever a new 3D position has been ray-picked.
                    // This will be the position about which we'll orbit.

                    // Sphere position, with a ID so we can update this node:
                    indicatorPos = lookat.addNode({
                        type: "translate",
                        id: "__spherePOI"
                    });

                    indicatorVis = indicatorPos.addNode({
                        type: "flags",
                        flags: {
                            enabled: false,
                            transparent: true,
                            specular: true,
                            diffuse: false
                        }
                    });

                    var cursorSize = params.cursorSize || 1;

                    indicatorSize = indicatorVis.addNode({
                        type: "scale",
                        id: "__sphereSize",
                        x: cursorSize,
                        y: cursorSize,
                        z: cursorSize,
                        nodes: [
                            {
                                type: "material",
                                color: { r: 0.4, g: 1.0, b: 0.4 },
                                specularColor: { r: 1.0, g: 1.0, b: 1.0 },
                                emit: 0.2,
                                nodes: [
                                    {
                                        type: "style",
                                        lineWidth: 2,
                                        nodes: [

                                            // Sphere primitive implemented by plugin at
                                            // http://scenejs.org/api/latest/plugins/node/geometry/sphere.js
                                            {
                                                type: "geometry/sphere"
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    });

                    this.getScene().getNode("__sphereSize", function (n) {
                        n.on("rendered",
                            function (event) {
                                label.setPos(event.getCanvasPos());
                            });
                    });
                }

                var eye = params.eye || { x: 0, y: 0, z: 0 };
                var look = params.look || { x: 0, y: 0, z: 0};
                var zoom = params.zoom || 100;
                var zoomSensitivity = params.zoomSensitivity || 1.0;

                var lookatArgs = {
                    eye: { x: eye.x, y: eye.y, z: eye.z},
                    look: { x: look.x, y: look.y, z: look.z },
                    up: { x: 0, y: 1, z: -zoom }
                };
                lookat.setEye(lookatArgs.eye);
                lookat.setLook(lookatArgs.look);
                lookat.setUp(lookatArgs.up);
                this.publish("updated", lookatArgs);

                var canvas = this.getScene().getCanvas();

                var downX;
                var downY;
                var lastX;
                var lastY;
                var dragging;

                var yaw = params.yaw || 0;
                var pitch = params.pitch || 0;

                var startPivot;
                var currentPivot = glmat.vec3.fromValues(look.x || 0, look.y || 0, look.z || 0);
                var endPivot = glmat.vec3.fromValues(look.x || 0, look.y || 0, look.z || 0);

                var flightStartTime = null;
                var flightDist;
                var flightDuration;
                var flying = false;
                var orbiting = true;

                function mouseDown(event) {
                    lastX = downX = event.clientX;
                    lastY = downY = event.clientY;
                    dragging = true;
                }

                function touchStart(event) {
                    lastX = downX = event.targetTouches[0].clientX;
                    lastY = downY = event.targetTouches[0].clientY;
                    dragging = true;
                }

                function mouseUp(event) {

                    if (dragging && closeEnough(event.clientX, downX) && closeEnough(event.clientY, downY)) {
                        pick(event.clientX, event.clientY);
                    }
                    dragging = false;
                }

                function closeEnough(x, y) {
                    return (x > y) ? (x - y < 5) : (y - x < 5);
                }

                function touchEnd(event) {
                    if (dragging && event.targetTouches[0].clientX == downX && event.targetTouches[0].clientY == downY) {
                        pick(event.targetTouches[0].clientX, event.targetTouches[0].clientY);
                    }
                    dragging = false;
                }

                function mouseMove(event) {
                    var posX = event.clientX;
                    var posY = event.clientY;
                    actionMove(posX, posY);
                }

                function touchMove(event) {
                    var posX = event.targetTouches[0].clientX;
                    var posY = event.targetTouches[0].clientY;
                    actionMove(posX, posY);
                }

                function actionMove(posX, posY) {
                    if (dragging) {
                        yaw -= (posX - lastX) * 0.1 ;
                        pitch -= (posY - lastY) * 0.1;
                        orbiting = true;
                    }
                    lastX = posX;
                    lastY = posY;
                }

                function mouseWheel(event) {
                    var delta = 0;
                    if (!event) event = window.event;
                    if (event.wheelDelta) {
                        delta = event.wheelDelta / 120;
                        if (window.opera) delta = -delta;
                    } else if (event.detail) {
                        delta = -event.detail / 3;
                    }
                    if (delta) {
                        if (delta < 0) {
                            zoom -= zoomSensitivity;
                        } else {
                            zoom += zoomSensitivity;
                        }
                    }
                    if (event.preventDefault) {
                        event.preventDefault();
                    }
                    event.returnValue = false;
                    orbiting = true;
                }

                canvas.addEventListener('mousedown', mouseDown, true);
                canvas.addEventListener('mouseup', mouseUp, true);
                canvas.addEventListener('touchstart', touchStart, true);
                canvas.addEventListener('touchend', touchEnd, true);
                canvas.addEventListener('mousemove', mouseMove, true);
                canvas.addEventListener('touchmove', touchMove, true);
                canvas.addEventListener('mousewheel', mouseWheel, true);
                canvas.addEventListener('DOMMouseScroll', mouseWheel, true);
                canvas.addEventListener('keydown', doKeyDown, true);
                window.addEventListener('keydown', doKeyDown, true);

                function doKeyDown(event){
                	var keyID = event.keyCode ? event.keyCode :event.which;
                	if(keyID === 38 || keyID === 87) { // up arrow and W
                		var xyz = lookat.getEye();
            			lookat.setEye({x: xyz.x, y:xyz.y+200, z: xyz.z })
                		event.preventDefault();
                	}
                	if(keyID === 39 || keyID === 68) { // right arrow and D
                		var xyz = lookat.getEye();
            			lookat.setEye({x: xyz.x+200, y:xyz.y, z: xyz.z })
                		event.preventDefault();
                	}
                	if(keyID === 40 || keyID === 83) { // down arrow and S

                		var xyz = lookat.getEye();
            			lookat.setEye({x: xyz.x, y:xyz.y-200, z: xyz.z })
                		event.preventDefault();
                	}
                	if(keyID === 37 || keyID === 65) { // left arrow and A

                		var xyz = lookat.getEye();
            			lookat.setEye({x: xyz.x-200, y:xyz.y, z: xyz.z })
                		event.preventDefault();
                	}
                }

                function pick(canvasX, canvasY) {
                    scene.pick({ canvasPos :[canvasX, canvasY], rayPick: true });
                }

                var scene = this.getScene();

                scene.on("pick",
                    function (hit) {

                        // Some plugins wrap things in this name to
                        // avoid them being picked, such as skyboxes
                        if (!hit.worldPos || hit.name == "__SceneJS_dontPickMe") {
                            return;
                        }

                        startPivot = glmat.vec3.fromValues(currentPivot[0], currentPivot[1], currentPivot[2]);
                        endPivot = hit.worldPos;

                        if (indicatorVis) {
                            indicatorVis.setEnabled(true);
                            indicatorPos.setXYZ({x: endPivot[0], y: endPivot[1], z: endPivot[2] });
                            label.setShown(true);
                        }

                        var vec = glmat.vec3.create();
                        glmat.vec3.sub(vec, endPivot, startPivot);

                        flightDist = glmat.vec3.length(vec);
                        flightStartTime = null;
                        flightDuration = 1000.0 * ((flightDist / 15000) + 1); // extra seconds to ensure arrival
                        flying = true;

                        label.setText("[ " + Math.round(endPivot[0]) + ", " + Math.round(endPivot[1]) + ", " + Math.round(endPivot[2]) + " ]");

                        scene.getNode(hit.name + "geometry",function (material) {
                            if(hisPick.name){
                                scene.getNode(hisPick.name + "geometry", function (material) {
                                    material.setColor(hisPick.color);//之前点过的东西还原
                                });
                            }
                            hisPick = {name:hit.name,color:material.getColor()}
                            material.setColor({r: 0.03137255, g: 0.30980392, b: 0.62745098});
                            var pTableScope= $('#pTable').scope();
                            pTableScope.oid = hit.name ;
                            $.ajax({
                          	  url:'./model/queryProperty.do',
                          	  type:'GET',
                          	  data:{oid:hit.name,rid:string}
                            }).done(function(data){
                          	  pTableScope.list = data.data
                          	  $('#pTable').scope().$apply();
                            })

                        });

                    });

                scene.on("tick",
                    function () {

                        if (flying) {

                            if (flightStartTime == null) {
                                flightStartTime = (new Date()).getTime();
                            }

                            var timeNow = (new Date()).getTime();
                            var timeElapsed = timeNow - flightStartTime;

                            if (timeElapsed >= flightDuration) {
                                flying = false;
                                flying = false;
                                flightStartTime = null;

                                // Hide pick indicator
                                if (indicatorVis) {
//                                    indicatorVis.setEnabled(false);
//                                    label.setShown(false);
                                }
                            } else {

                                var easedTime = easeOut((timeNow - flightStartTime) / flightDuration, 0, 1, 1);

                                // Continue flight
                                // Find new pivot point, interpolated on path towards new point

                                glmat.vec3.lerp(currentPivot, startPivot, endPivot, easedTime);

                                // Need to rotate lookat
                                orbiting = true;
                            }
                        }

                        if (orbiting) {

                            // Update location of point-of-interest indicator
                            if (indicatorVis) {
                                indicatorVis.setEnabled(true);
                                label.setShown(true);
                            }

                            var eye = glmat.vec3.fromValues(0, 0, zoom);
                            var look = glmat.vec3.fromValues(currentPivot[0], currentPivot[1], currentPivot[2]);
                            //var up = glmat.vec3.fromValues(0, 1, 0);

                            var eyeVec = glmat.vec3.create();
                            glmat.vec3.sub(eyeVec, eye, look);

                            var mat = glmat.mat4.create();

                            glmat.mat4.rotateY(mat, mat, -yaw * 0.0174532925);
                            glmat.mat4.rotateX(mat, mat, -pitch * 0.0174532925);

                            var eye3 = glmat.vec3.create();

                            glmat.vec3.transformMat4(eye3, eye, mat);

                            // Update view transform
                            lookat.setLook({x: look[0], y: look[1], z: look[2] });
                            lookat.setEye({x: look[0] - eye3[0], y: look[1] - eye3[1], z: look[2] - eye3[2] });

                            var lookatArgs = {
                                eye: {x: look[0], y: look[1], z: look[2] },
                                look: {x: look[0] - eye3[0], y: look[1] - eye3[1], z: look[2] - eye3[2] }
                            };

                            self.publish("updated", lookatArgs);

                            // Rotate complete
                            orbiting = false;

                            if (indicatorVis) {
                                setTimeout(function () {
                                    indicatorVis.setEnabled(false);
                                    label.setShown(false);
                                }, 2000);
                            }
                        }
                    });
            },

            destruct: function () {
                // TODO: remove mouse handlers
            }
        });

        function easeOut(t, b, c, d) {
            var ts = (t /= d) * t;
            var tc = ts * t;
            return b + c * (-1 * ts * ts + 4 * tc + -6 * ts + 4 * t);
        }

        function easeIn(t, b, c, d) {
            var ts = (t /= d) * t;
            var tc = ts * t;
            return b + c * (tc * ts);
        }

    });<|endoftext|>


<commit_before>/*
 * Q-municate chat application
 *
 * Message Module
 *
 */

define(function() {

  function Message(app) {
    this.app = app;
    this.skip = {};
  }

  Message.prototype = {

    download: function(dialog_id, callback, count, isAjaxDownloading) {
      var QBApiCalls = this.app.service,
          DialogView = this.app.views.Dialog,
          self = this;

      if (self.skip[dialog_id] && self.skip[dialog_id] === count) return false;

      if (isAjaxDownloading) DialogView.createDataSpinner(null, null, true);
      QBApiCalls.listMessages({chat_dialog_id: dialog_id, sort_desc: 'date_sent', limit: 50, skip: count || 0}, function(messages) {
        if (isAjaxDownloading) DialogView.removeDataSpinner();
        callback(messages);
        self.skip[dialog_id] = count;
      });
    },

    create: function(params) {
      var User = this.app.models.User,
          message;

      message = {
        id: (params.extension && params.extension.message_id) || params._id || null,
        dialog_id: (params.extension && params.extension.dialog_id) || params.chat_dialog_id,
        body: params.body || params.message || null,
        notification_type: (params.extension && params.extension.notification_type) || params.notification_type || null,
        date_sent: (params.extension && params.extension.date_sent) || params.date_sent,
        read: params.read || false,
        attachment: (params.extension && params.extension.attachments && params.extension.attachments[0]) || (params.attachments && params.attachments[0]) || params.attachment || null,
        sender_id: params.sender_id || null,
        recipient_id: params.recipient_id || null,
        current_occupant_ids: (params.extension && params.extension.current_occupant_ids) || params.current_occupant_ids || null,
        added_occupant_ids: (params.extension && params.extension.added_occupant_ids) || params.added_occupant_ids || null,
        deleted_occupant_ids: (params.extension && params.extension.deleted_occupant_ids) || params.deleted_occupant_ids || null,
        room_name: (params.extension && params.extension.room_name) || params.room_name || null,
        room_photo: (params.extension && params.extension.room_photo && params.extension.room_photo.replace('http://', 'https://')) ||
                    (params.room_photo && params.room_photo.replace('http://', 'https://')) || null,
        room_updated_date: (params.extension && params.extension.room_updated_date) || params.room_updated_date || null,
        dialog_update_info: (params.extension && params.extension.dialog_update_info) || params.dialog_update_info || null,
        callType: (params.extension && params.extension.callType) || params.callType || null,
        callState: (params.extension && params.extension.callState) || params.callState || null,
        caller: parseInt((params.extension && params.extension.caller)) || parseInt(params.caller) || null,
        callee: parseInt((params.extension && params.extension.callee)) || parseInt(params.callee) || null,
        duration: (params.extension && params.extension.duration) || params.duration || null,
        sessionID: (params.extension && params.extension.sessionID) || params.sessionID || null,
        read_ids: (params.extension && params.extension.read_ids) || params.read_ids || null,
        delivered_ids: (params.delivered_ids && params.extension.delivered_ids) || params.delivered_ids || null
      };

      if (message.attachment) {
        message.attachment.size = parseInt(message.attachment.size);
      }

      return message;
    },

    update: function(message_id, dialog_id) {
      var QBApiCalls = this.app.service;

      QBApiCalls.updateMessage(message_id, {chat_dialog_id: dialog_id, read: 1}, function() {

      });
    }

  };

  return Message;

});
<commit_msg>fix for dialog select<commit_after>/*
 * Q-municate chat application
 *
 * Message Module
 *
 */

define(function() {

  function Message(app) {
    this.app = app;
    this.skip = {};
  }

  Message.prototype = {

    download: function(dialog_id, callback, count, isAjaxDownloading) {
      var QBApiCalls = this.app.service,
          DialogView = this.app.views.Dialog,
          self = this;

      if (self.skip[dialog_id] && self.skip[dialog_id] === count) return false;

      if (isAjaxDownloading) DialogView.createDataSpinner(null, null, true);
      QBApiCalls.listMessages({chat_dialog_id: dialog_id, sort_desc: 'date_sent', limit: 50, skip: count || 0}, function(messages) {
        if (isAjaxDownloading) DialogView.removeDataSpinner();
        callback(messages);
        self.skip[dialog_id] = count;
      });
    },

    create: function(params) {
      var User = this.app.models.User,
          message;

      message = {
        id: (params.extension && params.extension.message_id) || params._id || null,
        dialog_id: (params.extension && params.extension.dialog_id) || params.chat_dialog_id,
        body: params.body || params.message || null,
        notification_type: (params.extension && params.extension.notification_type) || params.notification_type || null,
        date_sent: (params.extension && params.extension.date_sent) || params.date_sent,
        read: params.read || false,
        attachment: (params.extension && params.extension.attachments && params.extension.attachments[0]) || (params.attachments && params.attachments[0]) || params.attachment || null,
        sender_id: params.sender_id || null,
        recipient_id: params.recipient_id || null,
        current_occupant_ids: (params.extension && params.extension.current_occupant_ids) || params.current_occupant_ids || null,
        added_occupant_ids: (params.extension && params.extension.added_occupant_ids) || params.added_occupant_ids || null,
        deleted_occupant_ids: (params.extension && params.extension.deleted_occupant_ids) || params.deleted_occupant_ids || null,
        room_name: (params.extension && params.extension.room_name) || params.room_name || null,
        room_photo: (params.extension && params.extension.room_photo && params.extension.room_photo.replace('http://', 'https://')) ||
                    (params.room_photo && params.room_photo.replace('http://', 'https://')) || null,
        room_updated_date: (params.extension && params.extension.room_updated_date) || params.room_updated_date || null,
        dialog_update_info: (params.extension && params.extension.dialog_update_info) || params.dialog_update_info || null,
        callType: (params.extension && params.extension.callType) || params.callType || null,
        callState: (params.extension && params.extension.callState) || params.callState || null,
        caller: parseInt((params.extension && params.extension.caller)) || parseInt(params.caller) || null,
        callee: parseInt((params.extension && params.extension.callee)) || parseInt(params.callee) || null,
        duration: (params.extension && params.extension.duration) || params.duration || null,
        sessionID: (params.extension && params.extension.sessionID) || params.sessionID || null
        // read_ids: (params.extension && params.extension.read_ids) || params.read_ids || null,
        // delivered_ids: (params.delivered_ids && params.extension.delivered_ids) || params.delivered_ids || null
      };

      if (message.attachment) {
        message.attachment.size = parseInt(message.attachment.size);
      }

      return message;
    },

    update: function(message_id, dialog_id) {
      var QBApiCalls = this.app.service;

      QBApiCalls.updateMessage(message_id, {chat_dialog_id: dialog_id, read: 1}, function() {

      });
    }

  };

  return Message;

});
<|endoftext|>


<commit_before>Ext.namespace('Vps.GoogleMap');
Vps.GoogleMap.isLoaded = false;
Vps.GoogleMap.isCallbackCalled = false;
Vps.GoogleMap.callbacks = [];

Vps.GoogleMap.load = function(callback, scope)
{
    if (Vps.GoogleMap.isCallbackCalled) {
        callback.call(scope || window);
        return;
    }
    if (Vps.GoogleMap.isLoaded) return;

    Vps.GoogleMap.isLoaded = true;
    Vps.GoogleMap.callbacks.push({
        callback: callback,
        scope: scope
    });

    var url = 'http://maps.google.com/maps?file=api&v=2.x&key={$googleMapsApiKey}&c&async=2';
    url += '&callback=Vps.GoogleMap._loaded';
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', url);
    document.getElementsByTagName("head")[0].appendChild(s);
};

Vps.GoogleMap._loaded = function()
{
    Vps.GoogleMap.isCallbackCalled = true;
    Vps.GoogleMap.callbacks.forEach(function(i) {
        i.callback.call(i.scope || window);
    });
};
<commit_msg>fix fuer js-komprimierer<commit_after>Ext.namespace('Vps.GoogleMap');
Vps.GoogleMap.isLoaded = false;
Vps.GoogleMap.isCallbackCalled = false;
Vps.GoogleMap.callbacks = [];

Vps.GoogleMap.load = function(callback, scope)
{
    if (Vps.GoogleMap.isCallbackCalled) {
        callback.call(scope || window);
        return;
    }
    if (Vps.GoogleMap.isLoaded) return;

    Vps.GoogleMap.isLoaded = true;
    Vps.GoogleMap.callbacks.push({
        callback: callback,
        scope: scope
    });

    var url = 'http:/'+'/maps.google.com/maps?file=api&v=2.x&key={$googleMapsApiKey}&c&async=2';
    url += '&callback=Vps.GoogleMap._loaded';
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', url);
    document.getElementsByTagName("head")[0].appendChild(s);
};

Vps.GoogleMap._loaded = function()
{
    Vps.GoogleMap.isCallbackCalled = true;
    Vps.GoogleMap.callbacks.forEach(function(i) {
        i.callback.call(i.scope || window);
    });
};
<|endoftext|>


<commit_before>$(document).ready(function() {
// static stuff
var ref = new Firebase("***firebase-url***");
var socket = io();
var canPost = true;
var authData;
var lastUser;
var unreadMessages =  false;
var soundEnabledText = "Sound enabled";
var soundDisabledText = "Mentions Only";
var lostConnection = false;
var ServerUser = {name: "Server", tags: "Server", image: "", colour: "inherit"};

var msgbox = $("#message");

$('.helpButton').click(function() {
  $('.about-box').fadeIn(function() {
    $('.close-button').click(function() {
      $('.about-box').fadeOut()
    });
  })
});

function updateSoundPrefButton(){
  // Check localstorage
  if (localStorage.getItem("soundPref") === null){
    localStorage.setItem("soundPref", 1)
  }else if (localStorage.getItem("soundPref") == 1){
    document.getElementById("soundPref").innerHTML = soundEnabledText;
  }else{
    document.getElementById("soundPref").innerHTML = soundDisabledText;
  }
}
updateSoundPrefButton();

$("#soundPref").click(toggleSoundPref);

function toggleSoundPref(){
  if (localStorage.getItem("soundPref") == "1"){
    localStorage.setItem("soundPref", 0);
  } else {
    localStorage.setItem("soundPref", 1);
  }

  updateSoundPrefButton()
}

function updateTitle() {
  var title= $(document).find("title");
  console.log(title);
  if (unreadMessages){
    if (title.text().charAt(0) != "*" ){
      title.text("* " + title.text())
    }
  }else{
    if (title.text().charAt(0) == "*"){
      title.text(title.text().substring(2));
    }
  }
}

window.onfocus = function() {
  unreadMessages = false;
  updateTitle();
};

//function showMessage(msg, user, tags, imageLink, colour) {
//  msg = emojione.toImage(msg);
//
//  var messageElement;
//  if (user == 'RubyBot' && lastUser != 'RubyBot') {
//    messageElement = $('
').html(
//      '' +
//      '
' +
//      '@' + user + '' + tags + '' +
//      '
' + msg + '

'
//    );
//
//  } else if (user == 'Server') {
//    messageElement = $('
').html('' + user + '' + ': ' + msg);
//
//  } else {
//    if (user == lastUser) {
//      messageElement = $('#messages li').last();
//      messageElement.find(".message").append("
" + msg + "
");
//    } else if (!imageLink || imageLink == ''){
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    } else {
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    }
//
//
//  }
//  lastUser = user;
//  messageElement.linkify({
//    target: "_blank"
//  });
//
//  $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
//
//  if (document.hasFocus() == false){
//    unreadMessages = true;
//    updateTitle();
//    var nameFormatted = authData.twitter.username;
//    if (msg.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
//        var audio = new Audio('/assets/sound/Ding.mp3');
//        audio.play();
//    }else{
//      if (localStorage.getItem("soundPref") == "1"){
//        var audio = new Audio('/assets/sound/pop.ogg');
//        audio.play();
//      }
//    }
//  }
//}
function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  if (hours.length == 1){
    hours = "0" + hours
  }
  if (minutes.length == 1){
    minutes = "0" + minutes
  }
  return hours + ":" + minutes
}

function SayAsServer(message){
  showMessage({text: message, timestamp: Date.now()}, ServerUser)
}

function getUsers(socket){
  socket.emit("get users", authData.token, function(users){
    $('#userlist').empty();
    users.data.forEach(function(user){
      $('#userlist').append("
@"+user.name+"
");
    });
  });
}

function showMessage(message, user){
  message.text = emojione.toImage(message.text);

  var msgClass = "msg";
  var hasImage = Boolean(user.image);
  var wasLastUser = lastUser == user.name;
  var canTweet = true;
  console.log(user);

  var twitterUser = user.name;
  var href = "https://twitter.com/"+ user + "/";

  if (user.name == "Server"){
    msgClass = "server-msg";
    hasImage = false;
    wasLastUser = false;
    canTweet = false;
    href = "http://yrs.io";
  } else if (user.name == "RubyBot") {
    msgClass = "bot-msg";
    canTweet = false;
    href = "http://twitter.com/YRSChat"
  }

  var messageElement = $('
');

  if (!wasLastUser) {
    if (hasImage) {
      messageElement.html('')
    }

    messageElement.html(messageElement.html()+
      '
' +
      '' + '@' + user.name + '' +
      '' + user.tags + '' + formatTimestamp(message.timestamp) + '' +
      '
' + message.text + '
'
    );

    if(canTweet){
      messageElement.html(messageElement.html() + '' +
        'Tweet'
      )
    }

    messageElement.html(messageElement.html() + '
');
  } else {
    messageElement = $('#messages li').last();

    if (canTweet){
      messageElement.find(".message").append(
        "
" + message.text + "
" +
        '' +
        'Tweet'
      );
    }
  }

  lastUser = user.name;
  messageElement.linkify({
    target: "_blank"
  });

  if (!wasLastUser){
    $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
  }

  if(canTweet){
    twttr.widgets.load()
  }

  if (!document.hasFocus()){
    unreadMessages = true;
    updateTitle();
    var nameFormatted = authData.twitter.username;
    if (message.text.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
        var audio = new Audio('/assets/sound/Ding.mp3');
        audio.play();
    }else{
      if (localStorage.getItem("soundPref") == "1"){
        var audio = new Audio('/assets/sound/pop.ogg');
        audio.play();
      }
    }
  }
}

// firebase stuff
ref.onAuth(function(data) {
  authData = data;
  if (!data){
    $('.twitter').css("display", "block")
  } else {
    socket.emit("user join", data.token, data.twitter.username, data.twitter.profileImageURL);
  }
});

$('#twitter-button').click(function() {
  ref.authWithOAuthPopup("twitter", function(error, data) {
    if (error) {
      console.log("Login Failed!", error);
    } else {
      $('.twitter').fadeOut()
    }
  });
  return false;
});

ref.getAuth();

$('form').submit(function(){
  if(canPost == false){
    showMessage('Please do not spam!', 'Server', '');
  } else {
    socket.emit('chat message',
      msgbox.val(),
      authData.token,
      function(response) {
        if (response.status == "failed"){
          showMessage(response.message, ServerUser);
        }
      }
    );
    canPost=false;
    setTimeout(function(){canPost=true},500);
  }
  msgbox.val('');
  return false;
});

socket.on("connect", function(){
  if (!authData) return;
  if (!lostConnection) return;
  SayAsServer("You have reconnected to the server.");
  socket.emit("user join", authData.token, authData.twitter.username, authData.twitter.profileImageURL);
  lostConnection = false;
});

socket.on("disconnect", function(){
  SayAsServer("You have been temporarlly disconnected from the server.");
  lostConnection = true;
});

socket.on('chat message', function(message, user) {
  showMessage(message, user);
});

socket.on("user join", function(user) {
  SayAsServer(user.name + " has joined!")
  getUsers(socket);
});

socket.on("user leave", function(user) {
  SayAsServer(user.name + " has left.")
  getUsers(socket);
});

window.setInterval(function() {
  socket.emit("user ping", authData.token)
  getUsers(socket);
}, 5000);

$(window).unload(function() {
  socket.emit("user leave", authData.token);
})
});

window.onbeforeunload = function(){
    return "Closing the window will disconnect your from YRS Chat";
};
<commit_msg>Removed debug code<commit_after>$(document).ready(function() {
// static stuff
var ref = new Firebase("***firebase-url***");
var socket = io();
var canPost = true;
var authData;
var lastUser;
var unreadMessages =  false;
var soundEnabledText = "Sound enabled";
var soundDisabledText = "Mentions Only";
var lostConnection = false;
var ServerUser = {name: "Server", tags: "Server", image: "", colour: "inherit"};

var msgbox = $("#message");

$('.helpButton').click(function() {
  $('.about-box').fadeIn(function() {
    $('.close-button').click(function() {
      $('.about-box').fadeOut()
    });
  })
});

function updateSoundPrefButton(){
  // Check localstorage
  if (localStorage.getItem("soundPref") === null){
    localStorage.setItem("soundPref", 1)
  }else if (localStorage.getItem("soundPref") == 1){
    document.getElementById("soundPref").innerHTML = soundEnabledText;
  }else{
    document.getElementById("soundPref").innerHTML = soundDisabledText;
  }
}
updateSoundPrefButton();

$("#soundPref").click(toggleSoundPref);

function toggleSoundPref(){
  if (localStorage.getItem("soundPref") == "1"){
    localStorage.setItem("soundPref", 0);
  } else {
    localStorage.setItem("soundPref", 1);
  }

  updateSoundPrefButton()
}

function updateTitle() {
  var title= $(document).find("title");
  if (unreadMessages){
    if (title.text().charAt(0) != "*" ){
      title.text("* " + title.text())
    }
  }else{
    if (title.text().charAt(0) == "*"){
      title.text(title.text().substring(2));
    }
  }
}

window.onfocus = function() {
  unreadMessages = false;
  updateTitle();
};

//function showMessage(msg, user, tags, imageLink, colour) {
//  msg = emojione.toImage(msg);
//
//  var messageElement;
//  if (user == 'RubyBot' && lastUser != 'RubyBot') {
//    messageElement = $('
').html(
//      '' +
//      '
' +
//      '@' + user + '' + tags + '' +
//      '
' + msg + '

'
//    );
//
//  } else if (user == 'Server') {
//    messageElement = $('
').html('' + user + '' + ': ' + msg);
//
//  } else {
//    if (user == lastUser) {
//      messageElement = $('#messages li').last();
//      messageElement.find(".message").append("
" + msg + "
");
//    } else if (!imageLink || imageLink == ''){
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    } else {
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    }
//
//
//  }
//  lastUser = user;
//  messageElement.linkify({
//    target: "_blank"
//  });
//
//  $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
//
//  if (document.hasFocus() == false){
//    unreadMessages = true;
//    updateTitle();
//    var nameFormatted = authData.twitter.username;
//    if (msg.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
//        var audio = new Audio('/assets/sound/Ding.mp3');
//        audio.play();
//    }else{
//      if (localStorage.getItem("soundPref") == "1"){
//        var audio = new Audio('/assets/sound/pop.ogg');
//        audio.play();
//      }
//    }
//  }
//}
function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  if (hours.length == 1){
    hours = "0" + hours
  }
  if (minutes.length == 1){
    minutes = "0" + minutes
  }
  return hours + ":" + minutes
}

function SayAsServer(message){
  showMessage({text: message, timestamp: Date.now()}, ServerUser)
}

function getUsers(socket){
  socket.emit("get users", authData.token, function(users){
    $('#userlist').empty();
    users.data.forEach(function(user){
      $('#userlist').append("
@"+user.name+"
");
    });
  });
}

function showMessage(message, user){
  message.text = emojione.toImage(message.text);

  var msgClass = "msg";
  var hasImage = Boolean(user.image);
  var wasLastUser = lastUser == user.name;
  var canTweet = true;
  console.log(user);

  var twitterUser = user.name;
  var href = "https://twitter.com/"+ user + "/";

  if (user.name == "Server"){
    msgClass = "server-msg";
    hasImage = false;
    wasLastUser = false;
    canTweet = false;
    href = "http://yrs.io";
  } else if (user.name == "RubyBot") {
    msgClass = "bot-msg";
    canTweet = false;
    href = "http://twitter.com/YRSChat"
  }

  var messageElement = $('
');

  if (!wasLastUser) {
    if (hasImage) {
      messageElement.html('')
    }

    messageElement.html(messageElement.html()+
      '
' +
      '' + '@' + user.name + '' +
      '' + user.tags + '' + formatTimestamp(message.timestamp) + '' +
      '
' + message.text + '
'
    );

    if(canTweet){
      messageElement.html(messageElement.html() + '' +
        'Tweet'
      )
    }

    messageElement.html(messageElement.html() + '
');
  } else {
    messageElement = $('#messages li').last();

    if (canTweet){
      messageElement.find(".message").append(
        "
" + message.text + "
" +
        '' +
        'Tweet'
      );
    }
  }

  lastUser = user.name;
  messageElement.linkify({
    target: "_blank"
  });

  if (!wasLastUser){
    $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
  }

  if(canTweet){
    twttr.widgets.load()
  }

  if (!document.hasFocus()){
    unreadMessages = true;
    updateTitle();
    var nameFormatted = authData.twitter.username;
    if (message.text.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
        var audio = new Audio('/assets/sound/Ding.mp3');
        audio.play();
    }else{
      if (localStorage.getItem("soundPref") == "1"){
        var audio = new Audio('/assets/sound/pop.ogg');
        audio.play();
      }
    }
  }
}

// firebase stuff
ref.onAuth(function(data) {
  authData = data;
  if (!data){
    $('.twitter').css("display", "block")
  } else {
    socket.emit("user join", data.token, data.twitter.username, data.twitter.profileImageURL);
  }
});

$('#twitter-button').click(function() {
  ref.authWithOAuthPopup("twitter", function(error, data) {
    if (error) {
      console.log("Login Failed!", error);
    } else {
      $('.twitter').fadeOut()
    }
  });
  return false;
});

ref.getAuth();

$('form').submit(function(){
  if(canPost == false){
    showMessage('Please do not spam!', 'Server', '');
  } else {
    socket.emit('chat message',
      msgbox.val(),
      authData.token,
      function(response) {
        if (response.status == "failed"){
          showMessage(response.message, ServerUser);
        }
      }
    );
    canPost=false;
    setTimeout(function(){canPost=true},500);
  }
  msgbox.val('');
  return false;
});

socket.on("connect", function(){
  if (!authData) return;
  if (!lostConnection) return;
  SayAsServer("You have reconnected to the server.");
  socket.emit("user join", authData.token, authData.twitter.username, authData.twitter.profileImageURL);
  lostConnection = false;
});

socket.on("disconnect", function(){
  SayAsServer("You have been temporarlly disconnected from the server.");
  lostConnection = true;
});

socket.on('chat message', function(message, user) {
  showMessage(message, user);
});

socket.on("user join", function(user) {
  SayAsServer(user.name + " has joined!")
  getUsers(socket);
});

socket.on("user leave", function(user) {
  SayAsServer(user.name + " has left.")
  getUsers(socket);
});

window.setInterval(function() {
  socket.emit("user ping", authData.token)
  getUsers(socket);
}, 5000);

$(window).unload(function() {
  socket.emit("user leave", authData.token);
})
});

window.onbeforeunload = function(){
    return "Closing the window will disconnect your from YRS Chat";
};
<|endoftext|>


<commit_before>/**
 * Author: krasu
 * Date: 8/13/13
 * Time: 1:33 AM
 */
define(function (require) {
	require('backbone')

	var toastr = require('toastr')
	var store = require('store').getNamespace('repo-selector')
	var tpl = require('tpl!../templates/layout.html')
	var selectorTpl = require('tpl!../templates/support-selector.html')
	var shareTpl = require('tpl!../templates/share.html')

	return Backbone.View.extend({
		events: {
			'click .share-trigger': 'toggleShare',
			'click .nav-tabs .tab': 'selectTab',
			'click .support-selector a[role="menuitem"]': 'select'
		},
		select: function (event) {
			var el = $(event.currentTarget)
			this.$('.support-selector').find('.value').text(el.data().val || el.text())
		},
		selectTab: function (event) {
			event.preventDefault()
			var tab = $(event.currentTarget).attr('href').replace('#', '')
			store().router.navigate(
				'/type/' + store().currentType.type + '/id/' + store().currentType.id + '/tab/' + tab,
				{trigger: true}
			)
		},
		initialize: function () {
			this.listenTo(store().hub, 'repos-loaded', this.loadedRepoList)

			this.listenTo(store().selected, 'add remove', this.updateSelectedCount)
			this.listenTo(store().selected, 'add', this.addHeart)
			this.listenTo(store().selected, 'remove', this.removeHeart)

			this.listenTo(store().selected, 'prefetch', this.showLoading)
			this.listenTo(store().selected, 'fetched', this.hideLoading)
			this.listenTo(store().groups, 'sync', this.showSelector)
			this.render()
		},
		hideLoading: function () {
			this.$('.loading').hide()
			this.$('.content').slideDown()

			var link = this.getProjectLink()
			this.$('.share').html(shareTpl({
				shareLink: link
			}))
			this.$('.preview').attr('href', link)
		},
		getProjectLink: function () {
			var link = []

			if (store().currentType.type == 'organization') {
				link.push('orgs')
			} else if (store().currentType.type == 'project') {
				link.push('projects')
			} else {
				link.push('users')
			}

			if (store().currentType.type != 'user') {
				link.push(store().currentType.id)
			} else {
				link.push(currentUserName)
			}

			return link.join('/')
		},
		showLoading: function () {
			this.$('.loading').show()
			this.$('.content').slideUp()
		},
		showSelector: function () {
			this.$('.support-selector').html(selectorTpl({
				groups: store().groups.toJSON(),
				current: store().currentType
			}))
		},
		updateSelectedCount: function (model, collection) {
			this.$('#selected-count').text(collection.length)
		},
		addHeart: function () {
			if (!store().groups.currentHasSupport()) {
				store().groups.updateCurrentSupport(true)
				this.showSelector()
			}
		},
		removeHeart: function (model, collection) {
			if (collection.length) return
			store().groups.updateCurrentSupport(false)
			this.showSelector()
		},
		toggleShare: function () {
			var btn = this.$('.share-trigger'),
				altText = btn.data().altText,
				el = this.$('.share')

			if (!el.is(':visible')) {
				el.slideDown()
			} else {
				el.slideUp()
			}

			btn.data().altText = btn.text()
			btn.text(altText)
		},
		render: function () {
			var self = this
			this.$('.loading').hide()
			this.$('.content').html(tpl()).slideDown()
			this.updateSelectedCount(null, store().selected)
		},
		loadedRepoList: function (collection, type) {
			if (type == 'search') return
			this.$('.nav .tab[href="#' + type + '-repos"]').parent().removeClass('disabled')
		}
	});
})<commit_msg>preview button now updating<commit_after>/**
 * Author: krasu
 * Date: 8/13/13
 * Time: 1:33 AM
 */
define(function (require) {
	require('backbone')

	var toastr = require('toastr')
	var store = require('store').getNamespace('repo-selector')
	var tpl = require('tpl!../templates/layout.html')
	var selectorTpl = require('tpl!../templates/support-selector.html')
	var shareTpl = require('tpl!../templates/share.html')

	return Backbone.View.extend({
		events: {
			'click .share-trigger': 'toggleShare',
			'click .nav-tabs .tab': 'selectTab',
			'click .support-selector a[role="menuitem"]': 'select'
		},
		select: function (event) {
			var el = $(event.currentTarget)
			this.$('.support-selector').find('.value').text(el.data().val || el.text())
		},
		selectTab: function (event) {
			event.preventDefault()
			var tab = $(event.currentTarget).attr('href').replace('#', '')
			store().router.navigate(
				'/type/' + store().currentType.type + '/id/' + store().currentType.id + '/tab/' + tab,
				{trigger: true}
			)
		},
		initialize: function () {
			this.listenTo(store().hub, 'repos-loaded', this.loadedRepoList)

			this.listenTo(store().selected, 'add remove', this.updateSelectedCount)
			this.listenTo(store().selected, 'add', this.addHeart)
			this.listenTo(store().selected, 'remove', this.removeHeart)

			this.listenTo(store().selected, 'prefetch', this.showLoading)
			this.listenTo(store().selected, 'fetched', this.hideLoading)
			this.listenTo(store().groups, 'sync', this.showSelector)
			this.render()
		},
		hideLoading: function () {
			this.$('.loading').hide()
			this.$('.content').slideDown()

			var link = this.getProjectLink()
			this.$('.share').html(shareTpl({
				shareLink: link
			}))

			this.$('.preview').attr('href', link).html('Preview ' + store().currentType.type)
		},
		getProjectLink: function () {
			var link = []

			if (store().currentType.type == 'organization') {
				link.push('orgs')
			} else if (store().currentType.type == 'project') {
				link.push('projects')
			} else {
				link.push('users')
			}

			if (store().currentType.type != 'user') {
				link.push(store().currentType.id)
			} else {
				link.push(currentUserName)
			}

			return link.join('/')
		},
		showLoading: function () {
			this.$('.loading').show()
			this.$('.content').slideUp()
		},
		showSelector: function () {
			this.$('.support-selector').html(selectorTpl({
				groups: store().groups.toJSON(),
				current: store().currentType
			}))
		},
		updateSelectedCount: function (model, collection) {
			this.$('#selected-count').text(collection.length)
		},
		addHeart: function () {
			if (!store().groups.currentHasSupport()) {
				store().groups.updateCurrentSupport(true)
				this.showSelector()
			}
		},
		removeHeart: function (model, collection) {
			if (collection.length) return
			store().groups.updateCurrentSupport(false)
			this.showSelector()
		},
		toggleShare: function () {
			var btn = this.$('.share-trigger'),
				altText = btn.data().altText,
				el = this.$('.share')

			if (!el.is(':visible')) {
				el.slideDown()
			} else {
				el.slideUp()
			}

			btn.data().altText = btn.text()
			btn.text(altText)
		},
		render: function () {
			var self = this
			this.$('.loading').hide()
			this.$('.content').html(tpl()).slideDown()
			this.updateSelectedCount(null, store().selected)
		},
		loadedRepoList: function (collection, type) {
			if (type == 'search') return
			this.$('.nav .tab[href="#' + type + '-repos"]').parent().removeClass('disabled')
		}
	});
})<|endoftext|>


<commit_before>import { createFormReducer } from 'redux-form'

export { default as auth } from './auth';
export { default as mobilizations } from './mobilizations';
export { default as blocks } from './blocks';
export { default as widgets } from './widgets';

export const loginForm = createFormReducer('loginForm', ['email', 'password'])
export const mobilizationFonts = createFormReducer('mobilizationFonts', ['headerFont', 'bodyFont'])
export const mobilizationBasics = createFormReducer('mobilizationBasics', ['name', 'goal'])
export const mobilizationCity = createFormReducer('mobilizationCity', ['colorScheme'])
export const mobilizationAnalytics = createFormReducer('mobilizationAnalytics', ['id'])
export const mobilizationSharing = createFormReducer('mobilizationSharing', ['facebook_share_title', 'facebook_share_description'])
export const widgetForm = createFormReducer('widgetForm', ['callToAction', 'buttonText', 'countText', 'emailText'])
<commit_msg>[#102391524] remove unused file<commit_after><|endoftext|>


<commit_before>function random_number(inner,outer){
	var delta = Math.abs(outer - inner);
	if(inner < outer){
		return (inner + delta * randomTool.genrand_real3());
	}
	else{
		return (outer + delta * randomTool.genrand_real3());
	}
};

/*----------------------------------------------------------------------*/
/* This function returns a value within a certain variation of the */
/* exact value given it in 'value'. */
/*----------------------------------------------------------------------*/
function about(value, variation){
	var inner = value - variation;
	return (inner + 2.0 * variation * randomTool.genrand_real3());
};

function random_eccentricity(){
	return (1.0 - Math.pow((randomTool.genrand_real3()),ECCENTRICITY_COEFF));
};
<commit_msg>Cleaned up utils.js<commit_after>function random_number(inner, outer) {
    var delta = Math.abs(outer - inner);
    if (inner < outer) {
	return (inner + delta * randomTool.genrand_real3());
    } else {
	return (outer + delta * randomTool.genrand_real3());
    }
};

/*----------------------------------------------------------------------*/
/* This function returns a value within a certain variation of the */
/* exact value given it in 'value'. */
/*----------------------------------------------------------------------*/
function about(value, variation) {
    var inner = value - variation;
    return (inner + 2.0 * variation * randomTool.genrand_real3());
};

function random_eccentricity() {
    return (1.0 - Math.pow((randomTool.genrand_real3()), ECCENTRICITY_COEFF));
};
<|endoftext|>


<commit_before>'use strict';
var Matrix = require('ml-matrix');
var Stat = require('ml-stat');
var SVD = Matrix.DC.SVD;

module.exports = PCA;

function PCA(dataset, reload) {

    if (reload) {
        this.U = dataset.U;
        this.S = dataset.S;
    } else {
        if (!Matrix.isMatrix(dataset)) {
            dataset = new Matrix(dataset);
        } else {
            dataset = dataset.clone();
        }
        var normalizedDataset = featureNormalize(dataset);
        var covarianceMatrix = normalizedDataset.transpose().mmul(normalizedDataset).divS(dataset.rows);

        var target = new SVD(covarianceMatrix, {
            computeLeftSingularVectors: true,
            computeRightSingularVectors: true,
            autoTranspose: false
        });

        this.U = target.leftSingularVectors;
        this.S = target.diagonal;
    }
}

PCA.load = function (model) {
    if(model.modelName !== 'PCA')
        throw new RangeError("The current model is invalid!");

    return new PCA(model, true);
};

PCA.prototype.export = function () {
    var model = {
        modelName: "PCA",
        U: this.U,
        S: this.S
    };

    return model;
};

PCA.prototype.project = function (dataset, dimensions) {
    var dim = dimensions - 1;
    if(dimensions > this.U.columns)
        throw new RangeError("the number of dimensions must not be larger than " + this.U.columns);

    var X = featureNormalize(Matrix(dataset).clone());
    return X.mmul(this.U.subMatrix(0, this.U.rows - 1, 0, dim));
};

PCA.prototype.getExplainedVariance = function () {
    var sum = this.S.reduce(function (previous, value) {
        return previous + value;
    });
    return this.S.map(function (value) {
        return value / sum;
    });
};

function featureNormalize(dataset) {
    var means = Stat.matrix.mean(dataset);
    var std = Matrix.rowVector(Stat.matrix.standardDeviation(dataset, means, true));
    means = Matrix.rowVector(means);

    var result = dataset.subRowVector(means);
    return result.divRowVector(std);
}
<commit_msg>All functions with docs.<commit_after>'use strict';
var Matrix = require('ml-matrix');
var Stat = require('ml-stat');
var SVD = Matrix.DC.SVD;

module.exports = PCA;

/*
* Creates new PCA (Principal Component Analysis) from the dataset
* @param {Matrix} dataset
* @constructor
* */
function PCA(dataset, reload) {

    if (reload) {
        this.U = dataset.U;
        this.S = dataset.S;
    } else {
        if (!Matrix.isMatrix(dataset)) {
            dataset = new Matrix(dataset);
        } else {
            dataset = dataset.clone();
        }
        var normalizedDataset = featureNormalize(dataset);
        var covarianceMatrix = normalizedDataset.transpose().mmul(normalizedDataset).divS(dataset.rows);

        var target = new SVD(covarianceMatrix, {
            computeLeftSingularVectors: true,
            computeRightSingularVectors: true,
            autoTranspose: false
        });

        this.U = target.leftSingularVectors;
        this.S = target.diagonal;
    }
}

/*
* Load a PCA model from JSON
* @oaram {Object} model
* @return {PCA}
* */
PCA.load = function (model) {
    if(model.modelName !== 'PCA')
        throw new RangeError("The current model is invalid!");

    return new PCA(model, true);
};

/*
* Exports the current model to an Object
* @return {Object} model
* */
PCA.prototype.export = function () {
    var model = {
        modelName: "PCA",
        U: this.U,
        S: this.S
    };

    return model;
};

/*
* Function that project the dataset into new space of k dimensions,
* this method doesn't modify your dataset.
* @param {Matrix} dataset.
* @param {Number} k - dimensions to project.
* @return {Matrix} dataset projected in k dimensions.
* @throws {RangeError} if k is larger than the number of eigenvector
*                      of the model.
* */
PCA.prototype.project = function (dataset, k) {
    var dimensions = k - 1;
    if(k > this.U.columns)
        throw new RangeError("the number of dimensions must not be larger than " + this.U.columns);

    var X = featureNormalize(Matrix(dataset).clone());
    return X.mmul(this.U.subMatrix(0, this.U.rows - 1, 0, dimensions));
};

/*
* This method returns the percentage variance of each eigenvector.
* @return {vector} variances
* */
PCA.prototype.getExplainedVariance = function () {
    var sum = this.S.reduce(function (previous, value) {
        return previous + value;
    });
    return this.S.map(function (value) {
        return value / sum;
    });
};

/*
* This method returns a dataset normalized in the following form:
* X = (X - mean) / std
* @param dataset
* @return A dataset normalized
* */
function featureNormalize(dataset) {
    var means = Stat.matrix.mean(dataset);
    var std = Matrix.rowVector(Stat.matrix.standardDeviation(dataset, means, true));
    means = Matrix.rowVector(means);

    var result = dataset.subRowVector(means);
    return result.divRowVector(std);
}
<|endoftext|>


<commit_before>/**
 * Run integration tests
 *
 * Uses the `waterline-adapter-tests` module to
 * run mocha tests against the appropriate version
 * of Waterline.  Only the interfaces explicitly
 * declared in this adapter's `package.json` file
 * are tested. (e.g. `queryable`, `semantic`, etc.)
 */

/**
 * Module dependencies
 */

var util = require('util');
var mocha = require('mocha');
var log = require('captains-log')();
var TestRunner = require('waterline-adapter-tests');
var Adapter = require('../../lib/adapter');

// Grab targeted interfaces from this adapter's `package.json` file:
var package = {},
  interfaces = [];
try {
  package = require('../../package.json');
  interfaces = package.waterlineAdapter.interfaces;
} catch (e) {
  throw new Error(
    '\n' +
    'Could not read supported interfaces from `waterlineAdapter.interfaces`' + '\n' +
    'in this adapter\'s `package.json` file ::' + '\n' +
    util.inspect(e)
  );
}

log.info('Testing `' + package.name + '`, a Sails/Waterline adapter.');
log.info('Running `waterline-adapter-tests` against ' + interfaces.length + ' interfaces...');
log.info('( ' + interfaces.join(', ') + ' )');
console.log();
log('Latest draft of Waterline adapter interface spec:');
log('http://links.sailsjs.org/docs/plugins/adapters/interfaces');
console.log();

/**
 * Integration Test Runner
 *
 * Uses the `waterline-adapter-tests` module to
 * run mocha tests against the specified interfaces
 * of the currently-implemented Waterline adapter API.
 */
new TestRunner({

  // Mocha opts
  mocha: {
    bail: true
  },

  // Load the adapter module.
  adapter: Adapter,

  // Default connection config to use.
  config: {
    host: 'localhost',
    database: 'sails-mongo',
    port: 6379,
    schema: true,
    poolSize: 1
  },

  // The set of adapter interfaces to test against.
  // (grabbed these from this adapter's package.json file above)
  interfaces: interfaces

  // Most databases implement 'semantic' and 'queryable'.
  //
  // As of Sails/Waterline v0.10, the 'associations' interface
  // is also available.  If you don't implement 'associations',
  // it will be polyfilled for you by Waterline core.  The core
  // implementation will always be used for cross-adapter / cross-connection
  // joins.
  //
  // In future versions of Sails/Waterline, 'queryable' may be also
  // be polyfilled by core.
  //
  // These polyfilled implementations can usually be further optimized at the
  // adapter level, since most databases provide optimizations for internal
  // operations.
  //
  // Full interface reference:
  // https://github.com/balderdashy/sails-docs/blob/master/adapter-specification.md
});
<commit_msg>Update runner.js<commit_after>/**
 * Run integration tests
 *
 * Uses the `waterline-adapter-tests` module to
 * run mocha tests against the appropriate version
 * of Waterline.  Only the interfaces explicitly
 * declared in this adapter's `package.json` file
 * are tested. (e.g. `queryable`, `semantic`, etc.)
 */

/**
 * Module dependencies
 */

var util = require('util');
var mocha = require('mocha');
var log = require('captains-log')();
var TestRunner = require('waterline-adapter-tests');
var Adapter = require('../../lib/adapter');

// Grab targeted interfaces from this adapter's `package.json` file:
var package = {},
  interfaces = [],
  features = [];
try {
  package = require('../../package.json');
  interfaces = package.waterlineAdapter.interfaces;
  features = package.waterlineAdapter.features;
} catch (e) {
  throw new Error(
    '\n' +
    'Could not read supported interfaces from `waterlineAdapter.interfaces`' + '\n' +
    'in this adapter\'s `package.json` file ::' + '\n' +
    util.inspect(e)
  );
}

log.info('Testing `' + package.name + '`, a Sails/Waterline adapter.');
log.info('Running `waterline-adapter-tests` against ' + interfaces.length + ' interfaces...');
log.info('( ' + interfaces.join(', ') + ' )');
console.log();
log('Latest draft of Waterline adapter interface spec:');
log('http://links.sailsjs.org/docs/plugins/adapters/interfaces');
console.log();

/**
 * Integration Test Runner
 *
 * Uses the `waterline-adapter-tests` module to
 * run mocha tests against the specified interfaces
 * of the currently-implemented Waterline adapter API.
 */
new TestRunner({

  // Mocha opts
  mocha: {
    bail: true
  },

  // Load the adapter module.
  adapter: Adapter,

  // Default connection config to use.
  config: {
    host: 'localhost',
    database: 'sails-mongo',
    port: 6379,
    schema: true,
    poolSize: 1
  },

  // The set of adapter interfaces to test against.
  // (grabbed these from this adapter's package.json file above)
  interfaces: interfaces,

  // The set of adapter features to test against.
  // (grabbed these from this adapter's package.json file above)
  features: features,

  // Most databases implement 'semantic' and 'queryable'.
  //
  // As of Sails/Waterline v0.10, the 'associations' interface
  // is also available.  If you don't implement 'associations',
  // it will be polyfilled for you by Waterline core.  The core
  // implementation will always be used for cross-adapter / cross-connection
  // joins.
  //
  // In future versions of Sails/Waterline, 'queryable' may be also
  // be polyfilled by core.
  //
  // These polyfilled implementations can usually be further optimized at the
  // adapter level, since most databases provide optimizations for internal
  // operations.
  //
  // Full interface reference:
  // https://github.com/balderdashy/sails-docs/blob/master/adapter-specification.md
});
<|endoftext|>


<commit_before>import styled from 'styled-components'

const Card = styled.div`{
  position: relative;
  border-radius: 1px;
  background-color: #ffffff;
  box-shadow: 2px 1px 14px 11px rgba(0, 0, 0, 0.04);
  width: 100%;
  display: block;
  ${props => props.height && `height: ${props.height};`}
  ${props => props.onClick && `cursor: pointer;`}

}`

Card.displayName = 'Card'

export default Card
<commit_msg>feat(styleguide): add rounded, margin and border props to Card<commit_after>import styled from 'styled-components'
import { px } from '../../utils'

const Card = styled.div`{
  position: relative;
  border-radius: ${props => px(props.rounded || '1px')};
  background-color: #ffffff;
  box-shadow: 2px 1px 14px 11px rgba(0, 0, 0, 0.04);
  width: ${props => props.width ? `${px(props.width)}` : '100%'};
  display: block;
  ${props => props.margin && `margin: ${props.margin};`}
  ${props => props.height && `height: ${props.height};`}
  ${props => props.onClick && `cursor: pointer;`}
  ${props => props.border && `border: ${props.border};`}

}`

Card.displayName = 'Card'

export default Card
<|endoftext|>


<commit_before>var parser = require('uglify-js').parser;
var uglify = require('uglify-js').uglify;
var _ = require('underscore');

var LOG_LEVELS = {
  'off':   0,
  'error': 1,
  'warn':  2,
  'info':  3,
  'debug': 4,
  'trace': 5
};

function init(options) {
  var logLevel = options.loggerLevel;
  if (typeof logLevel !== 'string' || typeof LOG_LEVELS[logLevel] === 'undefined') {
    throw new Error('invalid log level: ' + logLevel);
  }

  var allowedLogLevelsSet = {};

  _(LOG_LEVELS).each(function(rank, name) {
    if (rank > 0 && rank <= LOG_LEVELS[logLevel]) {
      allowedLogLevelsSet[name] = true;
    }
  });

  var loggerFile = __dirname + '/logger.js';

  return {
    run: function(src) {
      var replacementOffset = 0;
      var walker = uglify.ast_walker();

      walker.with_walkers({
        'call': function() {
          if (this[1][0] === 'dot' &&
                     this[1][1][0] === 'name' &&
                     this[1][1][1] === 'logger') {
            var logLevel = this[1][2];
            var token = this[0];
            var startPos = token.start.pos + replacementOffset;
            var endPos = token.end.endpos + replacementOffset;

            if (allowedLogLevelsSet[logLevel] !== true) {
              src = src.substring(0, startPos) + '/* ' +
                    src.substring(startPos, endPos) + ' */' +
                    src.substring(endPos);
              replacementOffset += '/*  */'.length;
            } else {
              var stringToInject = '"' + logLevel.charAt(0) + '[" + __shortfilename + "]:"';
              if (this[2].length > 0) {
                stringToInject += ', ';
              }
              var logStatement = src.substring(startPos, endPos);
              var logFnRegex = new RegExp('(^\\s*logger\\s*\\.\\s*' + logLevel + '\\s*\\(\s*)');
              logStatement = logStatement.replace(logFnRegex, '$1' + stringToInject);
              src = src.substring(0, startPos) +
                    logStatement +
                    src.substring(endPos);
              replacementOffset += stringToInject.length;
            }
          }
        }
      }, function() {
        return walker.walk(parser.parse(src, false, true));
      });

      if (logLevel === 'off') {
        return src;
      } else {
        return 'var __shortfilename = String(__filename).split("/");\n\
                __shortfilename = __shortfilename.slice(__shortfilename.length - 3).join("/");\n\
                var logger = new (require(' + JSON.stringify(loggerFile) + '));\n' + src;
      }
    },
    requires: logLevel === "off" ? [] : [ loggerFile ], // must be absolute paths
    lineDelta: logLevel === "off" ? 0 : 3
  }
}

exports.init = init;

<commit_msg>minor code clean-up<commit_after>var parser = require('uglify-js').parser;
var uglify = require('uglify-js').uglify;
var _ = require('underscore');

var LOG_LEVELS = {
  'off':   0,
  'error': 1,
  'warn':  2,
  'info':  3,
  'debug': 4,
  'trace': 5
};

function init(options) {
  var logLevel = options.loggerLevel;
  if (typeof logLevel !== 'string' || typeof LOG_LEVELS[logLevel] === 'undefined') {
    throw new Error('invalid log level: ' + logLevel);
  }

  var allowedLogLevelsSet = {};

  _(LOG_LEVELS).each(function(rank, name) {
    if (rank > 0 && rank <= LOG_LEVELS[logLevel]) {
      allowedLogLevelsSet[name] = true;
    }
  });

  var loggerFile = __dirname + '/logger.js';

  return {
    run: function(src) {
      var replacementOffset = 0;
      var walker = uglify.ast_walker();

      walker.with_walkers({
        'call': function() {
          if (this[1][0] === 'dot' &&
                     this[1][1][0] === 'name' &&
                     this[1][1][1] === 'logger') {
            var logLevel = this[1][2];
            var token = this[0];
            var startPos = token.start.pos + replacementOffset;
            var endPos = token.end.endpos + replacementOffset;

            if (allowedLogLevelsSet[logLevel] !== true) {
              src = src.substring(0, startPos) + '/* ' +
                    src.substring(startPos, endPos) + ' */' +
                    src.substring(endPos);
              replacementOffset += '/*  */'.length;
            } else {
              var stringToInject = '"' + logLevel.charAt(0) + '[" + __shortfilename + "]:"';
              if (this[2].length > 0) {
                stringToInject += ', ';
              }
              var logStatement = src.substring(startPos, endPos);
              var logFnRegex = new RegExp('(^\\s*logger\\s*\\.\\s*' + logLevel + '\\s*\\(\s*)');
              logStatement = logStatement.replace(logFnRegex, '$1' + stringToInject);
              src = src.substring(0, startPos) +
                    logStatement +
                    src.substring(endPos);
              replacementOffset += stringToInject.length;
            }
          }
        }
      }, function() {
        return walker.walk(parser.parse(src, false, true));
      });

      if (logLevel === 'off') {
        return src;
      } else {
        return 'var __shortfilename = String(__filename).split("/");\n\
                __shortfilename = __shortfilename.slice(__shortfilename.length - 3).join("/");\n\
                var logger = new (require(' + JSON.stringify(loggerFile) + '));\n' + src;
      }
    },

    requires: logLevel === 'off' ? [] : [ loggerFile ], // must be absolute paths

    lineDelta: logLevel === 'off' ? 0 : 3
  }
}

exports.init = init;

<|endoftext|>


<commit_before>"use strict";

const SocketIOFileUploadServer = require("socketio-file-upload/server");
const Helper = require("../helper");
const path = require("path");
const fsextra = require("fs-extra");
const fs = require("fs");
const fileType = require("file-type");
const readChunk = require("read-chunk");
const crypto = require("crypto");
const isUtf8 = require("is-utf8");
const log = require("../log");

const whitelist = [
	"application/ogg",
	"audio/midi",
	"audio/mpeg",
	"audio/ogg",
	"audio/x-wav",
	"image/bmp",
	"image/gif",
	"image/jpeg",
	"image/png",
	"image/webp",
	"text/plain",
	"video/mp4",
	"video/ogg",
	"video/webm",
];

class Uploader {
	constructor(socket) {
		const uploader = new SocketIOFileUploadServer();
		const folder = path.join(Helper.getFileUploadPath(), ".tmp");

		fsextra.ensureDir(folder, (err) => {
			if (err) {
				log.err(`Error ensuring ${folder} exists for uploads.`);
			} else {
				uploader.dir = folder;
			}
		});

		uploader.on("complete", (data) => {
			let randomName;
			let destPath;

			// Generate a random file name for storage on disk
			do {
				randomName = crypto.randomBytes(8).toString("hex");
				destPath = path.join(Helper.getFileUploadPath(), randomName.substring(0, 2), randomName);
			} while (fs.stat(destPath, (err) => (err ? true : false)));

			fsextra.move(data.file.pathName, destPath).then(() => {
				const slug = encodeURIComponent(path.basename(data.file.pathName));
				const url = `uploads/${randomName}/${slug}`;
				socket.emit("upload:success", url);
			}).catch(() => {
				log.warn(`Unable to move uploaded file "${data.file.pathName}"`);

				// Emit failed upload to the client if file move fails
				socket.emit("siofu_error", {
					id: data.file.id,
					message: "Unable to move uploaded file",
				});
			});
		});

		uploader.on("error", (data) => {
			log.error(`File upload failed: ${data.error}`);
		});

		// maxFileSize is in bytes, but config option is passed in as KB
		uploader.maxFileSize = Uploader.getMaxFileSize();
		uploader.listen(socket);
	}

	static isValidType(mimeType) {
		return whitelist.includes(mimeType);
	}

	static router(express) {
		express.get("/uploads/:name/:slug*?", (req, res) => {
			const name = req.params.name;

			const nameRegex = /^[0-9a-f]{16}$/;

			if (!nameRegex.test(name)) {
				return res.status(404).send("Not found");
			}

			const folder = name.substring(0, 2);
			const uploadPath = Helper.getFileUploadPath();
			const filePath = path.join(uploadPath, folder, name);
			const type = Uploader.getFileType(filePath);
			const mimeType = type || "application/octet-stream";
			const contentDisposition = Uploader.isValidType(type) ? "inline" : "attachment";

			// doesn't exist
			if (type === undefined) {
				return res.status(404).send("Not found");
			}

			res.setHeader("Content-Disposition", contentDisposition);
			res.setHeader("Cache-Control", "max-age=86400");
			res.contentType(mimeType);

			return res.sendFile(filePath);
		});
	}

	static getMaxFileSize() {
		const configOption = Helper.config.fileUpload.maxFileSize;

		if (configOption === -1) { // no file size limit
			return null;
		}

		return configOption * 1024;
	}

	static getFileType(filePath) {
		let buffer;
		let type;

		try {
			buffer = readChunk.sync(filePath, 0, fileType.minimumBytes);
		} catch (e) {
			if (e.code === "ENOENT") { // doesn't exist
				return;
			}

			log.warn(`Failed to read ${filePath}`);
			return;
		}

		// returns {ext, mime} if found, null if not.
		const file = fileType(buffer);

		if (file) {
			type = file.mime;
		} else if (isUtf8(buffer)) {
			type = "text/plain";
		}

		return type;
	}
}

module.exports = Uploader;
<commit_msg>Fix incorrect use of fs.stat<commit_after>"use strict";

const SocketIOFileUploadServer = require("socketio-file-upload/server");
const Helper = require("../helper");
const path = require("path");
const fsextra = require("fs-extra");
const fs = require("fs");
const fileType = require("file-type");
const readChunk = require("read-chunk");
const crypto = require("crypto");
const isUtf8 = require("is-utf8");
const log = require("../log");

const whitelist = [
	"application/ogg",
	"audio/midi",
	"audio/mpeg",
	"audio/ogg",
	"audio/x-wav",
	"image/bmp",
	"image/gif",
	"image/jpeg",
	"image/png",
	"image/webp",
	"text/plain",
	"video/mp4",
	"video/ogg",
	"video/webm",
];

class Uploader {
	constructor(socket) {
		const uploader = new SocketIOFileUploadServer();
		const folder = path.join(Helper.getFileUploadPath(), ".tmp");

		fsextra.ensureDir(folder, (err) => {
			if (err) {
				log.err(`Error ensuring ${folder} exists for uploads.`);
			} else {
				uploader.dir = folder;
			}
		});

		uploader.on("complete", (data) => {
			let randomName;
			let destPath;

			// Generate a random file name for storage on disk
			do {
				randomName = crypto.randomBytes(8).toString("hex");
				destPath = path.join(Helper.getFileUploadPath(), randomName.substring(0, 2), randomName);
			} while (fs.existsSync(destPath));

			fsextra.move(data.file.pathName, destPath).then(() => {
				const slug = encodeURIComponent(path.basename(data.file.pathName));
				const url = `uploads/${randomName}/${slug}`;
				socket.emit("upload:success", url);
			}).catch(() => {
				log.warn(`Unable to move uploaded file "${data.file.pathName}"`);

				// Emit failed upload to the client if file move fails
				socket.emit("siofu_error", {
					id: data.file.id,
					message: "Unable to move uploaded file",
				});
			});
		});

		uploader.on("error", (data) => {
			log.error(`File upload failed: ${data.error}`);
		});

		// maxFileSize is in bytes, but config option is passed in as KB
		uploader.maxFileSize = Uploader.getMaxFileSize();
		uploader.listen(socket);
	}

	static isValidType(mimeType) {
		return whitelist.includes(mimeType);
	}

	static router(express) {
		express.get("/uploads/:name/:slug*?", (req, res) => {
			const name = req.params.name;

			const nameRegex = /^[0-9a-f]{16}$/;

			if (!nameRegex.test(name)) {
				return res.status(404).send("Not found");
			}

			const folder = name.substring(0, 2);
			const uploadPath = Helper.getFileUploadPath();
			const filePath = path.join(uploadPath, folder, name);
			const type = Uploader.getFileType(filePath);
			const mimeType = type || "application/octet-stream";
			const contentDisposition = Uploader.isValidType(type) ? "inline" : "attachment";

			// doesn't exist
			if (type === undefined) {
				return res.status(404).send("Not found");
			}

			res.setHeader("Content-Disposition", contentDisposition);
			res.setHeader("Cache-Control", "max-age=86400");
			res.contentType(mimeType);

			return res.sendFile(filePath);
		});
	}

	static getMaxFileSize() {
		const configOption = Helper.config.fileUpload.maxFileSize;

		if (configOption === -1) { // no file size limit
			return null;
		}

		return configOption * 1024;
	}

	static getFileType(filePath) {
		let buffer;
		let type;

		try {
			buffer = readChunk.sync(filePath, 0, fileType.minimumBytes);
		} catch (e) {
			if (e.code === "ENOENT") { // doesn't exist
				return;
			}

			log.warn(`Failed to read ${filePath}`);
			return;
		}

		// returns {ext, mime} if found, null if not.
		const file = fileType(buffer);

		if (file) {
			type = file.mime;
		} else if (isUtf8(buffer)) {
			type = "text/plain";
		}

		return type;
	}
}

module.exports = Uploader;
<|endoftext|>