<commit_before>"use strict";

var utils     = require("./lib/utils");

function RespModifier (opts) {

    // options
    opts           = opts || {};
    opts.blacklist = utils.toArray(opts.blacklist)   || [];
    opts.whitelist = utils.toArray(opts.whitelist)   || [];
    opts.rules     = opts.rules                      || [];
    opts.ignore    = opts.ignore || opts.excludeList || utils.defaultIgnoreTypes;

    // helper functions
    opts.regex = (function () {
        var matches = opts.rules.map(function (item) {
            return item.match.source;
        }).join("|");
        return new RegExp(matches);
    })();

    var respMod        = this;

    respMod.opts       = opts;
    respMod.middleware = respModifierMiddleware;
    respMod.update = function (key, value) {
        if (respMod.opts[key]) {
            respMod.opts[key] = value;
        }
        return respMod;
    };

    function respModifierMiddleware(req, res, next) {

        if (res._respModifier) {
            return next();
        }

        res._respModifier = true;

        var writeHead = res.writeHead;
        var runPatches = true;
        var write = res.write;
        var count = 0;
        var end = res.end;
        res.rulesWritten = [];
        var singlerules = utils.isWhiteListedForSingle(req.url, respMod.opts.rules);

        var withoutSingle = respMod.opts.rules.filter(function (rule) {
            if (rule.paths && rule.paths.length) {
                return false;
            }
            return true;
        });

        if (singlerules.length) {
            modifyResponse(singlerules, true);
        } else {
            if (utils.isWhitelisted(req.url, respMod.opts.whitelist)) {
                modifyResponse(withoutSingle, true);
            } else {
                if (!utils.hasAcceptHeaders(req) || utils.inBlackList(req.url, respMod.opts)) {
                    return next();
                } else {
                    modifyResponse(withoutSingle);
                }
            }
        }

        next();

        /**
         * Actually do the overwrite
         * @param {boolean} [force] - if true, will perform an overwrite even regardless of whether it's HTML or not.
         */
        function modifyResponse(rules, force) {

            req.headers["accept-encoding"] = "identity";

            function restore() {
                res.writeHead = writeHead;
                res.write = write;
                res.end = end;
            }

            res.push = function (chunk) {
                res.data = (res.data || "") + chunk;
            };

            res.write = function (string, encoding) {

                if (!runPatches) {
                    return write.call(res, string, encoding);
                }

                if (string !== undefined) {
                    var body = string instanceof Buffer ? string.toString(encoding) : string;
                    // If this chunk must receive a snip, do so
                    if (force || (utils.isHtml(body) || utils.isHtml(res.data))) {
                        res.push(body);
                    } else {
                        restore();
                        return write.call(res, string, encoding);
                    }
                }
                return true;
            };

            res.writeHead = function () {
                if (!runPatches) {
                    return writeHead.apply(res, arguments);
                }

                var headers = arguments[arguments.length - 1];
                if (typeof headers === "object") {
                    for (var name in headers) {
                        if (/content-length/i.test(name)) {
                            delete headers[name];
                        }
                    }
                }

                if (res.getHeader("content-length")) {
                    res.removeHeader("content-length");
                }

                writeHead.apply(res, arguments);
            };

            res.end = function (string, encoding) {

                res.data = res.data || '';

                if (typeof string === 'string') {
                    res.data += string;
                }

                if (!runPatches) {
                    return end.call(res, string, encoding);
                }

                //// If there are remaining bytes, save them as well
                //// Also, some implementations call "end" directly with all data.
                //res.inject(string);
                //runPatches = false;
                //// Check if our body is HTML, and if it does not already have the snippet.
                if (force || utils.isHtml(res.data) && !utils.snip(res.data)) {
                    // Include, if necessary, replacing the entire res.data with the included snippet.
                    res.data = utils.overwriteBody(rules, res.data, res);
                    runPatches = false;
                }
                if (res.data !== undefined && !res._header) {
                    res.setHeader("content-length", Buffer.byteLength(res.data, encoding));
                }
                end.call(res, res.data, encoding);
            };
        }
    }

    return respMod;
}

module.exports = function (opts) {
    var resp = new RespModifier(opts);
    return resp.middleware;
};

module.exports.create = function (opts) {
    var resp = new RespModifier(opts);
    return resp;
};

module.exports.utils = utils;
<commit_msg>Accept string or buffer in .end*( call<commit_after>"use strict";

var utils     = require("./lib/utils");

function RespModifier (opts) {

    // options
    opts           = opts || {};
    opts.blacklist = utils.toArray(opts.blacklist)   || [];
    opts.whitelist = utils.toArray(opts.whitelist)   || [];
    opts.rules     = opts.rules                      || [];
    opts.ignore    = opts.ignore || opts.excludeList || utils.defaultIgnoreTypes;

    // helper functions
    opts.regex = (function () {
        var matches = opts.rules.map(function (item) {
            return item.match.source;
        }).join("|");
        return new RegExp(matches);
    })();

    var respMod        = this;

    respMod.opts       = opts;
    respMod.middleware = respModifierMiddleware;
    respMod.update = function (key, value) {
        if (respMod.opts[key]) {
            respMod.opts[key] = value;
        }
        return respMod;
    };

    function respModifierMiddleware(req, res, next) {

        if (res._respModifier) {
            return next();
        }

        res._respModifier = true;

        var writeHead = res.writeHead;
        var runPatches = true;
        var write = res.write;
        var count = 0;
        var end = res.end;
        res.rulesWritten = [];
        var singlerules = utils.isWhiteListedForSingle(req.url, respMod.opts.rules);

        var withoutSingle = respMod.opts.rules.filter(function (rule) {
            if (rule.paths && rule.paths.length) {
                return false;
            }
            return true;
        });

        if (singlerules.length) {
            modifyResponse(singlerules, true);
        } else {
            if (utils.isWhitelisted(req.url, respMod.opts.whitelist)) {
                modifyResponse(withoutSingle, true);
            } else {
                if (!utils.hasAcceptHeaders(req) || utils.inBlackList(req.url, respMod.opts)) {
                    return next();
                } else {
                    modifyResponse(withoutSingle);
                }
            }
        }

        next();

        /**
         * Actually do the overwrite
         * @param {boolean} [force] - if true, will perform an overwrite even regardless of whether it's HTML or not.
         */
        function modifyResponse(rules, force) {

            req.headers["accept-encoding"] = "identity";

            function restore() {
                res.writeHead = writeHead;
                res.write = write;
                res.end = end;
            }

            res.push = function (chunk) {
                res.data = (res.data || "") + chunk;
            };

            res.write = function (string, encoding) {

                if (!runPatches) {
                    return write.call(res, string, encoding);
                }

                if (string !== undefined) {
                    var body = string instanceof Buffer ? string.toString(encoding) : string;
                    // If this chunk must receive a snip, do so
                    if (force || (utils.isHtml(body) || utils.isHtml(res.data))) {
                        res.push(body);
                    } else {
                        restore();
                        return write.call(res, string, encoding);
                    }
                }
                return true;
            };

            res.writeHead = function () {
                if (!runPatches) {
                    return writeHead.apply(res, arguments);
                }

                var headers = arguments[arguments.length - 1];
                if (typeof headers === "object") {
                    for (var name in headers) {
                        if (/content-length/i.test(name)) {
                            delete headers[name];
                        }
                    }
                }

                if (res.getHeader("content-length")) {
                    res.removeHeader("content-length");
                }

                writeHead.apply(res, arguments);
            };

            res.end = function (string, encoding) {

                res.data = res.data || '';

                if (typeof string === 'string') {
                    res.data += string;
                }

                if (string instanceof Buffer) {
                    res.data += string.toString();
                }

                if (!runPatches) {
                    return end.call(res, string, encoding);
                }

                //// If there are remaining bytes, save them as well
                //// Also, some implementations call "end" directly with all data.
                //res.inject(string);
                //runPatches = false;
                //// Check if our body is HTML, and if it does not already have the snippet.
                if (force || utils.isHtml(res.data) && !utils.snip(res.data)) {
                    // Include, if necessary, replacing the entire res.data with the included snippet.
                    res.data = utils.overwriteBody(rules, res.data, res);
                    runPatches = false;
                }
                if (res.data !== undefined && !res._header) {
                    res.setHeader("content-length", Buffer.byteLength(res.data, encoding));
                }
                end.call(res, res.data, encoding);
            };
        }
    }

    return respMod;
}

module.exports = function (opts) {
    var resp = new RespModifier(opts);
    return resp.middleware;
};

module.exports.create = function (opts) {
    var resp = new RespModifier(opts);
    return resp;
};

module.exports.utils = utils;
<|endoftext|>


<commit_before>EFFECTS.push({

  NAME: "dev",
  FFT: 128,

  POINTS: [],

  LINES: [],

  COLORCYCLE: function(c) {
    return c;
  },

  setup: function() {

    _newAnalyser(this.FFT, .5);

    CAMERA = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
    CAMERA.position.z = 2400;

    for(var i = -(this.FFT / 2) + .5; i < this.FFT / 2; i++) {

      var material = new THREE.MeshBasicMaterial({color: new THREE.Color(1, 1, 1)});
      var geometry = new THREE.CircleGeometry(1, 64);
      var mesh = new THREE.Mesh(geometry, material);

      mesh.position.x = (i * this.FFT) / 2;

      SCENE.add(mesh);
      this.POINTS.push(mesh);
    }

    //shaders

    COMPOSER = new THREE.EffectComposer(RENDERER);
    COMPOSER.addPass(new THREE.RenderPass(SCENE, CAMERA));

    var kaleidoPass = new THREE.ShaderPass(THREE.KaleidoShader);
    kaleidoPass.uniforms['sides'] = { type: "f", value: 8.0 };
    kaleidoPass.uniforms['angle'] = { type: "f", value: (2 * Math.PI) / 16 };
    kaleidoPass.renderToScreen = true;

    COMPOSER.addPass(kaleidoPass);

  }, //setup

  destroy: function() {

    for(var i = 0; i < this.POINTS.length; i++) {
      SCENE.remove(this.POINTS[i]);
    }

    this.POINTS = [];

    COMPOSER = null;

  }, //destroy

  input: function() {

  }, //input

  tick: function() {

    var i = this.POINTS.length;
    for(var i = 0; i < this.POINTS.length; i++) {
      var fd = FD[Math.abs(i - this.FFT / 2)];
      if(this.POINTS[i].scale.x < fd) this.POINTS[i].scale.x = fd * 3;
      if(this.POINTS[i].scale.y < fd) this.POINTS[i].scale.y = fd * 3;
      var newscalex = this.POINTS[i].scale.x < 0 ? 0 : this.POINTS[i].scale.x * .98;
      var newscaley = this.POINTS[i].scale.y < 0 ? 0 : this.POINTS[i].scale.y * .98;
      this.POINTS[i].scale.x = newscalex;
      this.POINTS[i].scale.y = newscaley;
      var newcolor = this.COLORCYCLE(this.POINTS[i].material.color);
      this.POINTS[i].material.color = newcolor ? newcolor : {r: 1, g: 1, b: 1};
    }

  }, //tick

  beat: function() {

  }, //beat

  resize: function() {

    CAMERA = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
    CAMERA.position.z = 2400;

  } //resize

});
<commit_msg>Time data<commit_after>EFFECTS.push({

  NAME: "dev",
  FFT: 128,

  POINTS: [],

  LINES: [],
  LINESMESH: null,

  // COLORCYCLE: function(c) {
  //   return c;
  // },

  setup: function() {

    _newAnalyser(this.FFT, .5);

    CAMERA = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
    CAMERA.position.z = 2400;

    for(var i = -(this.FFT / 2) + .5; i < this.FFT / 2; i++) {

      var material = new THREE.MeshBasicMaterial({color: new THREE.Color(1, 1, 1)});
      var geometry = new THREE.CircleGeometry(1, 64);
      var mesh = new THREE.Mesh(geometry, material);

      mesh.position.x = (i * this.FFT) / 2;

      SCENE.add(mesh);
      this.POINTS.push(mesh);
    }

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial({color: new THREE.Color(0, 255, 255)});

    for(var i = -(this.FFT  / 2) + .5; i < this.FFT / 2; i++) {
      geometry.vertices.push(new THREE.Vector3((i * this.FFT) / 2, 0 , 10));
    }

    var mesh = new THREE.Line(geometry, material);
    SCENE.add(mesh);
    this.LINES = geometry;
    this.LINESMESH = mesh;

    //shaders

    COMPOSER = new THREE.EffectComposer(RENDERER);
    COMPOSER.addPass(new THREE.RenderPass(SCENE, CAMERA));

    var kaleidoPass = new THREE.ShaderPass(THREE.KaleidoShader);
    kaleidoPass.uniforms['sides'] = { type: "f", value: 8.0 };
    kaleidoPass.uniforms['angle'] = { type: "f", value: (2 * Math.PI) / 16 };
    kaleidoPass.renderToScreen = true;

    COMPOSER.addPass(kaleidoPass);

  }, //setup

  destroy: function() {

    for(var i = 0; i < this.POINTS.length; i++) {
      SCENE.remove(this.POINTS[i]);
    }

    this.POINTS = [];

    SCENE.remove(this.LINES);
    this.LINES = null;
    SCENE.remove(this.LINESMESH);
    this.LINESMESH = null;

    COMPOSER = null;

  }, //destroy

  input: function() {

  }, //input

  tick: function() {

    var i = this.POINTS.length;
    for(var i = 0; i < this.POINTS.length; i++) {
      var fd = FD[Math.abs(i - this.FFT / 2)];
      if(this.POINTS[i].scale.x < fd) this.POINTS[i].scale.x = fd * 2.5;
      if(this.POINTS[i].scale.y < fd) this.POINTS[i].scale.y = fd * 2.5;
      var newscalex = this.POINTS[i].scale.x < 0 ? 0 : this.POINTS[i].scale.x * .97;
      var newscaley = this.POINTS[i].scale.y < 0 ? 0 : this.POINTS[i].scale.y * .97;
      this.POINTS[i].scale.x = newscalex;
      this.POINTS[i].scale.y = newscaley;
      //var newcolor = this.COLORCYCLE(this.POINTS[i].material.color);
      //this.POINTS[i].material.color = newcolor ? newcolor : {r: 1, g: 1, b: 1};
    }

    for(var i = 0; i < this.LINES.vertices.length; i++) {

      var td = TD[i] - 128;

      if(Math.abs(this.LINES.vertices[i].y) < Math.abs(td * 25)) this.LINES.vertices[i].setY(td * 25);
      var newy = Math.abs(this.LINES.vertices[i].y) < 1 ? 0 : this.LINES.vertices[i].y * .92;
      this.LINES.vertices[i].setY(newy);
    }

    this.LINES.verticesNeedUpdate = true;

  }, //tick

  beat: function() {

  }, //beat

  resize: function() {

    CAMERA = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
    CAMERA.position.z = 2400;

  } //resize

});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const async = require('async');
const log = require('util').log;
const config = require('../../config.js');
const utils = require('../../utils');

let builder = {

    /**
     * Function that writes the default upstream.conf file for soajs.controller
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb      Callback function
     *
     */
    writeUpstream(options, cb) {
        if(!options.count) {
            log('No upstream entries available for SOAJS controllers, default upstream file won\'t be written');
            return cb();
        }

        log("Writing upstream.conf in " + options.loc);
        let wstream = fs.createWriteStream(options.loc + 'upstream.conf');
        wstream.write("upstream " + options.upstreamName + " {\n");
        for (let i = 1; i <= options.count; i++) {
            if (process.env[options.ipEnvName + i]) {
                wstream.write("  server " + process.env[options.ipEnvName + i] + ":" + options.port + ";\n");
            }
            else {
                log("ERROR: Unable to find environment variable " + options.ipEnvName + i);
            }
        }
        wstream.write("}\n");
        wstream.end();
        return cb(null);
    },

    /**
     * Function that writes nginx config for static location
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeStaticLocation(options, wstream) {
    	let rootPath = options.path;

        wstream.write("  location / {\n");
        wstream.write("    root  " + rootPath + ";\n");
        wstream.write("    sendfile       off;\n");
        wstream.write("    index  index.html index.htm;\n");
        wstream.write("  }\n");
    },

    /**
     * Function that writes nginx config for proxy location
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeProxyLocation(options, wstream) {
        if(!options.count) {
            log('No upstream entries available for SOAJS controllers, proxy location will not be written');
            return;
        }

        wstream.write("  location / {\n");
        wstream.write("    proxy_pass 		    http://" + options.upstreamName + ";\n");
        wstream.write("    proxy_set_header   	X-Forwarded-Proto 	    $scheme;\n");
        wstream.write("    proxy_set_header   	X-Forwarded-For 	    $remote_addr;\n");
        wstream.write("    proxy_set_header   	Host             		$http_host;\n");
        wstream.write("    proxy_set_header   	X-NginX-Proxy     	    true;\n");
        wstream.write("    proxy_set_header   	Connection        	    \"\";\n");
        wstream.write("  }\n");
    },

    /**
     * Function that writes nginx config for server redirect
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeServerRedirect(options, wstream) {
        wstream.write("server {\n");
        wstream.write("  listen       " + options.port + ";\n");
        wstream.write("  server_name  " + options.domain + ";\n");
        wstream.write("  client_max_body_size 100m;\n");
        wstream.write("  rewrite ^/(.*) https://" + options.domain + "/$1 permanent;\n");
        wstream.write("}\n");
    },

    /**
     * Function that writes nginx SSL config
     * @param  {Object}   options An object that contains params passed to the function
     *
     */
    writeServerSSL(wstream) {
        let certsLocation = path.join(config.nginx.location, '/ssl');
        if (config.nginx.config.ssl.customCerts) certsLocation = config.nginx.config.ssl.customCertsPath;

        let tlscrt = certsLocation + "/tls-crt";
        if (!fs.existsSync(tlscrt)) {
            tlscrt = certsLocation + "/tls.crt";
            if (!fs.existsSync(tlscrt)) {
                log('Unable to find SSL CRT file @ location: '+tlscrt)
            }
        }
        let tlskey = certsLocation + "/tls-key";
        if (!fs.existsSync(tlskey)) {
            tlskey = certsLocation + "/tls.key";
            if (!fs.existsSync(tlskey)) {
                log('Unable to find SSL KEY file @ location: '+tlskey)
            }
        }

        wstream.write("  ssl_certificate         " + tlscrt + ";\n");
        wstream.write("  ssl_certificate_key     " + tlskey + ";\n");
        wstream.write("  include " + config.nginx.location + "/ssl/ssl.conf;\n");
    },

    /**
     * Function that writes nginx config for server
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeServer(options, wstream) {
        if (options.location == "proxy" && !options.count) {
            log('No API server entry will be written, SOAJS controller count is missing');
            return;
        }

    	log("writing server entry for", options.domain);
        wstream.write("server {\n");
        wstream.write("  listen       " + options.port + ";\n");
        wstream.write("  server_name  " + options.domain + ";\n");
        wstream.write("  client_max_body_size 100m;\n");
        if (options.https)
            builder.writeServerSSL(wstream);
        if (options.location == "proxy")
            builder.writeProxyLocation(options, wstream);
        else if (options.location == "static")
            builder.writeStaticLocation(options, wstream);
        wstream.write("}\n");
    },

    /**
     * Function that redirects to proper write function for api config based on passed params
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb      Callback function
     *
     */
    writeApiConf(options, cb) {
        log("Writing api conf in " + options.loc + " " + options.confFileName);
        let wstream = fs.createWriteStream(options.loc + options.confFileName);
        let httpsApi = config.nginx.config.ssl.httpsApi;
        let httpApiRedirect = config.nginx.config.ssl.httpApiRedirect;

        options.location = "proxy";

        if (httpsApi) {
            if (httpApiRedirect) {
                options.port = "80";
                builder.writeServerRedirect(options, wstream);
            }
            options.https = true;
            options.port = "443 ssl";
            builder.writeServer(options, wstream);
        }
        else if (!httpApiRedirect){
            options.port = "80";
            builder.writeServer(options, wstream);
        }

        wstream.end();
        return cb(null);
    },

    /**
     * Function that redirects to proper write function for site config based on passed params
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb      Callback function
     *
     */
    writeSiteConf(options, cb) {
    	let fileLocation = options.loc + options.confFileName;
	    options.domain = process.env.SOAJS_NX_SITE_DOMAIN;
    	//check if dashboard site.conf
	    if (process.env.SOAJS_ENV) {
	    	if(process.env.SOAJS_ENV.toLowerCase() === 'dashboard'){
			    fileLocation = options.loc + "dash.conf";
		    }
		    else if(process.env.SOAJS_ENV.toLowerCase() === 'portal'){
			    fileLocation = options.loc + "portal.conf";
		    }
	    }

        log("Writing site conf in " + fileLocation);
        let wstream = fs.createWriteStream(fileLocation);

        let httpsSite = config.nginx.config.ssl.httpsSite;
        let httpSiteRedirect = config.nginx.config.ssl.httpSiteRedirect;

        options.location = "static";

        if (httpsSite) {
	        if (httpSiteRedirect) {
		        options.port = "80";
		        builder.writeServerRedirect(options, wstream);
	        }
	        options.https = true;
	        options.port = "443 ssl";
	        builder.writeServer(options, wstream);
        }
        else if (!httpSiteRedirect){
	        options.port = "80";
	        builder.writeServer(options, wstream);
        }

        wstream.end();
        setTimeout(function(){
            return cb(null);
        }, 100);
    },

    /**
     * Function that writes the default nginx.conf file from templates and replaces placeholders with appropriate values
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb Callback function
     *
     */
    writeDefaultNginxConf(options, cb) {
        //read nginx.conf from templates directory
        log('Writing default nginx.conf ...');
        options.source = 'template';
        options.content = 'nginx';
        options.type = 'nginx.conf';
        options.target = options.nginx.location;
        utils.import(options, (error) => {
            if (error) throw new Error(error);

            log('nginx.conf written successfully ...');
            return cb();
        });
    },

    /**
     * Function that copies ssl.conf from templates directory to nginx directory
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb Callback function
     *
     */
    copySSLConf(options, cb) {
        //copy ssl.conf from templates directory to nginx directory
        log('Copying ssl.conf ...');
        let readStream = fs.createReadStream(path.join(options.paths.templates.nginx.path, 'ssl.conf'));
        let writeStream = fs.createWriteStream(path.join(options.nginx.location, '/ssl/ssl.conf'));

        readStream.on('error', (error) => {
            log('Unable to read ssl.conf ...');
            throw new Error(error);
        });
        writeStream.on('error', (error) => {
            log('Unable to write ssl.conf ...');
            throw new Error(error);
        });
        writeStream.on('close', () => {
            log('Successfully copied ssl.conf ...');
            return cb();
        });

        readStream.pipe(writeStream);
    },

    /**
     * Function that calls writeUpstream, writeApiConf, and writeSiteConf
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    write(options, cb) {
        let nxOs = options.nginx.os;
        builder.writeDefaultNginxConf(options, () => {
            builder.copySSLConf(options, () => {
                builder.writeUpstream({
                    loc: options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/conf.d/" : "/nginx/"),
                    port: options.nginx.config.upstream.ctrlPort,
                    ipEnvName: options.nginx.config.upstream.ipEnvName,
                    upstreamName: options.nginx.config.upstream.upstreamName,
                    count: options.nginx.config.upstream.count,
                }, () => {
                    log('SOAJS Controller Upstream was written successfully');
                    builder.writeApiConf({
                        loc: options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/sites-enabled/" : "/nginx/"),
                        confFileName: options.nginx.config.apiConf.fileName,
                        domain: options.nginx.config.apiConf.domain,
                        upstreamName: options.nginx.config.upstream.upstreamName,
                        count: options.nginx.config.upstream.count
                    }, () => {
                        log('Nginx API config was written successfully');
                        if (options.nginx.config.siteConf.domain) {
                            builder.writeSiteConf({
                                loc: options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/sites-enabled/" : "/nginx/"),
                                confFileName: options.nginx.config.siteConf.fileName,
                                domain: options.nginx.config.siteConf.domain,
                                path: options.nginx.config.siteConf.path
                            }, () => {
                                log('Nginx Site config was written successfully');
                                return cb();
                            });
                        }
                        else {
                            return cb();
                        }
                    });
                });
            });
        });
    }

};

module.exports = {
    write: builder.write
};
<commit_msg>added one extra folder layer @ ssl<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const async = require('async');
const log = require('util').log;
const config = require('../../config.js');
const utils = require('../../utils');

let builder = {

    /**
     * Function that writes the default upstream.conf file for soajs.controller
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb      Callback function
     *
     */
    writeUpstream(options, cb) {
        if(!options.count) {
            log('No upstream entries available for SOAJS controllers, default upstream file won\'t be written');
            return cb();
        }

        log("Writing upstream.conf in " + options.loc);
        let wstream = fs.createWriteStream(options.loc + 'upstream.conf');
        wstream.write("upstream " + options.upstreamName + " {\n");
        for (let i = 1; i <= options.count; i++) {
            if (process.env[options.ipEnvName + i]) {
                wstream.write("  server " + process.env[options.ipEnvName + i] + ":" + options.port + ";\n");
            }
            else {
                log("ERROR: Unable to find environment variable " + options.ipEnvName + i);
            }
        }
        wstream.write("}\n");
        wstream.end();
        return cb(null);
    },

    /**
     * Function that writes nginx config for static location
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeStaticLocation(options, wstream) {
    	let rootPath = options.path;

        wstream.write("  location / {\n");
        wstream.write("    root  " + rootPath + ";\n");
        wstream.write("    sendfile       off;\n");
        wstream.write("    index  index.html index.htm;\n");
        wstream.write("  }\n");
    },

    /**
     * Function that writes nginx config for proxy location
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeProxyLocation(options, wstream) {
        if(!options.count) {
            log('No upstream entries available for SOAJS controllers, proxy location will not be written');
            return;
        }

        wstream.write("  location / {\n");
        wstream.write("    proxy_pass 		    http://" + options.upstreamName + ";\n");
        wstream.write("    proxy_set_header   	X-Forwarded-Proto 	    $scheme;\n");
        wstream.write("    proxy_set_header   	X-Forwarded-For 	    $remote_addr;\n");
        wstream.write("    proxy_set_header   	Host             		$http_host;\n");
        wstream.write("    proxy_set_header   	X-NginX-Proxy     	    true;\n");
        wstream.write("    proxy_set_header   	Connection        	    \"\";\n");
        wstream.write("  }\n");
    },

    /**
     * Function that writes nginx config for server redirect
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeServerRedirect(options, wstream) {
        wstream.write("server {\n");
        wstream.write("  listen       " + options.port + ";\n");
        wstream.write("  server_name  " + options.domain + ";\n");
        wstream.write("  client_max_body_size 100m;\n");
        wstream.write("  rewrite ^/(.*) https://" + options.domain + "/$1 permanent;\n");
        wstream.write("}\n");
    },

    /**
     * Function that writes nginx SSL config
     * @param  {Object}   options An object that contains params passed to the function
     *
     */
    writeServerSSL(wstream) {
        let certsLocation = path.join(config.nginx.location, '/ssl');
        if (config.nginx.config.ssl.customCerts) certsLocation = config.nginx.config.ssl.customCertsPath;

        let tlscrt = certsLocation + "/crt/tls-crt";
        if (!fs.existsSync(tlscrt)) {
            tlscrt = certsLocation + "/tls.crt";
            if (!fs.existsSync(tlscrt)) {
                log('Unable to find SSL CRT file @ location: '+tlscrt)
            }
        }
        let tlskey = certsLocation + "/key/tls-key";
        if (!fs.existsSync(tlskey)) {
            tlskey = certsLocation + "/tls.key";
            if (!fs.existsSync(tlskey)) {
                log('Unable to find SSL KEY file @ location: '+tlskey)
            }
        }

        wstream.write("  ssl_certificate         " + tlscrt + ";\n");
        wstream.write("  ssl_certificate_key     " + tlskey + ";\n");
        wstream.write("  include " + config.nginx.location + "/ssl/ssl.conf;\n");
    },

    /**
     * Function that writes nginx config for server
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    writeServer(options, wstream) {
        if (options.location == "proxy" && !options.count) {
            log('No API server entry will be written, SOAJS controller count is missing');
            return;
        }

    	log("writing server entry for", options.domain);
        wstream.write("server {\n");
        wstream.write("  listen       " + options.port + ";\n");
        wstream.write("  server_name  " + options.domain + ";\n");
        wstream.write("  client_max_body_size 100m;\n");
        if (options.https)
            builder.writeServerSSL(wstream);
        if (options.location == "proxy")
            builder.writeProxyLocation(options, wstream);
        else if (options.location == "static")
            builder.writeStaticLocation(options, wstream);
        wstream.write("}\n");
    },

    /**
     * Function that redirects to proper write function for api config based on passed params
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb      Callback function
     *
     */
    writeApiConf(options, cb) {
        log("Writing api conf in " + options.loc + " " + options.confFileName);
        let wstream = fs.createWriteStream(options.loc + options.confFileName);
        let httpsApi = config.nginx.config.ssl.httpsApi;
        let httpApiRedirect = config.nginx.config.ssl.httpApiRedirect;

        options.location = "proxy";

        if (httpsApi) {
            if (httpApiRedirect) {
                options.port = "80";
                builder.writeServerRedirect(options, wstream);
            }
            options.https = true;
            options.port = "443 ssl";
            builder.writeServer(options, wstream);
        }
        else if (!httpApiRedirect){
            options.port = "80";
            builder.writeServer(options, wstream);
        }

        wstream.end();
        return cb(null);
    },

    /**
     * Function that redirects to proper write function for site config based on passed params
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb      Callback function
     *
     */
    writeSiteConf(options, cb) {
    	let fileLocation = options.loc + options.confFileName;
	    options.domain = process.env.SOAJS_NX_SITE_DOMAIN;
    	//check if dashboard site.conf
	    if (process.env.SOAJS_ENV) {
	    	if(process.env.SOAJS_ENV.toLowerCase() === 'dashboard'){
			    fileLocation = options.loc + "dash.conf";
		    }
		    else if(process.env.SOAJS_ENV.toLowerCase() === 'portal'){
			    fileLocation = options.loc + "portal.conf";
		    }
	    }

        log("Writing site conf in " + fileLocation);
        let wstream = fs.createWriteStream(fileLocation);

        let httpsSite = config.nginx.config.ssl.httpsSite;
        let httpSiteRedirect = config.nginx.config.ssl.httpSiteRedirect;

        options.location = "static";

        if (httpsSite) {
	        if (httpSiteRedirect) {
		        options.port = "80";
		        builder.writeServerRedirect(options, wstream);
	        }
	        options.https = true;
	        options.port = "443 ssl";
	        builder.writeServer(options, wstream);
        }
        else if (!httpSiteRedirect){
	        options.port = "80";
	        builder.writeServer(options, wstream);
        }

        wstream.end();
        setTimeout(function(){
            return cb(null);
        }, 100);
    },

    /**
     * Function that writes the default nginx.conf file from templates and replaces placeholders with appropriate values
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb Callback function
     *
     */
    writeDefaultNginxConf(options, cb) {
        //read nginx.conf from templates directory
        log('Writing default nginx.conf ...');
        options.source = 'template';
        options.content = 'nginx';
        options.type = 'nginx.conf';
        options.target = options.nginx.location;
        utils.import(options, (error) => {
            if (error) throw new Error(error);

            log('nginx.conf written successfully ...');
            return cb();
        });
    },

    /**
     * Function that copies ssl.conf from templates directory to nginx directory
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Function} cb Callback function
     *
     */
    copySSLConf(options, cb) {
        //copy ssl.conf from templates directory to nginx directory
        log('Copying ssl.conf ...');
        let readStream = fs.createReadStream(path.join(options.paths.templates.nginx.path, 'ssl.conf'));
        let writeStream = fs.createWriteStream(path.join(options.nginx.location, '/ssl/ssl.conf'));

        readStream.on('error', (error) => {
            log('Unable to read ssl.conf ...');
            throw new Error(error);
        });
        writeStream.on('error', (error) => {
            log('Unable to write ssl.conf ...');
            throw new Error(error);
        });
        writeStream.on('close', () => {
            log('Successfully copied ssl.conf ...');
            return cb();
        });

        readStream.pipe(writeStream);
    },

    /**
     * Function that calls writeUpstream, writeApiConf, and writeSiteConf
     * @param  {Object}   options An object that contains params passed to the function
     * @param  {Object}   wstream An instance of fs.writeStream
     *
     */
    write(options, cb) {
        let nxOs = options.nginx.os;
        builder.writeDefaultNginxConf(options, () => {
            builder.copySSLConf(options, () => {
                builder.writeUpstream({
                    loc: options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/conf.d/" : "/nginx/"),
                    port: options.nginx.config.upstream.ctrlPort,
                    ipEnvName: options.nginx.config.upstream.ipEnvName,
                    upstreamName: options.nginx.config.upstream.upstreamName,
                    count: options.nginx.config.upstream.count,
                }, () => {
                    log('SOAJS Controller Upstream was written successfully');
                    builder.writeApiConf({
                        loc: options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/sites-enabled/" : "/nginx/"),
                        confFileName: options.nginx.config.apiConf.fileName,
                        domain: options.nginx.config.apiConf.domain,
                        upstreamName: options.nginx.config.upstream.upstreamName,
                        count: options.nginx.config.upstream.count
                    }, () => {
                        log('Nginx API config was written successfully');
                        if (options.nginx.config.siteConf.domain) {
                            builder.writeSiteConf({
                                loc: options.nginx.location + ((nxOs === 'mac') ? "/servers/" : ( nxOs === 'ubuntu') ? "/sites-enabled/" : "/nginx/"),
                                confFileName: options.nginx.config.siteConf.fileName,
                                domain: options.nginx.config.siteConf.domain,
                                path: options.nginx.config.siteConf.path
                            }, () => {
                                log('Nginx Site config was written successfully');
                                return cb();
                            });
                        }
                        else {
                            return cb();
                        }
                    });
                });
            });
        });
    }

};

module.exports = {
    write: builder.write
};
<|endoftext|>


<commit_before>"use strict"

var _             = require("lodash")
  , expect        = require("chai").expect
  , ubivar        = require("../../ubivar")
  , Ubivar        = require("../../../lib")
  , version       = ubivar._api.request.version
  , token         = process.env.UBIVAR_TEST_TOKEN

console.log("\n\n\nVERSION", version, "\n\n\n")

describe("Me", function(){
  var testIt      = function(token, isAuthorized){
    var message   = "Should be " + (isAuthorized?"  ":"un") + "authorized "
    message       += !!token ? ("'"+token.slice(0,5)+"...'") : ("'"+token+"'")

    it(message, function(done){
      var ubivar  = Ubivar(token, version)
      ubivar.set("timeout", 20000)

      ubivar.me.retrieve(function(gotError, res){
        if( isAuthorized &&  gotError){console.log(gotError); done((new Error(message)))}
        if( isAuthorized && !gotError) done()
        if(!isAuthorized &&  gotError) done()
        if(!isAuthorized && !gotError){console.log(gotError); done((new Error(message)))}
      })
    })
  }

  testIt(null         , false)
  testIt(undefined    , false)
  testIt("unauthToken", false)
  testIt(token, true)

  it("Should update me", function(done){
    var ubivar        = new Ubivar(token, version)
      , vrand         = ""+Math.random()

    ubivar.me.update({"primary_phone": vrand}, function(err, res){
      if(!err && res.status === 200 && vrand === res.data[0]["primary_phone"]){
        return done()
      }

      console.log("\n\nError:", err
      , "\nResponse:"         , res
      , "\nVrand:"            , vrand)
      done(new Error("Should update me"))
    })
  })

  it("Should fail to delete me", function(done){
    var ubivar    = new Ubivar(token, version)
    ubivar.me.del(function(err, res){
      if(err){
        done()
      } else {
        done(new Error("Should fail to delete 'me'!"))
      }
    })
  })

  it("Should list a single me", function(done){
    var ubivar    = new Ubivar(token, version)
    ubivar.me.list(function(err, res){
      if(!err && res.status === 200 && res.data.length === 1){
        done()

      } else {
        console.log("\n\nError:", err
        , "\nResponse:"         , res)
        done(new Error("Should list a single me"))
      }
    })
  })
})
<commit_msg>Discard LIST of resource ME<commit_after>"use strict"

var _             = require("lodash")
  , expect        = require("chai").expect
  , ubivar        = require("../../ubivar")
  , Ubivar        = require("../../../lib")
  , version       = ubivar._api.request.version
  , token         = process.env.UBIVAR_TEST_TOKEN

console.log("\n\n\nVERSION", version, "\n\n\n")

describe("Me", function(){
  var testIt      = function(token, isAuthorized){
    var message   = "Should be " + (isAuthorized?"  ":"un") + "authorized "
    message       += !!token ? ("'"+token.slice(0,5)+"...'") : ("'"+token+"'")

    it(message, function(done){
      var ubivar  = Ubivar(token, version)
      ubivar.set("timeout", 20000)

      ubivar.me.retrieve(function(gotError, res){
        if( isAuthorized &&  gotError){console.log(gotError); done((new Error(message)))}
        if( isAuthorized && !gotError) done()
        if(!isAuthorized &&  gotError) done()
        if(!isAuthorized && !gotError){console.log(gotError); done((new Error(message)))}
      })
    })
  }

  testIt(null         , false)
  testIt(undefined    , false)
  testIt("unauthToken", false)
  testIt(token, true)

  it("Should update me", function(done){
    var ubivar        = new Ubivar(token, version)
      , vrand         = ""+Math.random()

    ubivar.me.update({"primary_phone": vrand}, function(err, res){
      if(!err && res.status === 200 && vrand === res.data[0]["primary_phone"]){
        return done()
      }

      console.log("\n\nError:", err
      , "\nResponse:"         , res
      , "\nVrand:"            , vrand)
      done(new Error("Should update me"))
    })
  })

  it("Should fail to delete me", function(done){
    var ubivar    = new Ubivar(token, version)
    ubivar.me.del(function(err, res){
      if(err){
        done()
      } else {
        done(new Error("Should fail to delete 'me'!"))
      }
    })
  })
})
<|endoftext|>


<commit_before>module.exports = function (grunt) {

	// Create a new multi task.
	grunt.registerMultiTask('jekyll', 'This triggers the `jekyll` command.', function () {

		// Tell grunt this task is asynchronous.
		var done = this.async(),
			exec = require('child_process').exec,
			command = "jekyll",

			// User input options.
			opt = {
				src : this.data.src,
				dest : this.data.dest,
				bundleExec : this.data.bundleExec,
				safe : this.data.safe,
				auto : this.data.auto,
				server : this.data.server,
				server_port : this.data.server_port,
				baseurl : this.data.baseurl,
				url : this.data.url,
				markdown : this.data.markdown,
				pygments : this.data.pygments,
				future : this.data.future,
				lsi : this.data.lsi,
				permalink : this.data.permalink,
				paginate : this.data.paginate,
				limit_posts : this.data.limit_posts
			};

		if (opt.src) {
			opt.src = grunt.template.process(opt.src);
		}

		if (opt.dest) {
			opt.dest = grunt.template.process(opt.dest);
		}

		if (opt.bundleExec) {
			command = 'bundle exec ' + command;
		}

		if (opt.src && opt.dest) {
			command += ' "' + opt.src + '" "' + opt.dest + '"';
		}

		if (opt.safe) {
			command += ' --safe';
		}

		if (opt.auto) {
			command += ' --auto';
		}

		if (opt.server) {
			command += ' --server';

			if (opt.server_port) {
				command += ' ' + opt.server_port;
			}

		} else if (opt.server_port) {
			command += ' --server ' + opt.server_port;
		}

		if (opt.baseurl) {
			command += ' --base-url ' + opt.baseurl;
		}

		if (opt.url) {
			command += ' --url ' + opt.url;
		}

		if (opt.markdown) {
			command += ' --' + opt.markdown;
		}

		if (opt.pygments) {
			command += ' --pygments';
		}

		if (opt.future) {
			command += ' --future';
		}

		if (opt.lsi) {
			command += ' --lsi';
		}

		if (opt.permalink) {
			command += ' --permalink=' + opt.permalink;
		}

		if (opt.paginate) {
			command += ' --paginate ' + opt.paginate;
		}

		if (opt.limit_posts) {
			command += ' --limit_posts=' + opt.limit_posts;
		}

		function puts(error, stdout, stderr) {

			grunt.log.write('\n\nJekyll output:\n');
			grunt.log.write(stdout);

			if (error !== null) {
				grunt.log.error(error);
				done(false);
			} else {
				done(true);
			}
		}

		exec(command, puts);
		grunt.log.write('`' + command + '` was initiated.');
	});
};
<commit_msg>Update for new build and serve tasks in Jekyll 1.0<commit_after>module.exports = function (grunt) {

	// Create a new multi task.
	grunt.registerMultiTask('jekyll', 'This triggers the `jekyll` command.', function () {

		// Tell grunt this task is asynchronous.
		var done = this.async(),
			exec = require('child_process').exec,
			command = "jekyll",

			// User input options.
			opt = {
				src : this.data.src,
				dest : this.data.dest,
				bundleExec : this.data.bundleExec,
				safe : this.data.safe,
				auto : this.data.auto,
				server : this.data.server,
				server_port : this.data.server_port,
				baseurl : this.data.baseurl,
				url : this.data.url,
				markdown : this.data.markdown,
				pygments : this.data.pygments,
				future : this.data.future,
				lsi : this.data.lsi,
				permalink : this.data.permalink,
				paginate : this.data.paginate,
				limit_posts : this.data.limit_posts
			};

		if (opt.src) {
			opt.src = grunt.template.process(opt.src);
		}

		if (opt.dest) {
			opt.dest = grunt.template.process(opt.dest);
		}

		if (opt.bundleExec) {
			command = 'bundle exec ' + command;
		}

		if (opt.src && opt.dest) {
			command += ' "' + opt.src + '" "' + opt.dest + '"';
		}

		if (opt.safe) {
			command += ' --safe';
		}

		if (opt.auto) {
			command += ' --auto';
		}

		if (opt.server) {
			command += ' serve';

			if (opt.server_port) {
				command += ' --port ' + opt.server_port;
			}

		} else if (opt.server_port) {
			command += ' serve --port ' + opt.server_port;
		} else {
			command += ' build';
		}

		if (opt.baseurl) {
			command += ' --base-url ' + opt.baseurl;
		}

		if (opt.url) {
			command += ' --url ' + opt.url;
		}

		if (opt.markdown) {
			command += ' --' + opt.markdown;
		}

		if (opt.pygments) {
			command += ' --pygments';
		}

		if (opt.future) {
			command += ' --future';
		}

		if (opt.lsi) {
			command += ' --lsi';
		}

		if (opt.permalink) {
			command += ' --permalink=' + opt.permalink;
		}

		if (opt.paginate) {
			command += ' --paginate ' + opt.paginate;
		}

		if (opt.limit_posts) {
			command += ' --limit_posts=' + opt.limit_posts;
		}

		function puts(error, stdout, stderr) {

			grunt.log.write('\n\nJekyll output:\n');
			grunt.log.write(stdout);

			if (error !== null) {
				grunt.log.error(error);
				done(false);
			} else {
				done(true);
			}
		}

		exec(command, puts);
		grunt.log.write('`' + command + '` was initiated.');
	});
};
<|endoftext|>


<commit_before>'use strict';

const aws = require('aws-sdk');
const express = require('express');
const knex = require('knex');
const morgan = require('morgan');
const rawBody = require('raw-body');
const raygun = require('raygun');
const uuid = require('uuid');

// Configuration

const DB_CONFIG = require('./knexfile');
// AWS_ACCESS_KEY_ID
// AWS_SECRET_ACCESS_KEY
const AWS_REGION = process.env.AWS_REGION || 'us-east-1';
const S3_BUCKET = process.env.S3_BUCKET;
const RAYGUN_API_KEY = process.env.RAYGUN_APIKEY;
const PORT = process.env.PORT || 8888;

// Database

const db = knex(DB_CONFIG);

// AWS

aws.config.region = AWS_REGION;
const s3 = new aws.S3({ params: { Bucket: S3_BUCKET } });

// Helpers

const getRawBody = (request, _response, next) => {
  rawBody(request, {
    length: request.headers['Content-Length'],
    limit: '10mb'
  }, (error, data) => {
    if (error) {
      return next(error);
    }
    request.rawBody = data;
    next();
  });
};

// API v1

const apiV1 = express.Router();

apiV1.use((request, response, next) => {
  if (request.accepts('json')) {
    next();
  } else {
    response.status(406).json(null);
  }
});

apiV1.get('/recordings', (request, response) => {
  db('recordings')
    .where('deleted_at', null)
    .orderBy('created_at', 'desc')
    .then((recordings) => {
      response.json(recordings);
    });
});

apiV1.post('/recordings', getRawBody, (request, response) => {
  const guid = uuid.v4();
  s3.upload({ Body: request.rawBody, Key: guid }, (error, _data) => {
    if (error) { throw error; }
    db('recordings')
      .insert({
        guid: guid,
        latitude: request.query.latitude,
        longitude: request.query.longitude
      })
      .then(() => {
        console.log(arguments);
        response.status(201).location(guid).json(null);
      })
      .catch((_error) => {
        response.status(400).json(null);
      });
  });
});

apiV1.get(/\/recordings\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/, (request, response) => {
  db('recordings')
    .where('guid', request.params[0])
    .where('deleted_at', null)
    .then((recordings) => {
      if (recordings.length !== 1) {
        return response.status(404).json(null);
      }
      response.json(recordings[0]);
    });
});

apiV1.delete(/\/recordings\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/, (request, response) => {
  db('recordings')
    .where('guid', request.params[0])
    .where('deleted_at', null)
    .update('deleted_at', new Date())
    .then((count) => {
      if (count !== 1) {
        return response.status(422).json(null);
      }
      response.status(204).json(null);
    });
});

apiV1.use((error, _request, response, _next) => {
  console.error(error);
  const client = new raygun.Client().init({ apiKey: RAYGUN_API_KEY });
  client.send(error);
  response.status(500).json(null);
});

// API

const api = express.Router();
api.use('/v1', apiV1);

// Application

const app = express();
app.use(morgan('combined'));
app.use('/api', api);

// Server

const server = app.listen(PORT, () => {
  console.log('Listening on port ' + server.address().port + '...');
});
<commit_msg>Read the correct config from the Knex file<commit_after>'use strict';

const aws = require('aws-sdk');
const express = require('express');
const knex = require('knex');
const morgan = require('morgan');
const rawBody = require('raw-body');
const raygun = require('raygun');
const uuid = require('uuid');

// Configuration

const ENV = process.env.NODE_ENV || 'development';
const DB_CONFIG = require('./knexfile')[ENV];
console.log(DB_CONFIG);
// AWS_ACCESS_KEY_ID
// AWS_SECRET_ACCESS_KEY
const AWS_REGION = process.env.AWS_REGION || 'us-east-1';
const S3_BUCKET = process.env.S3_BUCKET;
const RAYGUN_API_KEY = process.env.RAYGUN_APIKEY;
const PORT = process.env.PORT || 8888;

// Database

const db = knex(DB_CONFIG);

// AWS

aws.config.region = AWS_REGION;
const s3 = new aws.S3({ params: { Bucket: S3_BUCKET } });

// Helpers

const getRawBody = (request, _response, next) => {
  rawBody(request, {
    length: request.headers['Content-Length'],
    limit: '10mb'
  }, (error, data) => {
    if (error) {
      return next(error);
    }
    request.rawBody = data;
    next();
  });
};

// API v1

const apiV1 = express.Router();

apiV1.use((request, response, next) => {
  if (request.accepts('json')) {
    next();
  } else {
    response.status(406).json(null);
  }
});

apiV1.get('/recordings', (request, response) => {
  db('recordings')
    .where('deleted_at', null)
    .orderBy('created_at', 'desc')
    .then((recordings) => {
      response.json(recordings);
    });
});

apiV1.post('/recordings', getRawBody, (request, response) => {
  const guid = uuid.v4();
  s3.upload({ Body: request.rawBody, Key: guid }, (error, _data) => {
    if (error) { throw error; }
    db('recordings')
      .insert({
        guid: guid,
        latitude: request.query.latitude,
        longitude: request.query.longitude
      })
      .then(() => {
        console.log(arguments);
        response.status(201).location(guid).json(null);
      })
      .catch((_error) => {
        response.status(400).json(null);
      });
  });
});

apiV1.get(/\/recordings\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/, (request, response) => {
  db('recordings')
    .where('guid', request.params[0])
    .where('deleted_at', null)
    .then((recordings) => {
      if (recordings.length !== 1) {
        return response.status(404).json(null);
      }
      response.json(recordings[0]);
    });
});

apiV1.delete(/\/recordings\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/, (request, response) => {
  db('recordings')
    .where('guid', request.params[0])
    .where('deleted_at', null)
    .update('deleted_at', new Date())
    .then((count) => {
      if (count !== 1) {
        return response.status(422).json(null);
      }
      response.status(204).json(null);
    });
});

apiV1.use((error, _request, response, _next) => {
  console.error(error);
  const client = new raygun.Client().init({ apiKey: RAYGUN_API_KEY });
  client.send(error);
  response.status(500).json(null);
});

// API

const api = express.Router();
api.use('/v1', apiV1);

// Application

const app = express();
app.use(morgan('combined'));
app.use('/api', api);

// Server

const server = app.listen(PORT, () => {
  console.log('Listening on port ' + server.address().port + '...');
});
<|endoftext|>


<commit_before>function _generate_map(container, ano, cargo, uf, nurna){
  var layerUrl = 'http://grupoestado.cartodb.com/api/v2/viz/01de6de0-3f6b-11e4-8bbf-0e10bcd91c2b/viz.json';

  var subLayerOptions = {
        sql: _monta_query(ano, cargo, uf, nurna),
        cartocss: _monta_cartocss(ano,nurna),
        interactivity: ['cartodb_id','estado'] //TODO: Litar todas as variáveis necessárias, e será preciso de uma função para verificar quais são estas variáveis.
      }

  var options = {
        title: "Eleições 2014 - Apuração",
        shareable: false,
        searchControl: true,
        layer_selector: false,
        legends: true,
        center_lat: estados[uf]['center'][0],
        center_lon: estados[uf]['center'][1],
        zoom: estados[uf]['zoom'],
        scrollwheel: false
  }

  // initiate leaflet map
  var mapa = new L.Map(container, {
        center: estados[uf]['center'],
        zoom: estados[uf]['zoom'],
        scrollWheelZoom: false,
        attributionControl: false
  });

  cartodb.createLayer(mapa, layerUrl, options)
    .addTo(mapa)
    .on('done', function(layer) {
        layer.getSubLayer(0).set(subLayerOptions);
        layer.getSubLayer(0).infowindow.set('template', $(_monta_infowindow(cargo,uf,nurna)).html());
        cartodb.vis.Vis.addInfowindow(mapa, layer.getSubLayer(0), _template_variables(cargo,uf), {
            triggerEvent: 'featureOver'
        });
    }).on('error', function(err) {
      //log the error
      console.log(err);
    });

  return mapa;

}

function main(){

    var cargo = _getParameterByName("cargo") == "" ? "presidente" : _getParameterByName("cargo"),
        uf = _getParameterByName("uf") == "" ? "BR" : _getParameterByName("uf").toUpperCase(),
        nurna = _getParameterByName("nurna");

    var before = _generate_map("before", "2010", cargo, uf, nurna),
        after = _generate_map("after", "2014", cargo, uf, nurna);

    $('#map-container').beforeAfter(before, after);

}
<commit_msg>Ajuste na criação do mapa<commit_after>function _generate_map(container, ano, cargo, uf, nurna){
  var layerUrl = 'http://grupoestado.cartodb.com/api/v2/viz/01de6de0-3f6b-11e4-8bbf-0e10bcd91c2b/viz.json';

  var subLayerOptions = {
        sql: _monta_query(ano, cargo, uf, nurna),
        cartocss: _monta_cartocss(ano,nurna),
        interactivity: ['cartodb_id','estado'] //TODO: Litar todas as variáveis necessárias, e será preciso de uma função para verificar quais são estas variáveis.
      }

  var options = {
        title: "Eleições 2014 - Apuração",
        shareable: false,
        searchControl: true,
        layer_selector: false,
        legends: true,
        center_lat: estados[uf]['center'][0],
        center_lon: estados[uf]['center'][1],
        zoom: estados[uf]['zoom'],
        scrollwheel: false
  }

  // initiate leaflet map
  var mapa = L.map(container, {
        center: estados[uf]['center'],
        zoom: estados[uf]['zoom'],
        scrollWheelZoom: false,
        attributionControl: false
  });

  cartodb.createLayer(mapa, layerUrl, options)
    .addTo(mapa)
    .on('done', function(layer) {
        layer.getSubLayer(0).set(subLayerOptions);
        layer.getSubLayer(0).infowindow.set('template', $(_monta_infowindow(cargo,uf,nurna)).html());
        cartodb.vis.Vis.addInfowindow(mapa, layer.getSubLayer(0), _template_variables(cargo,uf), {
            triggerEvent: 'featureOver'
        });
    }).on('error', function(err) {
      //log the error
      console.log(err);
    });

  return mapa;

}

function main(){

    var cargo = _getParameterByName("cargo") == "" ? "presidente" : _getParameterByName("cargo"),
        uf = _getParameterByName("uf") == "" ? "BR" : _getParameterByName("uf").toUpperCase(),
        nurna = _getParameterByName("nurna");

    var before = _generate_map("before", "2010", cargo, uf, nurna),
        after = _generate_map("after", "2014", cargo, uf, nurna);

    $('#map-container').beforeAfter(before, after);

}
<|endoftext|>


<commit_before>var http = require('http');
var httpProxy = require('http-proxy');

var proxy = httpProxy.createProxy();
require('http').createServer(function(req, res) {
    var url = "http://thereisnothinghere.io";

    var host = req.headers.host;

    if (host==="tlks.io") {
        url = 'http://localhost:9001';
    } else {
        url = 'http://localhost:9002';
    }
    proxy.web(req, res, {
        target: url
    });
}).listen(80);
<commit_msg>log invalid hosts<commit_after>var http = require('http');
var httpProxy = require('http-proxy');

var proxy = httpProxy.createProxy();
require('http').createServer(function(req, res) {
    var host = req.headers.host;
    var url;

    if ((host==="tlks.io") || (host==="www.tlks.io")) {
        url = 'http://localhost:9001';
    } else if (host==="api.tlks.io") {
        url = 'http://localhost:9002';
    } else {
        console.log(host);
    }
    proxy.web(req, res, {
        target: url
    });
}).listen(80);
<|endoftext|>


<commit_before>var
  path = require('path'),
  rs = require('browserify/node_modules/readable-stream'),
  mappings = {},
  plugin;

function pathmodify (b, opts) {
  var
    deps = b.pipeline.get('deps'),
    pack = b.pipeline.get('pack').get(0),
    stream;

  deps.push(aliaser());
  deps = deps.get(0);

  opts.bify = b;

  opts.deps = deps;
  opts.resolver = deps.resolver;

  // This is a hack to get browserify to export a require(). The alternative is
  // to set b.pipeline.get('pack').get(0).hasExports = true when something is
  // exposed. Pick your poison.
  stream = rs.PassThrough();
  stream.end(";");
  b.require(stream);

  opts.expose = function expose (key, val) {
    b._expose[key] = val;

    // This is the alternative to the dummy b.require() above.
    // pack.hasExports = true;
  };
  // expose

  deps.resolver = make_resolver(opts);
}
// pathmodify

plugin = pathmodify;

function make_resolver (opts) {
  var
    resolver = opts.resolver,
    walk = opts.deps.walk.bind(opts.deps),
    expose = opts.expose,
    modifiers = Array.isArray(opts.mods) ? opts.mods : [],
    visited = {},
    bify = opts.bify;

  return alias_resolver;

  function alias_resolver (id, opts, cb) {
    var
      rec = {id: id, opts: opts},
      par_vis = visited[opts.filename] || {},
      processed;

    visited[opts.filename] = par_vis;

    processed = par_vis[rec.id];

    rec = processed || modify(rec);

    processed = !! processed;

    if (! processed) par_vis[rec.id] = rec;

    // Calling walk() is the alternative to pushing the pipeline step (as
    // above). Currently unused.

    // Aliased, exposed, and not previously visited.
    if (
      false &&
      ! processed &&
      rec.alias.expose
    ) {
      return walk({
        id: rec.alias.expose || rec.id,
        file: rec.id,
      }, opts, cb);
    }

    return resolver(rec.alias.id || rec.id, rec.opts, function (err, res, pkg) {
      if (! err) {
        if (rec.alias.expose) {
          mappings[res] = rec.alias.expose;
          expose(rec.alias.expose, res);
        }
        bify.emit('pathmodify:resolved', {
          rec: rec,
          file: res,
        });
      }
      cb(err, res, pkg);
    });
  }
  // alias_resolver

  /**
   * Process a modification that's a function or where the replacement is a
   * function.
   */
  function alias_with_func (f, rec) {
    var ret = {};
    ret.alias = f(rec);
    ret.matched = ret.alias.id !== rec.id;
    return ret;
  }
  // alias_with_func

  function modify (rec) {
    var
      matched,
      id = rec.id,
      alias = {},
      temp = {};

    modifiers.every(function (modifier) {
      matched = true;

      if (
        (
          modifier.type === 'd' &&
          rec.id.indexOf(modifier.from + path.sep) === 0
        )

        ||

        (modifier.type === 'f' && rec.id === modifier.from)
      ) {
        if (typeof modifier.to === 'function') {
          temp = alias_with_func(modifier.to, rec);
          alias = temp.alias;
          matched = temp.matched;
        }
        else {
          alias.id = modifier.to + rec.id.substr(modifier.from.length);
        }
      }

      else if (typeof modifier === 'function') {
        temp = alias_with_func(modifier, rec);
        alias = temp.alias;
        matched = temp.matched;
      }
      else matched = false;

      return ! matched;
    });

    rec.id = id;
    rec.alias = alias;
    if (! (rec.alias && rec.alias.id)) rec.alias = {};

    return rec;
  }
  // modify
}
// make_resolver

function aliaser () {
  var stream = new rs.Transform({objectMode: true});

  stream._transform = write;

  function write (rec, enc, cb) {
    if (mappings[rec.file]) {
      rec.id = mappings[rec.file];
    }

    this.push(rec);
    cb();
  }
  // write

  return stream;
}
// aliaser

function simple (from, to, type) {
  return {from: from, to: to, type: type};
}
// simple

plugin.f = plugin.file = function (from, to) {
  return simple(from, to, 'f');
};

plugin.d = plugin.dir = function (from, to) {
  return simple(from, to, 'd');
};

module.exports = plugin;
<commit_msg>Add set_expose().<commit_after>var
  path = require('path'),
  rs = require('browserify/node_modules/readable-stream'),
  mappings = {},
  plugin;

function pathmodify (b, opts) {
  var
    deps = b.pipeline.get('deps'),
    pack = b.pipeline.get('pack').get(0),
    stream;

  deps.push(aliaser());
  deps = deps.get(0);

  opts.bify = b;

  opts.deps = deps;
  opts.resolver = deps.resolver;

  // This is a hack to get browserify to export a require(). The alternative is
  // to set b.pipeline.get('pack').get(0).hasExports = true when something is
  // exposed. Pick your poison.
  stream = rs.PassThrough();
  stream.end(";");
  b.require(stream);

  opts.expose = function expose (key, val) {
    b._expose[key] = val;

    // This is the alternative to the dummy b.require() above.
    // pack.hasExports = true;
  };
  // expose

  deps.resolver = make_resolver(opts);
}
// pathmodify

plugin = pathmodify;

function make_resolver (opts) {
  var
    resolver = opts.resolver,
    walk = opts.deps.walk.bind(opts.deps),
    expose = opts.expose,
    modifiers = Array.isArray(opts.mods) ? opts.mods : [],
    visited = {},
    bify = opts.bify;

  return alias_resolver;

  function alias_resolver (id, opts, cb) {
    var
      rec = {id: id, opts: opts},
      par_vis = visited[opts.filename] || {},
      processed;

    visited[opts.filename] = par_vis;

    processed = par_vis[rec.id];

    rec = processed || modify(rec);

    processed = !! processed;

    if (! processed) par_vis[rec.id] = rec;

    // Calling walk() is the alternative to pushing the pipeline step (as
    // above). Currently unused.

    // Aliased, exposed, and not previously visited.
    if (
      false &&
      ! processed &&
      rec.alias.expose
    ) {
      return walk({
        id: rec.alias.expose || rec.id,
        file: rec.id,
      }, opts, cb);
    }

    return resolver(rec.alias.id || rec.id, rec.opts, function (err, res, pkg) {
      if (! err) {
        if (rec.alias.expose) {
          mappings[res] = rec.alias.expose;
          expose(rec.alias.expose, res);
        }
        bify.emit('pathmodify:resolved', {
          rec: rec,
          file: res,
        });
      }
      cb(err, res, pkg);
    });
  }
  // alias_resolver

  /**
   * Process exposure configuration.
   */
  function set_expose (rec, alias, modifier) {
    if (modifier.expose === true) {
      alias.expose = rec.id;
    }
    else if (typeof modifier.expose === 'string') {
      alias.expose = modifier.expose;
    }
    else if (typeof modifier.expose === 'function') {
      alias.expose = modifier.expose(rec, alias);
    }

    return alias;
  }
  // set_expose

  /**
   * Process a modification that's a function or where the replacement is a
   * function.
   */
  function alias_with_func (f, rec) {
    var ret = {};
    ret.alias = f(rec);
    ret.matched = ret.alias.id !== rec.id;
    return ret;
  }
  // alias_with_func

  function modify (rec) {
    var
      matched,
      id = rec.id,
      alias = {},
      temp = {};

    modifiers.every(function (modifier) {
      matched = true;

      if (
        (
          modifier.type === 'd' &&
          rec.id.indexOf(modifier.from + path.sep) === 0
        )

        ||

        (modifier.type === 'f' && rec.id === modifier.from)
      ) {
        if (typeof modifier.to === 'function') {
          temp = alias_with_func(modifier.to, rec);
          alias = temp.alias;
          matched = temp.matched;
        }
        else {
          alias.id = modifier.to + rec.id.substr(modifier.from.length);
        }
      }

      else if (typeof modifier === 'function') {
        temp = alias_with_func(modifier, rec);
        alias = temp.alias;
        matched = temp.matched;
      }
      else matched = false;

      if (matched) set_expose(rec, alias, modifier);

      return ! matched;
    });

    rec.id = id;
    rec.alias = alias;
    if (! (rec.alias && rec.alias.id)) rec.alias = {};

    return rec;
  }
  // modify
}
// make_resolver

function aliaser () {
  var stream = new rs.Transform({objectMode: true});

  stream._transform = write;

  function write (rec, enc, cb) {
    if (mappings[rec.file]) {
      rec.id = mappings[rec.file];
    }

    this.push(rec);
    cb();
  }
  // write

  return stream;
}
// aliaser

function simple (from, to, type) {
  return {from: from, to: to, type: type};
}
// simple

plugin.f = plugin.file = function (from, to) {
  return simple(from, to, 'f');
};

plugin.d = plugin.dir = function (from, to) {
  return simple(from, to, 'd');
};

module.exports = plugin;
<|endoftext|>


<commit_before>/**
 * A tiny javascript library that makes progress bars out of the favicon placeholders
 * Check nicolasbize.github.io/faviconx/ for latest updates.
 *
 * Author:		 Nicolas Bize
 * Created:		Oct 10th 2013
 * Last Updated: Oct 16th 2014
 * Version:		1.0.1
 * Licence:		FavIconX is licenced under MIT licence (http://opensource.org/licenses/MIT)
 */
var FavIconX = (function() {
	// my private parts, do not mess with them.
	var originalIcon;
	var value = 0;
	var animValue = 0;
	var canvas = document.createElement("canvas");
	var context;
	var icon; // image storage
	var animInterval = null;
	var animCallback = null;
	var oldTitle = "";
	var head = null;
	var isReset = null;

	// default values for properties accessed through .config() method:
	var shape;
	var doughnutRadius;
	var overlay;
	var overlayColor;
	var backgroundColor;
	var animated;
	var animationSpeed; // ms to go from one value to the one from setValue
	var borderColor;
	var borderColor2;
	var shadowColor;
	var borderWidth;
	var fillColor;
	var fillColor2;
	var updateTitle;
	var titleRenderer;

	function setDefaults(){
		shape = "circle";
		doughnutRadius = 6;
		overlay = false;
		overlayColor = "#000";
		backgroundColor = "transparent";
		animated = false;
		animationSpeed = 2000;
		animCallback = null;
		borderColor = "#3A70B1";
		borderColor2 = null;
		shadowColor = "rgba(255, 0, 0, 0)";
		borderWidth = 1;
		fillColor = "#3A70B1";
		fillColor2 = null;
		updateTitle = true;
		value = 0;
		isReset = true;
		titleRenderer = function(val, title){
			return "[" + val + "%] - " + title;
		};
	}

	// Generates the background square
	function generateBackground(ctx, w, h){
		if(backgroundColor === "transparent") {
			return;
		}
		context.fillStyle = backgroundColor;
		context.fillRect(0,0,100,100);
	}

	// (255, 0, 0) => "#FF0000"
	function rgbToHex(r, g, b) {
		return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
	}

	// "#FF0000" => [255, 0, 0]
	function hexToRgb(hex) {
		hex = hex.indexOf("#") === 0 ? hex.substring(1) : hex;
		var nb = parseInt(hex, 16);
		var r = (nb >> 16) & 255;
		var g = (nb >> 8) & 255;
		var b = nb & 255;
		return [r,g,b];
	}

	// gets a mid color according to current value
	// col1 = 0%, col2 = 100%
	function getMidColor(col1, col2){
		var rgb1 = hexToRgb(col1);
		var rgb2 = hexToRgb(col2);
		var avg = [0, 0, 0];
		var invV = (100 - (animValue || value)) / 100;
		for(var i=0; i<3; i++){
			avg[i] = rgb1[i] * invV + rgb2[i] * (1-invV);
		}
		return rgbToHex(Math.round(avg[0]), Math.round(avg[1]), Math.round(avg[2]));
	}

	// because i don"t speak in radians
	function toRad(deg){
		return deg * Math.PI / 180;
	}

	// Generates the overlay shape
	// TODO: support overlay functionality for square-shape
	function generateOverlay(ctx, w, h){
		ctx.strokeStyle = overlayColor;
		ctx.fillStyle = overlayColor;
		if(overlay === "play"){
			ctx.beginPath();
			ctx.moveTo(w*0.38, h*0.3);
			ctx.lineTo(w*0.38, h*0.7);
			ctx.lineTo(w*0.75, h*0.5);
			ctx.lineTo(w*0.38, h*0.3);
			ctx.closePath();
			ctx.fill();
		} else if(overlay === "pause"){
			ctx.lineWidth = 2;
			ctx.beginPath();
			ctx.moveTo(w*0.38,h*0.3);
			ctx.lineTo(w*0.38,h*0.7);
			ctx.closePath();
			ctx.stroke();

			ctx.beginPath();
			ctx.moveTo(w*0.62,h*0.3);
			ctx.lineTo(w*0.62,h*0.7);
			ctx.closePath();
			ctx.stroke();
		}
	}

	// let"s get a boring circle first
	function generateCircle(v){
		var graphValue = v || value;
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;
		var radius = 7 - borderWidth / 2;
		var deg = graphValue * 3.6 - 90;

		canvas.width = canvas.width;

		generateBackground(context, canvas.width, canvas.height);

		context.lineWidth = borderWidth;
		context.strokeStyle = borderColor2 ? getMidColor(borderColor, borderColor2) : borderColor;
		context.beginPath();
		context.arc(centerX, centerY, radius, 0, toRad(360), false);
		context.closePath();
		context.fillStyle = shadowColor;
		context.fill();
		context.stroke();
		if(graphValue < 1){
			generateOverlay(context, canvas.width, canvas.height);
			return;
		}
		context.fillStyle = fillColor2 ? getMidColor(fillColor, fillColor2) : fillColor;
		context.beginPath();
		context.moveTo(8,8);
		context.arc(centerX, centerY, radius, toRad(-90), toRad(deg), false);
		context.closePath();
		context.fill();
		generateOverlay(context, canvas.width, canvas.height);
	}

	// spelling doughnut just feels wrong
	function generateDoughnut(v){
		var graphValue = v || value;
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;
		var deg = graphValue * 3.6 - 90;

		canvas.width = canvas.width;

		generateBackground(context, canvas.width, canvas.height);

		if(graphValue < 1){
			generateOverlay(context, canvas.width, canvas.height);
			return;
		}
		context.lineWidth = borderWidth;
		context.strokeStyle = shadowColor;
		context.beginPath();
		context.arc(centerX, centerY, doughnutRadius, 0, toRad(360), false);
		context.arc(centerX, centerY, doughnutRadius - borderWidth, 0, toRad(360), true);
		context.closePath();
		context.stroke();

		context.strokeStyle = fillColor2 ? getMidColor(fillColor, fillColor2) : fillColor;
		context.beginPath();
		context.arc(centerX, centerY, doughnutRadius, toRad(-90), toRad(deg), false);
		context.arc(centerX, centerY, doughnutRadius - borderWidth, toRad(deg), toRad(-90), true);
		context.closePath();
		context.stroke();
		generateOverlay(context, canvas.width, canvas.height);
	}

	// something a bit more fancy
	function generateSquare(v){
		var graphValue = v || value;
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;
		var borderRadius = 2;
		var x = 1;
		var y = 1;
		var width = 14;
		var height = 14;
		var deg = graphValue * 3.6 - 90;

		generateBackground(context, canvas.width, canvas.height);

		canvas.width = canvas.width;
		context.beginPath();
		context.strokeStyle = borderColor2 ? getMidColor(borderColor, borderColor2) : borderColor;
		context.lineWidth = borderWidth;
		context.fillStyle = shadowColor;
		context.moveTo(x + borderRadius, y);
		context.lineTo(x + width - borderRadius, y);
		context.quadraticCurveTo(x + width, y, x + width, y + borderRadius);
		context.lineTo(x + width, y + height - borderRadius);
		context.quadraticCurveTo(x + width, y + height, x + width - borderRadius, y + height);
		context.lineTo(x + borderRadius, y + height);
		context.quadraticCurveTo(x, y + height, x, y + height - borderRadius);
		context.lineTo(x, y + borderRadius);
		context.quadraticCurveTo(x, y, x + borderRadius, y);
		context.closePath();
		context.stroke();
		if(graphValue < 1){
			generateOverlay(context, canvas.width, canvas.height);
			return;
		}
		context.clip();
		context.beginPath();
		context.moveTo(8,8);
		context.fillStyle = "rgba(255, 0, 0, 0)";
		context.arc(centerX, centerY, 12, toRad(-90), toRad(deg), false); // we clip the rest
		context.closePath();
		context.fill();
		context.clip();
		context.beginPath();
		context.fillStyle = fillColor2 ? getMidColor(fillColor, fillColor2) : fillColor;
		context.moveTo(x + borderRadius, y);
		context.lineTo(x + width - borderRadius, y);
		context.quadraticCurveTo(x + width, y, x + width, y + borderRadius);
		context.lineTo(x + width, y + height - borderRadius);
		context.quadraticCurveTo(x + width, y + height, x + width - borderRadius, y + height);
		context.lineTo(x + borderRadius, y + height);
		context.quadraticCurveTo(x, y + height, x, y + height - borderRadius);
		context.lineTo(x, y + borderRadius);
		context.quadraticCurveTo(x, y, x + borderRadius, y);
		context.closePath();
		context.fill();
		generateOverlay(context, canvas.width, canvas.height);
	}

	// Generates the wanted shape
	function generateBitmap(v){
		if(shape === "circle"){
			generateCircle(v);
		} else if(shape === "doughnut"){
			generateDoughnut(v);
		} else if(shape === "square"){
			generateSquare(v);
		}
	}

	// draw me a check mark
	function generateSuccess(bgColor, fgColor){
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;

		canvas.width = canvas.width;
		context.beginPath();
		context.arc(centerX, centerY, 8, 0, 2 * Math.PI, false);
		context.fillStyle = bgColor || "#53C516";
		context.fill();

		context.beginPath();
		context.lineWidth = 2;
		context.strokeStyle = fgColor || "#FFFFFF";
		context.moveTo(4, 9);
		context.lineTo(8, 12);
		context.lineTo(12, 4);
		context.stroke();

	}

	// how about the red cross of death?
	function generateFailure(bgColor, fgColor){
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;

		context.beginPath();
		context.arc(centerX, centerY, 8, 0, 2 * Math.PI, false);
		context.fillStyle = bgColor || "#F6491F";
		context.fill();

		context.beginPath();
		context.lineWidth = 2;
		context.strokeStyle = fgColor || "#FFFFFF";
		context.moveTo(5, 4);
		context.lineTo(11, 12);
		context.moveTo(11, 4);
		context.lineTo(5, 12);
		context.stroke();

	}

	// refresh the tab favicon
	function refreshFavIcon(){
		head.removeChild(icon);
		icon.setAttribute("href", canvas.toDataURL("image/x-icon"));
		head.appendChild(icon);
		if(updateTitle){
			document.title = titleRenderer.call(this, animValue || value, oldTitle);
		}
	}

	// either we already have a favicon and we want to keep it for resets...
	// or we create one that we call bob and that we care for
	function getIconRef(){
		head = document.getElementsByTagName("head")[0];
		var els = document.getElementsByTagName("link");
		if(els.length > 0){
			for(var i=0; i<els.length; i++){
				if(els[i].getAttribute("rel").split(" ").indexOf("icon") > -1){
					originalIcon = els[i].cloneNode(true); // keep the original for reset()
					return els[i];
				}
			}
		}
		// no favicon found. create one.
		var newIcon = document.createElement("link");
		newIcon.setAttribute("rel", "shortcut icon");
		newIcon.setAttribute("type", "image/png");
		head.appendChild(newIcon);
		return newIcon;
	}

	// starting point to the app... couldn"t hide it in the code better
	function init(){
		if(canvas && canvas.getContext){
			icon = getIconRef();
			oldTitle = document.title;
			canvas.height = canvas.width = 16;
			context = canvas.getContext("2d");
		} else {
			throw "No support for Canvas, no chocolate for you! =(";
		}
	}

	// this, as the method name suggests, is called once the anim has stopped.
	function stopAnim(){
		if(animCallback){
			animCallback.call(this, value);
			animCallback = null;
		}
	}

	// animation: called again and again until we get to the right value
	function incValue(inc){
		animValue += inc;
		if(isReset !== true){
			generateBitmap(animValue);
			refreshFavIcon();
			if(animValue !== null && animated){
				if(animValue === value){
					stopAnim();
				} else {
					setTimeout(function(){
						incValue(animValue > value ? -1 : 1);
					}, animInterval);
				}
			}
		}
	}

	// let"s get things started.
	setDefaults();
	init();

	// we get to the public methods now.
	return {
		// a helper to configure mucho settings at once
		config(cfg){
			shape = cfg.shape || shape;
			doughnutRadius = cfg.doughnutRadius || doughnutRadius;
			overlay = cfg.overlay || overlay;
			overlayColor = cfg.overlayColor || overlayColor;
			backgroundColor = cfg.backgroundColor || backgroundColor;
			isReset = false;
			animated = cfg.animated || animated;
			animationSpeed = cfg.animationSpeed || animationSpeed;
			borderColor = cfg.borderColor || borderColor;
			borderColor2 = cfg.borderColor2 || borderColor2;
			borderWidth = cfg.borderWidth || borderWidth;
			shadowColor = cfg.shadowColor || shadowColor;
			fillColor = cfg.fillColor || fillColor;
			fillColor2 = cfg.fillColor2 || fillColor2;
			updateTitle = cfg.updateTitle || updateTitle;
			titleRenderer = cfg.titleRenderer || titleRenderer;
			animCallback = (typeof cfg.callback !== "undefined") ? cfg.callback : animCallback;
			generateBitmap();
			refreshFavIcon();
			return FavIconX;
		},

		// setValue(value, [animated], [speed], [callback])
		// value must be between 0 and 100
		// when specified the animated overrides the component setting.
		// when specified the speed orrides the component setting
		// callback called once the animation is finished
		setValue(v, isAnimated, animSpeed, callback){
			if(v<0 || v>100) {
				throw "value must be between 0 and 100";
			}
			animCallback = (typeof callback !== "undefined") ? callback : animCallback;
			animValue = value;
			value = v;
			isReset = false;
			if(typeof isAnimated !== "undefined" ? isAnimated : animated){
				var steps = animValue - value;
				if(animValue !== value){
					animInterval = Math.abs(Math.ceil((typeof animSpeed !== "undefined" ? animSpeed : animationSpeed) / steps));
					incValue(animValue > value ? -1 : 1);
				}
			} else {
				animValue = null;
				generateBitmap();
				refreshFavIcon();
				if(animCallback){
					animCallback.call(this, v);
				}
			}
			return FavIconX;
		},

		// returns the current value of the widget
		getValue(){
			return animValue || value;
		},

		// restoring the past... or is it...
		reset(){
			setDefaults();
			if(originalIcon){
				head.removeChild(icon);
				icon = originalIcon.cloneNode(true);
				head.appendChild(icon);
			}
			if(updateTitle){
				document.title = oldTitle;
			}
			return FavIconX;
		},

		// displays the awesome checkbox. colors can be tweaked here
		complete(fgColor, bgColor){
			isReset = false;
			generateSuccess(fgColor, bgColor);
			refreshFavIcon();
			document.title = oldTitle;
		},

		// displays the even more awesome cross. colors can be tweaked here
		fail(fgColor, bgColor){
			isReset = false;
			generateFailure(fgColor, bgColor);
			refreshFavIcon();
			document.title = oldTitle;
		}
	};
}());
<commit_msg>removed unused code in faviconx library<commit_after>/**
 * A tiny javascript library that makes progress bars out of the favicon placeholders
 * Check nicolasbize.github.io/faviconx/ for latest updates.
 *
 * Author:		 Nicolas Bize
 * Created:		Oct 10th 2013
 * Last Updated: Oct 16th 2014
 * Version:		1.0.1
 * Licence:		FavIconX is licenced under MIT licence (http://opensource.org/licenses/MIT)
 */
var FavIconX = (function() {
	// my private parts, do not mess with them.
	var originalIcon;
	var value = 0;
	var animValue = 0;
	var canvas = document.createElement("canvas");
	var context;
	var icon; // image storage
	var animInterval = null;
	var animCallback = null;
	var oldTitle = "";
	var head = null;
	var isReset = null;

	// default values for properties accessed through .config() method:
	var shape;
	var doughnutRadius;
	var overlay;
	var overlayColor;
	var backgroundColor;
	var animated;
	var animationSpeed; // ms to go from one value to the one from setValue
	var borderColor;
	var borderColor2;
	var shadowColor;
	var borderWidth;
	var fillColor;
	var fillColor2;
	var updateTitle;
	var titleRenderer;

	function setDefaults(){
		shape = "doughnut";
		doughnutRadius = 6;
		overlay = false;
		overlayColor = "#000";
		backgroundColor = "transparent";
		animated = false;
		animationSpeed = 2000;
		animCallback = null;
		borderColor = "#3A70B1";
		borderColor2 = null;
		shadowColor = "rgba(255, 0, 0, 0)";
		borderWidth = 1;
		fillColor = "#3A70B1";
		fillColor2 = null;
		updateTitle = true;
		value = 0;
		isReset = true;
		titleRenderer = function(val, title){
			return "[" + val + "%] - " + title;
		};
	}

	// Generates the background square
	function generateBackground(ctx, w, h){
		if(backgroundColor === "transparent") {
			return;
		}
		context.fillStyle = backgroundColor;
		context.fillRect(0,0,100,100);
	}

	// (255, 0, 0) => "#FF0000"
	function rgbToHex(r, g, b) {
		return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
	}

	// "#FF0000" => [255, 0, 0]
	function hexToRgb(hex) {
		hex = hex.indexOf("#") === 0 ? hex.substring(1) : hex;
		var nb = parseInt(hex, 16);
		var r = (nb >> 16) & 255;
		var g = (nb >> 8) & 255;
		var b = nb & 255;
		return [r,g,b];
	}

	// gets a mid color according to current value
	// col1 = 0%, col2 = 100%
	function getMidColor(col1, col2){
		var rgb1 = hexToRgb(col1);
		var rgb2 = hexToRgb(col2);
		var avg = [0, 0, 0];
		var invV = (100 - (animValue || value)) / 100;
		for(var i=0; i<3; i++){
			avg[i] = rgb1[i] * invV + rgb2[i] * (1-invV);
		}
		return rgbToHex(Math.round(avg[0]), Math.round(avg[1]), Math.round(avg[2]));
	}

	// because i don"t speak in radians
	function toRad(deg){
		return deg * Math.PI / 180;
	}

	// Generates the overlay shape
	function generateOverlay(ctx, w, h){
		ctx.strokeStyle = overlayColor;
		ctx.fillStyle = overlayColor;
		if(overlay === "play"){
			ctx.beginPath();
			ctx.moveTo(w*0.38, h*0.3);
			ctx.lineTo(w*0.38, h*0.7);
			ctx.lineTo(w*0.75, h*0.5);
			ctx.lineTo(w*0.38, h*0.3);
			ctx.closePath();
			ctx.fill();
		} else if(overlay === "pause"){
			ctx.lineWidth = 2;
			ctx.beginPath();
			ctx.moveTo(w*0.38,h*0.3);
			ctx.lineTo(w*0.38,h*0.7);
			ctx.closePath();
			ctx.stroke();

			ctx.beginPath();
			ctx.moveTo(w*0.62,h*0.3);
			ctx.lineTo(w*0.62,h*0.7);
			ctx.closePath();
			ctx.stroke();
		}
	}

	// spelling doughnut just feels wrong
	function generateDoughnut(v){
		var graphValue = v || value;
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;
		var deg = graphValue * 3.6 - 90;

		canvas.width = canvas.width;

		generateBackground(context, canvas.width, canvas.height);

		if(graphValue < 1){
			generateOverlay(context, canvas.width, canvas.height);
			return;
		}
		context.lineWidth = borderWidth;
		context.strokeStyle = shadowColor;
		context.beginPath();
		context.arc(centerX, centerY, doughnutRadius, 0, toRad(360), false);
		context.arc(centerX, centerY, doughnutRadius - borderWidth, 0, toRad(360), true);
		context.closePath();
		context.stroke();

		context.strokeStyle = fillColor2 ? getMidColor(fillColor, fillColor2) : fillColor;
		context.beginPath();
		context.arc(centerX, centerY, doughnutRadius, toRad(-90), toRad(deg), false);
		context.arc(centerX, centerY, doughnutRadius - borderWidth, toRad(deg), toRad(-90), true);
		context.closePath();
		context.stroke();
		generateOverlay(context, canvas.width, canvas.height);
	}

	// Generates the wanted shape
	function generateBitmap(v){
		if(shape === "doughnut"){
			generateDoughnut(v);
		}
	}

	// draw me a check mark
	function generateSuccess(bgColor, fgColor){
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;

		canvas.width = canvas.width;
		context.beginPath();
		context.arc(centerX, centerY, 8, 0, 2 * Math.PI, false);
		context.fillStyle = bgColor || "#53C516";
		context.fill();

		context.beginPath();
		context.lineWidth = 2;
		context.strokeStyle = fgColor || "#FFFFFF";
		context.moveTo(4, 9);
		context.lineTo(8, 12);
		context.lineTo(12, 4);
		context.stroke();

	}

	// how about the red cross of death?
	function generateFailure(bgColor, fgColor){
		var centerX = canvas.width / 2;
		var centerY = canvas.height / 2;

		context.beginPath();
		context.arc(centerX, centerY, 8, 0, 2 * Math.PI, false);
		context.fillStyle = bgColor || "#F6491F";
		context.fill();

		context.beginPath();
		context.lineWidth = 2;
		context.strokeStyle = fgColor || "#FFFFFF";
		context.moveTo(5, 4);
		context.lineTo(11, 12);
		context.moveTo(11, 4);
		context.lineTo(5, 12);
		context.stroke();

	}

	// refresh the tab favicon
	function refreshFavIcon(){
		head.removeChild(icon);
		icon.setAttribute("href", canvas.toDataURL("image/x-icon"));
		head.appendChild(icon);
		if(updateTitle){
			document.title = titleRenderer.call(this, animValue || value, oldTitle);
		}
	}

	// either we already have a favicon and we want to keep it for resets...
	// or we create one that we call bob and that we care for
	function getIconRef(){
		head = document.getElementsByTagName("head")[0];
		var els = document.getElementsByTagName("link");
		if(els.length > 0){
			for(var i=0; i<els.length; i++){
				if(els[i].getAttribute("rel").split(" ").indexOf("icon") > -1){
					originalIcon = els[i].cloneNode(true); // keep the original for reset()
					return els[i];
				}
			}
		}
		// no favicon found. create one.
		var newIcon = document.createElement("link");
		newIcon.setAttribute("rel", "shortcut icon");
		newIcon.setAttribute("type", "image/png");
		head.appendChild(newIcon);
		return newIcon;
	}

	// starting point to the app... couldn"t hide it in the code better
	function init(){
		if(canvas && canvas.getContext){
			icon = getIconRef();
			oldTitle = document.title;
			canvas.height = canvas.width = 16;
			context = canvas.getContext("2d");
		} else {
			throw "No support for Canvas, no chocolate for you! =(";
		}
	}

	// this, as the method name suggests, is called once the anim has stopped.
	function stopAnim(){
		if(animCallback){
			animCallback.call(this, value);
			animCallback = null;
		}
	}

	// animation: called again and again until we get to the right value
	function incValue(inc){
		animValue += inc;
		if(isReset !== true){
			generateBitmap(animValue);
			refreshFavIcon();
			if(animValue !== null && animated){
				if(animValue === value){
					stopAnim();
				} else {
					setTimeout(function(){
						incValue(animValue > value ? -1 : 1);
					}, animInterval);
				}
			}
		}
	}

	// let"s get things started.
	setDefaults();
	init();

	// we get to the public methods now.
	return {
		// a helper to configure mucho settings at once
		config(cfg){
			shape = cfg.shape || shape;
			doughnutRadius = cfg.doughnutRadius || doughnutRadius;
			overlay = cfg.overlay || overlay;
			overlayColor = cfg.overlayColor || overlayColor;
			backgroundColor = cfg.backgroundColor || backgroundColor;
			isReset = false;
			animated = cfg.animated || animated;
			animationSpeed = cfg.animationSpeed || animationSpeed;
			borderColor = cfg.borderColor || borderColor;
			borderColor2 = cfg.borderColor2 || borderColor2;
			borderWidth = cfg.borderWidth || borderWidth;
			shadowColor = cfg.shadowColor || shadowColor;
			fillColor = cfg.fillColor || fillColor;
			fillColor2 = cfg.fillColor2 || fillColor2;
			updateTitle = cfg.updateTitle || updateTitle;
			titleRenderer = cfg.titleRenderer || titleRenderer;
			animCallback = (typeof cfg.callback !== "undefined") ? cfg.callback : animCallback;
			generateBitmap();
			refreshFavIcon();
			return FavIconX;
		},

		// setValue(value, [animated], [speed], [callback])
		// value must be between 0 and 100
		// when specified the animated overrides the component setting.
		// when specified the speed orrides the component setting
		// callback called once the animation is finished
		setValue(v, isAnimated, animSpeed, callback){
			if(v<0 || v>100) {
				throw "value must be between 0 and 100";
			}
			animCallback = (typeof callback !== "undefined") ? callback : animCallback;
			animValue = value;
			value = v;
			isReset = false;
			if(typeof isAnimated !== "undefined" ? isAnimated : animated){
				var steps = animValue - value;
				if(animValue !== value){
					animInterval = Math.abs(Math.ceil((typeof animSpeed !== "undefined" ? animSpeed : animationSpeed) / steps));
					incValue(animValue > value ? -1 : 1);
				}
			} else {
				animValue = null;
				generateBitmap();
				refreshFavIcon();
				if(animCallback){
					animCallback.call(this, v);
				}
			}
			return FavIconX;
		},

		// returns the current value of the widget
		getValue(){
			return animValue || value;
		},

		// restoring the past... or is it...
		reset(){
			setDefaults();
			if(originalIcon){
				head.removeChild(icon);
				icon = originalIcon.cloneNode(true);
				head.appendChild(icon);
			}
			if(updateTitle){
				document.title = oldTitle;
			}
			return FavIconX;
		},

		// displays the awesome checkbox. colors can be tweaked here
		complete(fgColor, bgColor){
			isReset = false;
			generateSuccess(fgColor, bgColor);
			refreshFavIcon();
			document.title = oldTitle;
		},

		// displays the even more awesome cross. colors can be tweaked here
		fail(fgColor, bgColor){
			isReset = false;
			generateFailure(fgColor, bgColor);
			refreshFavIcon();
			document.title = oldTitle;
		}
	};
}());
<|endoftext|>