<commit_before>const debug = require('debug')('ConsulPilot');
const Consulite = require('consulite');

const _ = {};

/**
 * ConsulPilot
 *
 * Returns singleton of module
 * discovers consul using envars CONSUL_HOST CONSUL_PORT or defaults to consul:8500
 *
 * watch services for change, executing function passed, CP will pass (err, { address, port }) to callback;
 * watch(serviceName, callbackFunc);
 */

class ConsulPilot {

    constructor () {
        this._services = {}; // serviceName: { callback, address, port }
    }

    watch (serviceName, callback) {
        debug('ADDING WATCHER', serviceName);

        const self = this;

        if (!self._services[serviceName]) {
            debug('SERVICE:', serviceName, 'NOT DEFINED, CREATING');
            self._services[serviceName] = {};
        }

        self._services[serviceName].callback = callback;

        return _.refreshService(serviceName)
            .then(consulService => {
                self._services[serviceName] = consulService;
            });
    }
}

module.exports = new ConsulPilot();

_.refreshAllServices = () => {
    debug('REFRESHING ALL SERVICES');

    const self = module.exports;
    const services = self._services;

    return Promise.all(
        Object.keys(services)
            .map(serviceName => _.refreshService(serviceName))
    );
}

_.refreshService = (serviceName) => {
    debug('REFRESHING SERVICE:', serviceName, module.exports._services[serviceName]);

    const service = module.exports._services[serviceName];

    return new Promise((resolve, reject) => {
        Consulite.refreshService(serviceName)
            .then(results => {
                const consulService = results[0];
                debug('RECEIVED NEW INFORMATION', serviceName, consulService);

                if (consulService && consulService.address && consulService.address !== service.address) {
                    debug('SERVICE:', serviceName, 'HAS NEW ADDRESS');
                    service.address = consulService.address;
                    service.port = consulService.port;

                    _.update(null, serviceName);
                }

                return resolve(service);
            })
            .catch(err => {
                debug('SERVICE NOT FOUND', serviceName, err);
                service.address = null;
                service.port = null;

                _.update(null, serviceName);

                return reject({ error: 'SERVICE_NOT_FOUND', serviceName });
            });
    });
}

_.update = (err, serviceName) => {
    debug('CALLING:', serviceName, 'CALLBACK');

    const service = module.exports._services[serviceName];

    return service.callback(err, { address: service.address, port: service.port });
}

_.signal = () => {
    debug('SIGHUP RECEIVED');
    return _.refreshAllServices().catch((err) => {
        console.log('error consul-pilot:', err);
    });
}

// process intercetor
process.on('SIGHUP', _.signal);

// expose everything for the tests
if (process.env.NODE_ENV === 'test') {
    module.exports._ = _;
}
<commit_msg>Fix code falling test Card DS-42<commit_after>const debug = require('debug')('ConsulPilot');
const Consulite = require('consulite');

const _ = {};

/**
 * ConsulPilot
 *
 * Returns singleton of module
 * discovers consul using envars CONSUL_HOST CONSUL_PORT or defaults to consul:8500
 *
 * watch services for change, executing function passed, CP will pass (err, { address, port }) to callback;
 * watch(serviceName, callbackFunc);
 */

class ConsulPilot {

    constructor () {
        this._services = {}; // serviceName: { callback, address, port }
    }

    watch (serviceName, callback) {
        debug('ADDING WATCHER', serviceName);

        const self = this;

        if (!self._services[serviceName]) {
            debug('SERVICE:', serviceName, 'NOT DEFINED, CREATING');
            self._services[serviceName] = {};
        }

        self._services[serviceName].callback = callback;

        return _.refreshService(serviceName)
            .then(consulService => {
                self._services[serviceName] = consulService;
            });
    }
}

module.exports = new ConsulPilot();

_.refreshAllServices = () => {
    debug('REFRESHING ALL SERVICES');

    const self = module.exports;
    const services = self._services;

    return Promise.all(
        Object.keys(services)
            .map(serviceName => _.refreshService(serviceName))
    );
}

_.refreshService = (serviceName) => {
    debug('REFRESHING SERVICE:', serviceName, module.exports._services[serviceName]);

    const service = module.exports._services[serviceName];

    return new Promise((resolve, reject) => {
        Consulite.refreshService(serviceName)
            .then(results => {
                const consulService = results[0];
                debug('RECEIVED NEW INFORMATION', serviceName, consulService);

                if (consulService && consulService.address && consulService.address !== service.address) {
                    debug('SERVICE:', serviceName, 'HAS NEW ADDRESS');
                    service.address = consulService.address;
                    service.port = consulService.port;

                    _.update(null, serviceName);
                }

                return resolve(service);
            })
            .catch(err => {
                debug('SERVICE NOT FOUND', serviceName, err);
                service.address = null;
                service.port = null;

                _.update(null, serviceName);

                return reject(Object.assign(service, { error: 'SERVICE_NOT_FOUND', serviceName }));
            });
    });
}

_.update = (err, serviceName) => {
    debug('CALLING:', serviceName, 'CALLBACK');

    const service = module.exports._services[serviceName];

    return service.callback(err, { address: service.address, port: service.port });
}

_.signal = () => {
    debug('SIGHUP RECEIVED');
    return _.refreshAllServices().catch((err) => {
        console.log('error consul-pilot:', err);
    });
}

// process intercetor
process.on('SIGHUP', _.signal);

// expose everything for the tests
if (process.env.NODE_ENV === 'test') {
    module.exports._ = _;
}
<|endoftext|>


<commit_before>var component = {}

if (process.browser) {
    component = require('vue2-dropzone/dist/vue2Dropzone.js')
}
component.name = 'dropzone'
component.render = function (createElement) {
    var that = this._self
    return createElement('div', {
        props: that.props,
        attrs: {
            class: 'vue-dropzone dropzone',
            id: that.id || ''
        },
        ref: 'dropzoneElement'
    }, [this.useCustomSlot ? createElement("div", {staticClass: "dz-message"}, [this.$slots.default]) : this.$slots.default])
}

module.exports = component
<commit_msg>Update index.js<commit_after>let component = {};
component.props = ["useCustomSlot"];
if (process.browser) {
  component = require('vue2-dropzone/dist/vue2Dropzone.js')
}
component.render = function (createElement) {
  const that = this._self;
  return createElement('div', {
    props: that.props,
    attrs: {
      class: 'vue-dropzone dropzone',
      id: that.id || ''
    },
    ref: 'dropzoneElement'
  }, [this.useCustomSlot === "" || this.useCustomSlot === true ? createElement("div", {staticClass: "dz-message"}, [this._t("default", [this._v("Drop files here to upload")])], 2) : this._e()])
};
component.name = 'dropzone';

export default component;
<|endoftext|>


<commit_before>var _ = require('lodash'),
    moment = require('moment'),
    isLevelActive = require('./level');

var LoggerConsolePlugin = function(configuration) {
  var defaults = {
    level: 'debug',
    timeFormat: 'YYYY-MM-DD HH:mm:ss',
    messageFormat: '%time | %logger::%level | PID: %pid - %msg'
  };

  var config = _.defaults(configuration || {}, defaults);
  //moment.utc().format('YYYY-MM-DD HH:mm:ss')

  var getMessage = function(logger, level, msg){
    var now = moment.utc().format(this.config.timeFormat);

    var outputMsg = msg instanceof Error ? msg.stack : msg;

		var formatedMessage = this.config.messageFormat
			.replace('%logger', logger.toUpperCase())
			.replace('%time', now)
			.replace('%level', level.toUpperCase())
			.replace('%pid', process.pid)
			.replace('%msg', outputMsg);

    return formatedMessage;
  }.bind(this);

  var log = function(level, args){

    if (isLevelActive(level, this.level)) {
      args = _.toArray(args);

      var logger = args.shift();
      var msg = args.shift();

      var output = getMessage(logger, level, msg);

      args.unshift(output);

      console.log.apply(console, args);
    }

  }.bind(this);

  this.config = config;

  this.level = config.level;

  this.name = 'LoggerConsolePlugin';

  this.isDebug = function(){
    return isLevelActive('debug', this.level);
  }.bind(this);

  this.debug = function(){
    log('debug', arguments);
  }.bind(this);

  this.trace = function(){
    log('trace', arguments);
  }.bind(this);

  this.info = function(){
    log('info', arguments);
  }.bind(this);

  this.warn = function(){
    log('warn', arguments);
  }.bind(this);

  this.error = function(){
    log('error', arguments);
  }.bind(this);
};

module.exports = LoggerConsolePlugin;
<commit_msg>removed unecessary comment<commit_after>var _ = require('lodash'),
    moment = require('moment'),
    isLevelActive = require('./level');

var LoggerConsolePlugin = function(configuration) {
  var defaults = {
    level: 'debug',
    timeFormat: 'YYYY-MM-DD HH:mm:ss',
    messageFormat: '%time | %logger::%level | PID: %pid - %msg'
  };

  var config = _.defaults(configuration || {}, defaults);

  var getMessage = function(logger, level, msg){
    var now = moment.utc().format(this.config.timeFormat);

    var outputMsg = msg instanceof Error ? msg.stack : msg;

		var formatedMessage = this.config.messageFormat
			.replace('%logger', logger.toUpperCase())
			.replace('%time', now)
			.replace('%level', level.toUpperCase())
			.replace('%pid', process.pid)
			.replace('%msg', outputMsg);

    return formatedMessage;
  }.bind(this);

  var log = function(level, args){

    if (isLevelActive(level, this.level)) {
      args = _.toArray(args);

      var logger = args.shift();
      var msg = args.shift();

      var output = getMessage(logger, level, msg);

      args.unshift(output);

      console.log.apply(console, args);
    }

  }.bind(this);

  this.config = config;

  this.level = config.level;

  this.name = 'LoggerConsolePlugin';

  this.isDebug = function(){
    return isLevelActive('debug', this.level);
  }.bind(this);

  this.debug = function(){
    log('debug', arguments);
  }.bind(this);

  this.trace = function(){
    log('trace', arguments);
  }.bind(this);

  this.info = function(){
    log('info', arguments);
  }.bind(this);

  this.warn = function(){
    log('warn', arguments);
  }.bind(this);

  this.error = function(){
    log('error', arguments);
  }.bind(this);
};

module.exports = LoggerConsolePlugin;
<|endoftext|>


<commit_before>var extend = require('xtend')

module.exports = function sendAction (options) {
  if (!options) throw new Error('options required')
  if (!options.onaction) throw new Error('options.onaction required')
  if (!options.onchange) throw new Error('options.onchange required')
  var state = options.state || {}

  function send (action, params) {
    if (typeof action === 'object') params = action
    else if (typeof action === 'string') params = extend({ type: action }, params)

    var newState = options.onaction(params, state)
    update(params, newState)
  }

  function update (params, newState) {
    var oldState = state
    state = extend(state, newState)
    options.onchange(params, newState, oldState)
  }

  send.event = function sendAction_event (action, params, flag) {
    if (typeof flag === undefined) flag = true
    return function sendAction_send_thunk (e) {
      if (flag && e && e.preventDefault) e.preventDefault()
      send(action, params, flag)
    }
  }

  send.state = function sendAction_state () {
    return state
  }

  return send
}
<commit_msg>onaction: allow recursion<commit_after>var extend = require('xtend')

module.exports = function sendAction (options) {
  if (!options) throw new Error('options required')
  if (!options.onaction) throw new Error('options.onaction required')
  if (!options.onchange) throw new Error('options.onchange required')
  var state = options.state || {}

  function send (action, params) {
    if (typeof action === 'object') params = action
    else if (typeof action === 'string') params = extend({ type: action }, params)

    var newState = options.onaction(params, state, send)
    update(params, newState)
  }

  function update (params, newState) {
    var oldState = state
    state = extend(state, newState)
    options.onchange(params, newState, oldState)
  }

  send.event = function sendAction_event (action, params, flag) {
    if (typeof flag === undefined) flag = true
    return function sendAction_send_thunk (e) {
      if (flag && e && e.preventDefault) e.preventDefault()
      send(action, params, flag)
    }
  }

  send.state = function sendAction_state () {
    return state
  }

  return send
}
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const http = require('http');
const server = http.Server(app);
const session = require("express-session");
const Util = require('./util');
const bodyParser = require("body-parser");
const expressValidator = require('express-validator')
const fileUpload = require('express-fileupload');
const Sentry = require("@sentry/node");
const Tracing = require("@sentry/tracing");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const Cookies = require("cookies");
const extend = require('util')._extend
const restClient = new (require("node-rest-client")).Client()
const unirest = require("unirest");
const crypto = require('crypto');
const fs = require('fs')
const morgan = require('morgan')
const rfs = require("rotating-file-stream");
const rateLimit = require("express-rate-limit");
const Optimus = require("optimus-js");
const puller = require("express-git-puller");
const path = require('path')
const colors = require("colors");
const metrics = require("./metrics");
const config = require("./config");
const port = process.env.PORT || config.port || 3014;

const TESTER_METRICS = metrics.metric('mineskin', 'tester');

console.log("\n" +
    "  ==== STARTING UP ==== " +
    "\n");

Sentry.init({
    dsn: config.sentry.dsn,
    integrations: [
        new Sentry.Integrations.Http({tracing: true}),
        new Tracing.Integrations.Express({app})
    ],
    tracesSampleRate: 0.05,
    serverName: config.server
});

require("rootpath")();
require('console-stamp')(console, 'HH:MM:ss.l');

// require("./statusMonitor")(app, config);

try {
    fs.mkdirSync("/tmp/url");
} catch (e) {
}
try {
    fs.mkdirSync("/tmp/upl");
} catch (e) {
}
try {
    fs.mkdirSync("/tmp/moj");
} catch (e) {
}

app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    if (req.method === 'OPTIONS') {
        res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        res.header("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type, Origin");
        res.header("Access-Control-Request-Headers", "X-Requested-With, Accept, Content-Type, Origin");
        return res.sendStatus(200);
    } else {
        return next();
    }
});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));
app.use(expressValidator());
app.use(fileUpload());
app.use(function (req, res, next) {
    req.realAddress = req.header("x-real-ip") || req.realAddress;
    res.header("X-Mineskin-Server", config.server || "default");
    next();
});

app.use("/.well-known", express.static(".well-known"));

// const swStats = require('swagger-stats');
// app.use(swStats.getMiddleware(config.swagger));

// create a rotating write stream
const accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: path.join(__dirname, 'log'),
    compress: "gzip"
})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
morgan.token('remote-addr', function (req) {
    return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
});

let updatingApp = false;
config.puller.beforeRun = function (req, res) {
    updatingApp = true;
};
config.puller.afterRun = function (req, res) {
    updatingApp = false;
};
app.use(function (req, res, next) {
    if (updatingApp) {
        res.status(503).send({err: "app is updating"});
        return;
    }
    next();
});
// Git Puller
app.use(config.puller.endpoint, new puller(config.puller));

colors.setTheme({
    silly: 'rainbow',
    input: 'grey',
    prompt: 'grey',
    info: 'green',
    data: 'grey',
    help: 'cyan',
    warn: 'yellow',
    debug: 'cyan',
    error: 'red'
});

// Databse
require("./db/db")(mongoose, config);
const Skin = require("./db/schemas/skin").Skin;

// API methods
app.get("/", function (req, res) {
    res.json({msg: "Hi!"});
});

app.post("/testing/upload_tester_result", function (req, res) {
    if (!config.testing.testerToken || req.body.token !== config.testing.testerToken) return;
    if (!req.body.data) return;
    if (req.headers["user-agent"] !== "mineskin-tester") return;

    try {
        TESTER_METRICS
            .tag("server", config.server)
            .tag("result", req.body.data.r || "fail")
            .tag("mismatches", req.body.data.m > 0 ? "true" : "false")
            .inc();
    } catch (e) {
        console.warn(e);
        Sentry.captureException(e);
    }

    if (req.body.data.r === "success") {
        Util.increaseStat("mineskintester.success");
        res.sendStatus(202);

        if (req.body.data.m > 0) {
            Util.postDiscordMessage("🛑 mineskin-tester generated data with " + req.body.data.m + " image mismatches! ID: " + req.body.data.i);
        }

        if (req.body.data.i) {
            Skin.findOneAndUpdate({id: req.body.data.i, server: req.body.data.s}, {testerRequest: true, testerMismatchCounter: req.body.data.m || 0});
        }
    } else if (req.body.data.r === "fail") {
        Util.increaseStat("mineskintester.fail");
        res.sendStatus(202);
    } else {
        res.sendStatus(400);
    }
});

const optimus = new Optimus(config.optimus.prime, config.optimus.inverse, config.optimus.random);
console.log("Optimus Test:", optimus.encode(Math.floor(Date.now() / 10)));

const limiter = rateLimit({
    windowMs: 2 * 60 * 1000, // 2 minutes,
    max: 6,
    message: JSON.stringify({error: "Too many requests"}),
    keyGenerator: function (req) {
        return req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.realAddress || req.connection.remoteAddress
    }
})

/// Routes
require("./routes/generate")(app, config, optimus, limiter);
require("./routes/get")(app);
require("./routes/render")(app);
require("./routes/util")(app);
require("./routes/admin")(app);
require("./routes/accountManager")(app, config);

function exitHandler(err) {
    if (err) {
        console.log("\n\n\n\n\n\n\n\n");
        console.log(err);
        console.log("\n\n\n");
    }
    process.exit();
}

app.use(Sentry.Handlers.errorHandler());

server.listen(port, function () {
    console.log(' ==> listening on *:' + port + "\n");
});

process.on("exit", exitHandler);
process.on("SIGINT", exitHandler);
process.on("uncaughtException", exitHandler);
<commit_msg>reduce<commit_after>const express = require('express');
const app = express();
const http = require('http');
const server = http.Server(app);
const session = require("express-session");
const Util = require('./util');
const bodyParser = require("body-parser");
const expressValidator = require('express-validator')
const fileUpload = require('express-fileupload');
const Sentry = require("@sentry/node");
const Tracing = require("@sentry/tracing");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const Cookies = require("cookies");
const extend = require('util')._extend
const restClient = new (require("node-rest-client")).Client()
const unirest = require("unirest");
const crypto = require('crypto');
const fs = require('fs')
const morgan = require('morgan')
const rfs = require("rotating-file-stream");
const rateLimit = require("express-rate-limit");
const Optimus = require("optimus-js");
const puller = require("express-git-puller");
const path = require('path')
const colors = require("colors");
const metrics = require("./metrics");
const config = require("./config");
const port = process.env.PORT || config.port || 3014;

const TESTER_METRICS = metrics.metric('mineskin', 'tester');

console.log("\n" +
    "  ==== STARTING UP ==== " +
    "\n");

Sentry.init({
    dsn: config.sentry.dsn,
    integrations: [
        new Sentry.Integrations.Http({tracing: true}),
        new Tracing.Integrations.Express({app})
    ],
    tracesSampleRate: 0.001,
    serverName: config.server
});

require("rootpath")();
require('console-stamp')(console, 'HH:MM:ss.l');

// require("./statusMonitor")(app, config);

try {
    fs.mkdirSync("/tmp/url");
} catch (e) {
}
try {
    fs.mkdirSync("/tmp/upl");
} catch (e) {
}
try {
    fs.mkdirSync("/tmp/moj");
} catch (e) {
}

app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    if (req.method === 'OPTIONS') {
        res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        res.header("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type, Origin");
        res.header("Access-Control-Request-Headers", "X-Requested-With, Accept, Content-Type, Origin");
        return res.sendStatus(200);
    } else {
        return next();
    }
});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));
app.use(expressValidator());
app.use(fileUpload());
app.use(function (req, res, next) {
    req.realAddress = req.header("x-real-ip") || req.realAddress;
    res.header("X-Mineskin-Server", config.server || "default");
    next();
});

app.use("/.well-known", express.static(".well-known"));

// const swStats = require('swagger-stats');
// app.use(swStats.getMiddleware(config.swagger));

// create a rotating write stream
const accessLogStream = rfs('access.log', {
    interval: '1d', // rotate daily
    path: path.join(__dirname, 'log'),
    compress: "gzip"
})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
morgan.token('remote-addr', function (req) {
    return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
});

let updatingApp = false;
config.puller.beforeRun = function (req, res) {
    updatingApp = true;
};
config.puller.afterRun = function (req, res) {
    updatingApp = false;
};
app.use(function (req, res, next) {
    if (updatingApp) {
        res.status(503).send({err: "app is updating"});
        return;
    }
    next();
});
// Git Puller
app.use(config.puller.endpoint, new puller(config.puller));

colors.setTheme({
    silly: 'rainbow',
    input: 'grey',
    prompt: 'grey',
    info: 'green',
    data: 'grey',
    help: 'cyan',
    warn: 'yellow',
    debug: 'cyan',
    error: 'red'
});

// Databse
require("./db/db")(mongoose, config);
const Skin = require("./db/schemas/skin").Skin;

// API methods
app.get("/", function (req, res) {
    res.json({msg: "Hi!"});
});

app.post("/testing/upload_tester_result", function (req, res) {
    if (!config.testing.testerToken || req.body.token !== config.testing.testerToken) return;
    if (!req.body.data) return;
    if (req.headers["user-agent"] !== "mineskin-tester") return;

    try {
        TESTER_METRICS
            .tag("server", config.server)
            .tag("result", req.body.data.r || "fail")
            .tag("mismatches", req.body.data.m > 0 ? "true" : "false")
            .inc();
    } catch (e) {
        console.warn(e);
        Sentry.captureException(e);
    }

    if (req.body.data.r === "success") {
        Util.increaseStat("mineskintester.success");
        res.sendStatus(202);

        if (req.body.data.m > 0) {
            Util.postDiscordMessage("🛑 mineskin-tester generated data with " + req.body.data.m + " image mismatches! ID: " + req.body.data.i);
        }

        if (req.body.data.i) {
            Skin.findOneAndUpdate({id: req.body.data.i, server: req.body.data.s}, {testerRequest: true, testerMismatchCounter: req.body.data.m || 0});
        }
    } else if (req.body.data.r === "fail") {
        Util.increaseStat("mineskintester.fail");
        res.sendStatus(202);
    } else {
        res.sendStatus(400);
    }
});

const optimus = new Optimus(config.optimus.prime, config.optimus.inverse, config.optimus.random);
console.log("Optimus Test:", optimus.encode(Math.floor(Date.now() / 10)));

const limiter = rateLimit({
    windowMs: 2 * 60 * 1000, // 2 minutes,
    max: 6,
    message: JSON.stringify({error: "Too many requests"}),
    keyGenerator: function (req) {
        return req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.realAddress || req.connection.remoteAddress
    }
})

/// Routes
require("./routes/generate")(app, config, optimus, limiter);
require("./routes/get")(app);
require("./routes/render")(app);
require("./routes/util")(app);
require("./routes/admin")(app);
require("./routes/accountManager")(app, config);

function exitHandler(err) {
    if (err) {
        console.log("\n\n\n\n\n\n\n\n");
        console.log(err);
        console.log("\n\n\n");
    }
    process.exit();
}

app.use(Sentry.Handlers.errorHandler());

server.listen(port, function () {
    console.log(' ==> listening on *:' + port + "\n");
});

process.on("exit", exitHandler);
process.on("SIGINT", exitHandler);
process.on("uncaughtException", exitHandler);
<|endoftext|>


<commit_before>#! /usr/bin/env node

var https       = require('https')
var http        = require('http')
var fs          = require('fs')
var join        = require('path').join

var btcprogress = require('btcprogress')
var route       = require('tiny-route')
var ecstatic    = require('ecstatic')
var stack       = require('stack')

var redirect    = require('./lib/https-redirect')
var config      = require('./config')
var api         = require('./api')
var views       = require('./views')

var autoApi     = require('./lib/auto-api')

var app = stack(
  route('/badge', btcprogress()),
  autoApi(api, views),
  ecstatic(join(__dirname, 'static'))
)

var secure = process.getuid() === 0

if(secure) {

  https.createServer({
   cert: fs.readFileSync(config.cert),
   key : fs.readFileSync(config.key)
  }, app).listen(443)

  http.createServer(redirect()).listen(80)

  process.on('uncaughtException', function (err) {
    console.log('*****************************')
    console.error('Error at:', new Date)
    console.error(err.stack)
    console.log('*****************************')
  })

} else {
  http.createServer(app).listen(config.port)
}
<commit_msg>use new badge<commit_after>#! /usr/bin/env node

var https       = require('https')
var http        = require('http')
var fs          = require('fs')
var join        = require('path').join

var btcprogress = require('btcprogress')
var route       = require('tiny-route')
var ecstatic    = require('ecstatic')
var stack       = require('stack')

var redirect    = require('./lib/https-redirect')
var config      = require('./config')
var api         = require('./api')
var views       = require('./views')

var badge       = require('./lib/badge').getBadge
var autoApi     = require('./lib/auto-api')

var app = stack(
  //TODO: remove
  route('/badge', btcprogress()),
  //the new badge with api
  autoApi(api, views, {png: {iteration: badge}}),
  ecstatic(join(__dirname, 'static'))
)

var secure = process.getuid() === 0

if(secure) {

  https.createServer({
   cert: fs.readFileSync(config.cert),
   key : fs.readFileSync(config.key)
  }, app).listen(443)

  http.createServer(redirect()).listen(80)

  process.on('uncaughtException', function (err) {
    console.log('*****************************')
    console.error('Error at:', new Date)
    console.error(err.stack)
    console.log('*****************************')
  })

} else {
  http.createServer(app).listen(config.port)
}
<|endoftext|>


<commit_before>if (!document) {
    throw Error("electron-tabs module must be called in renderer process");
}

// Inject styles
(function () {
    const styles = `
        webview {
            display: flex;
            flex: 0 1;
            width: 0px;
            height: 0px;
        }
        webview.visible {
            width: 100%;
            height: 100%;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
    `;
    let styleTag = document.createElement("style");
    styleTag.innerHTML = styles;
    document.getElementsByTagName("head")[0].appendChild(styleTag);
})();

class TabGroup {
    constructor (args) {
        let options = this.options = {
            tabContainerSelector: args.tabContainerSelector || ".tabs-tabcontainer",
            viewContainerSelector: args.viewContainerSelector || ".tabs-viewcontainer",
            tabClass: args.tabClass || "tabs-tab",
            viewClass: args.viewClass || "tabs-view"
        };
        this.tabContainer = document.querySelector(options.tabContainerSelector);
        this.viewContainer = document.querySelector(options.viewContainerSelector);
        this.tabs = [];
        this.newTabId = 0;
    }

    addTab (args) {
        let id = this.newTabId;
        this.newTabId++;
        let tab = new Tab(this, id, args);
        this.pushTab(tab);
        return tab;
    }

    pushTab (tab) {
        this.tabs.push(tab);
    }

    removeTab (tab) {
        let id = tab.id;
        for (let i in this.tabs) {
            if (this.tabs[i].id === id) {
                this.tabs.splice(i, 1);
                break;
            }
        }
    }

    setActiveTab (tab) {
        this.removeTab(tab);
        this.pushTab(tab);
    }

    getActiveTab () {
        if (this.tabs.length < 1) return null;
        return this.tabs[this.tabs.length - 1];
    }

    activateRecentTab (tab) {
        let recentTab = this.tabs[this.tabs.length - 1];
        if (!recentTab) return;
        recentTab.activate();
    }
}

class Tab {
    constructor (tabGroup, id, args) {
        this.tabGroup = tabGroup;
        this.id = id;
        this.title = args.title;
        this.iconURL = args.iconURL;
        this.webviewAttributes = args.webviewAttributes || {};
        this.webviewAttributes.src = args.src;
        this.tabElements = {};
        this.initTab();
        this.initWebview();
    }

    initTab () {
        let tabClass = this.tabGroup.options.tabClass;

        // Create tab element
        let tab = this.tab = document.createElement("div");
        tab.classList.add(tabClass);
        for (let el of ["icon", "title", "buttons"]) {
            let span = tab.appendChild(document.createElement("span"));
            span.classList.add(`${tabClass}-${el}`);
            this.tabElements[el] = span;
        }

        this.setTitle(this.title);
        this.setIcon(this.iconURL);

        tab.addEventListener("click", this.activate.bind(this), false);
        this.tabGroup.tabContainer.appendChild(this.tab);
        // TODO: close button
        // TODO: handle middle click
    }

    initWebview () {
        this.webview = document.createElement("webview");
        this.webview.classList.add(this.tabGroup.options.viewClass);
        if (this.webviewAttributes) {
            let attrs = this.webviewAttributes;
            for (let key in attrs) {
                this.webview.setAttribute(key, attrs[key]);
            }
        }
        this.tabGroup.viewContainer.appendChild(this.webview);
    }

    setTitle (title) {
        let span = this.tabElements.title;
        span.innerHTML = title;
        this.title = title;
    }

    getTitle () {
        return this.title;
    }

    setIcon (iconURL) {
        this.iconURL = iconURL;
        let span = this.tabElements.icon;
        if (iconURL) {
            span.innerHTML = `<img src="${iconURL}" />`;
        }
    }

    getIcon () {
        return this.iconURL;
    }

    activate () {
        let activeTab = this.tabGroup.getActiveTab();
        if (activeTab) {
            activeTab.tab.classList.remove("active");
            activeTab.webview.classList.remove("visible");
        }
        this.tabGroup.setActiveTab(this);
        this.tab.classList.add("active");
        this.webview.classList.add("visible");
    }

    flash (flag) {
        if (flag !== false) {
            this.tab.classList.add("flash");
        } else {
            this.tab.classList.remove("flash");
        }
    }

    move (index) {
        // TODO: move
    }

    close () {
        let tabGroup = this.tabGroup;
        tabGroup.tabContainer.removeChild(this.tab);
        tabGroup.viewContainer.removeChild(this.webview);
        tabGroup.removeTab(this);
        tabGroup.activateRecentTab();
    }
}

module.exports = TabGroup;
<commit_msg>Add close button to tabs<commit_after>if (!document) {
    throw Error("electron-tabs module must be called in renderer process");
}

// Inject styles
(function () {
    const styles = `
        webview {
            display: flex;
            flex: 0 1;
            width: 0px;
            height: 0px;
        }
        webview.visible {
            width: 100%;
            height: 100%;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
    `;
    let styleTag = document.createElement("style");
    styleTag.innerHTML = styles;
    document.getElementsByTagName("head")[0].appendChild(styleTag);
})();

class TabGroup {
    constructor (args) {
        let options = this.options = {
            tabContainerSelector: args.tabContainerSelector || ".tabs-tabcontainer",
            viewContainerSelector: args.viewContainerSelector || ".tabs-viewcontainer",
            tabClass: args.tabClass || "tabs-tab",
            viewClass: args.viewClass || "tabs-view"
        };
        this.tabContainer = document.querySelector(options.tabContainerSelector);
        this.viewContainer = document.querySelector(options.viewContainerSelector);
        this.tabs = [];
        this.newTabId = 0;
    }

    addTab (args) {
        let id = this.newTabId;
        this.newTabId++;
        let tab = new Tab(this, id, args);
        this.pushTab(tab);
        return tab;
    }

    pushTab (tab) {
        this.tabs.push(tab);
    }

    removeTab (tab) {
        let id = tab.id;
        for (let i in this.tabs) {
            if (this.tabs[i].id === id) {
                this.tabs.splice(i, 1);
                break;
            }
        }
    }

    setActiveTab (tab) {
        this.removeTab(tab);
        this.pushTab(tab);
    }

    getActiveTab () {
        if (this.tabs.length < 1) return null;
        return this.tabs[this.tabs.length - 1];
    }

    activateRecentTab (tab) {
        let recentTab = this.tabs[this.tabs.length - 1];
        if (!recentTab) return;
        recentTab.activate();
    }
}

class Tab {
    constructor (tabGroup, id, args) {
        this.tabGroup = tabGroup;
        this.id = id;
        this.title = args.title;
        this.iconURL = args.iconURL;
        this.closable = args.closable === false ? false : true;
        this.webviewAttributes = args.webviewAttributes || {};
        this.webviewAttributes.src = args.src;
        this.tabElements = {};
        this.initTab();
        this.initWebview();
    }

    initTab () {
        let tabClass = this.tabGroup.options.tabClass;

        // Create tab element
        let tab = this.tab = document.createElement("div");
        tab.classList.add(tabClass);
        for (let el of ["icon", "title", "buttons"]) {
            let span = tab.appendChild(document.createElement("span"));
            span.classList.add(`${tabClass}-${el}`);
            this.tabElements[el] = span;
        }

        this.setTitle(this.title);
        this.setIcon(this.iconURL);
        this.setButtons();

        tab.addEventListener("click", this.activate.bind(this), false);
        this.tabGroup.tabContainer.appendChild(this.tab);
        // TODO: handle middle click
    }

    initWebview () {
        this.webview = document.createElement("webview");
        this.webview.classList.add(this.tabGroup.options.viewClass);
        if (this.webviewAttributes) {
            let attrs = this.webviewAttributes;
            for (let key in attrs) {
                this.webview.setAttribute(key, attrs[key]);
            }
        }
        this.tabGroup.viewContainer.appendChild(this.webview);
    }

    setTitle (title) {
        let span = this.tabElements.title;
        span.innerHTML = title;
        this.title = title;
    }

    getTitle () {
        return this.title;
    }

    setIcon (iconURL) {
        this.iconURL = iconURL;
        let span = this.tabElements.icon;
        if (iconURL) {
            span.innerHTML = `<img src="${iconURL}" />`;
        }
    }

    getIcon () {
        return this.iconURL;
    }

    setButtons () {
        let container = this.tabElements.buttons;
        let tabClass = this.tabGroup.options.tabClass;
        if (this.closable) {
            let button = container.appendChild(document.createElement("button"));
            button.classList.add(`${tabClass}-button-close`);
            button.innerHTML = "❌";
            button.addEventListener("click", this.close.bind(this), false);
        }
    }

    activate () {
        let activeTab = this.tabGroup.getActiveTab();
        if (activeTab) {
            activeTab.tab.classList.remove("active");
            activeTab.webview.classList.remove("visible");
        }
        this.tabGroup.setActiveTab(this);
        this.tab.classList.add("active");
        this.webview.classList.add("visible");
    }

    flash (flag) {
        if (flag !== false) {
            this.tab.classList.add("flash");
        } else {
            this.tab.classList.remove("flash");
        }
    }

    move (index) {
        // TODO: move
    }

    close () {
        let tabGroup = this.tabGroup;
        tabGroup.tabContainer.removeChild(this.tab);
        tabGroup.viewContainer.removeChild(this.webview);
        tabGroup.removeTab(this);
        tabGroup.activateRecentTab();
    }
}

module.exports = TabGroup;
<|endoftext|>


<commit_before>// External Modules
var express = require('express'),
	flash = require('connect-flash');

var app = express();

// Local Modules
var auth = require('./auth'),
	db = require('./db');

////////////////////////////////////
// Middleware & Config
////////////////////////////////////
var port = process.env.PORT || 3003;
app.configure( function(){
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.use( express.static('bs') );
	app.use(express.bodyParser());
	app.use(express.cookieParser());
	app.use(express.cookieSession({ secret: 'shakabum',
							  cookie: { maxAge: 180000 } })); // session expiry in 3 minutes
	app.use( flash() );
});

var flasherror = 'error';

////////////////////////////////////
// Routes
////////////////////////////////////
// GET

// Https redirect
app.all('*', function(req,res,next){
	var stuff = req.host;
	stuff += " : " + req.originalUrl;
	if ( !req.secure ) stuff += "<br/> NOT SECURE";
	res.send( stuff );
});

// Carry on
app.get('/', function(req, res ){
	res.render('index', { title: "Authentication start" } );
} );

app.get('/login', function(req, res){

	res.render('login', { message: req.flash( flasherror ) } );
});

app.get('/studentarea', auth.check, function(req,res){
	res.render('studentarea', { title: "Students authenticated" } );
});

app.get('/teacherarea', auth.check, function(req,res){
	res.render('teacherarea', { title: "Teacher authenticated" } );
});

app.get('/admin', auth.check, function( req, res ){
	res.render('admin', {title: "Authentication start" });
} );

app.get('/logout', auth.logout, function(req,res){
	res.send("Logged out");
} );

// POST
app.post('/login', auth.login, function(req, res){
	res.send("Logged in");
} );

////////////////////////////////////
app.listen(port);<commit_msg>https done testing<commit_after>// External Modules
var express = require('express'),
	flash = require('connect-flash');

var app = express();

// Local Modules
var auth = require('./auth'),
	db = require('./db');

////////////////////////////////////
// Middleware & Config
////////////////////////////////////
var port = process.env.PORT || 3003;
app.configure( function(){
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.use( express.static('bs') );
	app.use(express.bodyParser());
	app.use(express.cookieParser());
	app.use(express.cookieSession({ secret: 'shakabum',
							  cookie: { maxAge: 180000 } })); // session expiry in 3 minutes
	app.use( flash() );
});

var flasherror = 'error';

////////////////////////////////////
// Routes
////////////////////////////////////
// GET

app.get('/', function(req, res ){
	res.render('index', { title: "Authentication start" } );
} );

app.get('/login', function(req, res){

	res.render('login', { message: req.flash( flasherror ) } );
});

app.get('/studentarea', auth.check, function(req,res){
	res.render('studentarea', { title: "Students authenticated" } );
});

app.get('/teacherarea', auth.check, function(req,res){
	res.render('teacherarea', { title: "Teacher authenticated" } );
});

app.get('/admin', auth.check, function( req, res ){
	res.render('admin', {title: "Authentication start" });
} );

app.get('/logout', auth.logout, function(req,res){
	res.send("Logged out");
} );

// POST
app.post('/login', auth.login, function(req, res){
	res.send("Logged in");
} );

////////////////////////////////////
app.listen(port);<|endoftext|>


<commit_before>// Register that we're using es6, so babel can compile import statements.
// The `ignore` set to false allows babel to compile npm modules, and the `only`
// forces it to only compile files with a `.es6.js` or `.jsx` extension.
require('babel/register')({
  ignore: false,
  only: /.+(?:(?:\.es6\.js)|(?:.jsx))$/,
  extensions: ['.js', '.es6.js', '.jsx' ],
  sourceMap: true,
});

// Require in the express server.
var Server = require('./src/server');

var cluster = require('cluster');
var numCPUs = process.env.PROCESSES || require('os').cpus().length;

// App config
var defaultConfig = require('./src/config');
var config = defaultConfig();

// Import built-asset manifests for passing to layouts
var jsManifest = require('./build/js/client-manifest.json');
var cssManifest = require('./build/css/css-manifest.json');
var servers = [];

var failedProcesses = 0;

// Then merge them into a single object for ease of use later
config.manifest = {};
config.processes = numCPUs;

function parseObject (list) {
  if (!list) { return; }
  var obj = {};
  var key;
  var value;
  var split;

  list.split(';').forEach(function (l) {
    if (l && l.indexOf('=')) {
      var split = l.split('=');
      obj[split[0].trim()] = split[1].trim();
    }
  });

  return obj;
}

function parseList (list) {
  if (!list) { return; }
  return list.split(';');
}

config.apiHeaders = parseObject(process.env.API_HEADERS);
config.apiPassThroughHeaders = parseList(process.env.API_PASS_THROUGH_HEADERS);
config.statsDomain = process.env.STATS_DOMAIN || 'https://stats.redditmedia.com/';
config.actionNameSecret = process.env.ACTION_NAME_SECRET;

config.experiments = parseObject(process.env.EXPERIMENTS);

Object.assign(config.manifest, jsManifest, cssManifest);

function start(config) {
  var server = new Server(config);
  server.start();
  return server;
}

// Private, server-only config that we don't put in config.js, which is shared
config.liveReload = process.env.LIVERELOAD === 'true';
config.oauth = {
  clientId: process.env.OAUTH_CLIENT_ID || '',
  secret: process.env.OAUTH_SECRET || '',

  secretClientId: process.env.SECRET_OAUTH_CLIENT_ID || '',
  secretSecret: process.env.SECRET_OAUTH_SECRET || '',
};

config.keys = [ process.env.SERVER_SIGNED_COOKIE_KEY || 'lambeosaurus' ];

if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  Server.info(config);

  cluster.on('exit', function(worker, code, signal) {
    if (failedProcesses < 20) {
      console.log('Worker ' + worker.process.pid + ' died, restarting.');
      cluster.fork();
      failedProcesses++;
    } else {
      console.log('Workers died too many times, exiting.');
      process.exit();
    }
  });
} else {
  servers.push(start(config));
}
<commit_msg>node ultralog<commit_after>// Register that we're using es6, so babel can compile import statements.
// The `ignore` set to false allows babel to compile npm modules, and the `only`
// forces it to only compile files with a `.es6.js` or `.jsx` extension.
require('babel/register')({
  ignore: false,
  only: /.+(?:(?:\.es6\.js)|(?:.jsx))$/,
  extensions: ['.js', '.es6.js', '.jsx' ],
  sourceMap: true,
});

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
  process.exit();
});

// Require in the express server.
var Server = require('./src/server');

var cluster = require('cluster');
var numCPUs = process.env.PROCESSES || require('os').cpus().length;

// App config
var defaultConfig = require('./src/config');
var config = defaultConfig();

// Import built-asset manifests for passing to layouts
var jsManifest = require('./build/js/client-manifest.json');
var cssManifest = require('./build/css/css-manifest.json');
var servers = [];

var failedProcesses = 0;

// Then merge them into a single object for ease of use later
config.manifest = {};
config.processes = numCPUs;

function parseObject (list) {
  if (!list) { return; }
  var obj = {};
  var key;
  var value;
  var split;

  list.split(';').forEach(function (l) {
    if (l && l.indexOf('=')) {
      var split = l.split('=');
      obj[split[0].trim()] = split[1].trim();
    }
  });

  return obj;
}

function parseList (list) {
  if (!list) { return; }
  return list.split(';');
}

config.apiHeaders = parseObject(process.env.API_HEADERS);
config.apiPassThroughHeaders = parseList(process.env.API_PASS_THROUGH_HEADERS);
config.statsDomain = process.env.STATS_DOMAIN || 'https://stats.redditmedia.com/';
config.actionNameSecret = process.env.ACTION_NAME_SECRET;

config.experiments = parseObject(process.env.EXPERIMENTS);

Object.assign(config.manifest, jsManifest, cssManifest);

function start(config) {
  var server = new Server(config);
  server.start();
  return server;
}

// Private, server-only config that we don't put in config.js, which is shared
config.liveReload = process.env.LIVERELOAD === 'true';
config.oauth = {
  clientId: process.env.OAUTH_CLIENT_ID || '',
  secret: process.env.OAUTH_SECRET || '',

  secretClientId: process.env.SECRET_OAUTH_CLIENT_ID || '',
  secretSecret: process.env.SECRET_OAUTH_SECRET || '',
};

config.keys = [ process.env.SERVER_SIGNED_COOKIE_KEY || 'lambeosaurus' ];

if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  Server.info(config);

  cluster.on('exit', function(worker, code, signal) {
    if (failedProcesses < 20) {
      console.log('Worker ' + worker.process.pid + ' died, restarting.');
      cluster.fork();
      failedProcesses++;
    } else {
      console.log('Workers died too many times, exiting.');
      process.exit();
    }
  });
} else {
  servers.push(start(config));
}
<|endoftext|>


<commit_before>var request = require('request'),
    BASE_URL = 'https://hummingbird.me/api/v2',
    ANIME_ID_URL = BASE_URL+'/anime/{id}',
    ANIME_MALID_URL = BASE_URL+'/anime/myanimelist:{malid}';

function _res(callback) {
    return function(error, response, body) {
        if (error)
            return callback(error);
        if (response.statusCode == 200) {
            try {
                var data = JSON.parse(body);
            } catch (err) {
                callback(err);
            }
			if(callback.length==3 && data.anime && data.linked.episodes)
				return callback(null, data.anime,data.linked.episodes);
			else if(callback.length==4 && data.anime && data.linked.episodes && data.linked.gallery_images)
				return callback(null, data.anime,data.linked.episodes,data.linked.gallery_images);
			else
				return callback(null,data);
        }else if(response.statusCode== 404){
			return callback(null,[]);
		}else {
            try {
                error = JSON.parse(body);
            } catch (err) {
                callback(err);
            }
		}
        return callback(error);
    }
}

function HB(key) {
    if (!key)
        throw new ReferenceError('API key is not defined');
    this.key = key;
};

HB.prototype.animeById = function getAnimeById(id, callback) {
    var options = {
        url: ANIME_ID_URL.replace('{id}', id),
        headers: {
            'X-Client-Id': this.key
        }
    };
    request(options, _res(callback));
};

HB.prototype.animeByMalId = function getAnimeByMalId(malid, callback) {
    var options = {
        url: ANIME_ID_URL.replace('{malid}', malid),
        headers: {
            'X-Client-Id': this.key
        }
    };
    request(options, _res(callback));
};

module.exports = HB;
<commit_msg>update comments<commit_after>var request = require('request'),
    BASE_URL = 'https://hummingbird.me/api/v2',
    ANIME_ID_URL = BASE_URL+'/anime/{id}',
    ANIME_MALID_URL = BASE_URL+'/anime/myanimelist:{malid}';

function _res(callback) {
    return function(error, response, body) {
        if (error)
            return callback(error);
        if (response.statusCode == 200) {
            try {
                var data = JSON.parse(body);
            } catch (err) {
                callback(err);
            }
			if(callback.length==3 && data.anime && data.linked.episodes)
				return callback(null, data.anime,data.linked.episodes);
			else if(callback.length==4 && data.anime && data.linked.episodes && data.linked.gallery_images)
				return callback(null, data.anime,data.linked.episodes,data.linked.gallery_images);
			else
				return callback(null,data);
        }else if(response.statusCode== 404){
			return callback(null,[]);
		}else {
            try {
                error = JSON.parse(body);
            } catch (err) {
                callback(err);
            }
		}
        return callback(error);
    }
}

function HB(key) {
    if (!key)
        throw new ReferenceError('API key is not defined');
    this.key = key;
};

// Get anime by id
HB.prototype.animeById = function getAnimeById(id, callback) {
    var options = {
        url: ANIME_ID_URL.replace('{id}', id),
        headers: {
            'X-Client-Id': this.key
        }
    };
    request(options, _res(callback));
};

// Get anime by malid
HB.prototype.animeByMalId = function getAnimeByMalId(malid, callback) {
    var options = {
        url: ANIME_ID_URL.replace('{malid}', malid),
        headers: {
            'X-Client-Id': this.key
        }
    };
    request(options, _res(callback));
};

module.exports = HB;
<|endoftext|>


<commit_before>const path = require('path')
const fastCgi = require('fastcgi-client')
const defaultOptions = {
  host: '127.0.0.1',
  port: 9000,
  documentRoot: path.dirname(require.main.filename || '.'),
  skipCheckServer: true
}

module.exports = function (userOptions = {}, customParams = {}) {
  const options = Object.assign({}, defaultOptions, userOptions)
  const fpm = new Promise((resolve, reject) => {
    const loader = fastCgi(options)
    loader.on('ready', () => resolve(loader))
    loader.on('error', reject)
  })

  return async function (req, res) {
    let params = Object.assign({}, customParams, {
      uri: req.url
    })

    if (!params.uri || !params.uri.startsWith('/')) {
      throw new Error('invalid uri')
    }

    if (options.rewrite) {
      const rules = Array.isArray(options.rewrite)
        ? options.rewrite : [options.rewrite]
      for (const rule of rules) {
        const match = params.uri.match(rule.search || /.*/)
        if (match) {
          let result = rule.replace
          for (const index in match) {
            const selector = new RegExp(`\\$${index}`, 'g')
            result = result.replace(selector, match[index])
          }
          params.outerUri = params.uri
          params.uri = result
          break
        }
      }
    }

    if (params.uri.indexOf('?') !== -1) {
      params.document = params.uri.split('?')[0]
      params.query = params.uri
        .slice(params.document.length + 1)
        .replace(/\?/g, '&')
    }

    if (!params.script) {
      params.script = path.join(options.documentRoot, params.document || params.uri)
    }

    const headers = {
      REQUEST_METHOD: req.method,
      CONTENT_TYPE: req.headers['content-type'],
      CONTENT_LENGTH: req.headers['content-length'],
      CONTENT_DISPOSITION: req.headers['content-disposition'],
      DOCUMENT_ROOT: options.documentRoot,
      SCRIPT_FILENAME: params.script,
      SCRIPT_NAME: params.script.split('/').pop(),
      REQUEST_URI: params.outerUri || params.uri,
      DOCUMENT_URI: params.document || params.uri,
      QUERY_STRING: params.query,
      REQUEST_SCHEME: req.protocol,
      HTTPS: req.protocol === 'https' ? 'on' : undefined,
      REMOTE_ADDR: req.connection.remoteAddress,
      REMOTE_PORT: req.connection.remotePort,
      SERVER_NAME: req.connection.domain,
      HTTP_HOST: req.headers.host,
      HTTP_COOKIE: req.headers.cookie,
      SERVER_PROTOCOL: 'HTTP/1.1',
      GATEWAY_INTERFACE: 'CGI/1.1',
      SERVER_SOFTWARE: 'php-fpm for Node',
      REDIRECT_STATUS: 200
    }

    for (const header in headers) {
      if (typeof headers[header] === 'undefined') { delete headers[header] }
    }

    if (options.debug) {
      console.log(headers)
    }

    const php = await fpm
    return new Promise(function (resolve, reject) {
      php.request(headers, function (err, request) {
        if (err) { reject(err) }
        var output = ''
        var errors = ''

        req.pipe(request.stdin)

        request.stdout.on('data', function (data) {
          output += data.toString('utf8')
        })

        request.stderr.on('data', function (data) {
          errors += data.toString('utf8')
        })

        request.stdout.on('end', function () {
          if (errors) { reject(new Error(errors)) }

          const head = output.match(/^[\s\S]*?\r\n\r\n/)[0]
          const parseHead = head.split('\r\n').filter(_ => _)
          for (const item of parseHead) {
            const pair = item.split(': ')
            res.setHeader(pair[0], pair[1])
            if (pair[0] === 'Status') {
              res.statusCode = parseInt(pair[1].match(/\d+/)[0])
            }
          }
          const body = output.slice(head.length)
          res.write(body)
          res.end()

          resolve({ headers, body })
        })
      })
    })
  }
}
<commit_msg>Send all HTTP headers<commit_after>const path = require('path')
const fastCgi = require('fastcgi-client')
const defaultOptions = {
  host: '127.0.0.1',
  port: 9000,
  documentRoot: path.dirname(require.main.filename || '.'),
  skipCheckServer: true
}

module.exports = function (userOptions = {}, customParams = {}) {
  const options = Object.assign({}, defaultOptions, userOptions)
  const fpm = new Promise((resolve, reject) => {
    const loader = fastCgi(options)
    loader.on('ready', () => resolve(loader))
    loader.on('error', reject)
  })

  return async function (req, res) {
    let params = Object.assign({}, customParams, {
      uri: req.url
    })

    if (!params.uri || !params.uri.startsWith('/')) {
      throw new Error('invalid uri')
    }

    if (options.rewrite) {
      const rules = Array.isArray(options.rewrite)
        ? options.rewrite : [options.rewrite]
      for (const rule of rules) {
        const match = params.uri.match(rule.search || /.*/)
        if (match) {
          let result = rule.replace
          for (const index in match) {
            const selector = new RegExp(`\\$${index}`, 'g')
            result = result.replace(selector, match[index])
          }
          params.outerUri = params.uri
          params.uri = result
          break
        }
      }
    }

    if (params.uri.indexOf('?') !== -1) {
      params.document = params.uri.split('?')[0]
      params.query = params.uri
        .slice(params.document.length + 1)
        .replace(/\?/g, '&')
    }

    if (!params.script) {
      params.script = path.join(options.documentRoot, params.document || params.uri)
    }

    const headers = {
      REQUEST_METHOD: req.method,
      CONTENT_TYPE: req.headers['content-type'],
      CONTENT_LENGTH: req.headers['content-length'],
      CONTENT_DISPOSITION: req.headers['content-disposition'],
      DOCUMENT_ROOT: options.documentRoot,
      SCRIPT_FILENAME: params.script,
      SCRIPT_NAME: params.script.split('/').pop(),
      REQUEST_URI: params.outerUri || params.uri,
      DOCUMENT_URI: params.document || params.uri,
      QUERY_STRING: params.query,
      REQUEST_SCHEME: req.protocol,
      HTTPS: req.protocol === 'https' ? 'on' : undefined,
      REMOTE_ADDR: req.connection.remoteAddress,
      REMOTE_PORT: req.connection.remotePort,
      SERVER_NAME: req.connection.domain,
      SERVER_PROTOCOL: 'HTTP/1.1',
      GATEWAY_INTERFACE: 'CGI/1.1',
      SERVER_SOFTWARE: 'php-fpm for Node',
      REDIRECT_STATUS: 200
    }

    for (const header in headers) {
      if (typeof headers[header] === 'undefined') { delete headers[header] }
    }

    for (header in req.headers) {
      headers['HTTP_' + header.toUpperCase().replace(/-/g, '_')] = req.headers[header];
    }

    if (options.debug) {
      console.log(headers)
    }

    const php = await fpm
    return new Promise(function (resolve, reject) {
      php.request(headers, function (err, request) {
        if (err) { reject(err) }
        var output = ''
        var errors = ''

        req.pipe(request.stdin)

        request.stdout.on('data', function (data) {
          output += data.toString('utf8')
        })

        request.stderr.on('data', function (data) {
          errors += data.toString('utf8')
        })

        request.stdout.on('end', function () {
          if (errors) { reject(new Error(errors)) }

          const head = output.match(/^[\s\S]*?\r\n\r\n/)[0]
          const parseHead = head.split('\r\n').filter(_ => _)
          for (const item of parseHead) {
            const pair = item.split(': ')
            res.setHeader(pair[0], pair[1])
            if (pair[0] === 'Status') {
              res.statusCode = parseInt(pair[1].match(/\d+/)[0])
            }
          }
          const body = output.slice(head.length)
          res.write(body)
          res.end()

          resolve({ headers, body })
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var _ = require('lodash')
var Mustache = require('mustache');

var d = new Date();
var curyear = d.getFullYear();

function getMonth(startDateStr) {
    switch (startDateStr.substr(5,2)) {
    case '01':
        return "January ";
    case '02':
        return "February ";
    case '03':
        return "March ";
    case '04':
        return "April ";
    case '05':
        return "May ";
    case '06':
        return "June ";
    case '07':
        return "July ";
    case '08':
        return "August ";
    case '09':
        return "September ";
    case '10':
        return "October ";
    case '11':
        return "November ";
    case '12':
        return "December ";
    }
}

function render(resumeObject) {

    resumeObject.basics.capitalName = resumeObject.basics.name.toUpperCase();

    _.each(resumeObject.basics.profiles, function(p){
        switch(p.network.toLowerCase()) {
            case "facebook":
                p.iconClass = "fa fa-facebook-square";
                break;
            case "github":
                p.iconClass = "fa fa-github-square";
                break;
            case "twitter":
                p.iconClass = "fa fa-twitter-square";
                break;
            case "googleplus":
                p.iconClass = "fa fa-google-plus-square";
                break;
            case "youtube":
                p.iconClass = "fa fa-youtube-square";
                break;
            case "vimeo":
                p.iconClass = "fa fa-vimeo-square";
                break;
            case "linkedin":
                p.iconClass = "fa fa-linkedin-square";
                break;
            case "pinterest":
                p.iconClass = "fa fa-pinterest-square";
                break;
            case "flickr":
                p.iconClass = "fa fa-flickr";
                break;
            case "behance":
                p.iconClass = "fa fa-behance-square";
                break;
            case "codepen":
                p.iconClass = "fa fa-codepen-square";
                break;
            case "soundcloud":
                p.iconClass = "fa fa-soundcloud";
                break;
            case "steam":
                p.iconClass = "fa fa-steam";
                break;
            case "reddit":
                p.iconClass = "fa fa-reddit";
                break;
            case "blog":
                p.iconClass = "fa fa-rss-square";
                break;
        }

        if (p.url) {
            p.text = p.url;
        } else {
            p.text = p.network + ": " + p.username;
        }
    });

    if (resumeObject.work && resumeObject.work.length) {
        resumeObject.workBool = true;
        _.each(resumeObject.work, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.volunteer && resumeObject.volunteer.length) {
        resumeObject.volunteerBool = true;
        _.each(resumeObject.volunteer, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.education && resumeObject.education.length) {
        if (resumeObject.education[0].institution) {
            resumeObject.educationBool = true;
            _.each(resumeObject.education, function(e){
                if( !e.area || !e.studyType ){
                  e.educationDetail = (e.area == null ? '' : e.area) + (e.studyType == null ? '' : e.studyType);
                } else {
                  e.educationDetail = e.area + ", "+ e.studyType;
                }
                if (e.startDate) {
                    e.startDateYear = e.startDate.substr(0,4);
                    e.startDateMonth = getMonth(e.startDate || "");
                } else {
                    e.endDateMonth = "";
                }
                if (e.endDate) {
                    e.endDateYear = e.endDate.substr(0,4);
                    e.endDateMonth = getMonth(e.endDate || "")

                    if (e.endDateYear > curyear) {
                        e.endDateYear += " (expected)";
                    }
                } else {
                    e.endDateYear = 'Present'
                    e.endDateMonth = '';
                }
                if (e.courses) {
                    if (e.courses[0]) {
                        if (e.courses[0] != "") {
                            e.educationCourses = true;
                        }
                    }
                }
            });
        }
    }

    if (resumeObject.awards && resumeObject.awards.length) {
        if (resumeObject.awards[0].title) {
            resumeObject.awardsBool = true;
            _.each(resumeObject.awards, function(a){
                a.year = (a.date || "").substr(0,4);
                a.day = (a.date || "").substr(8,2);
                a.month = getMonth(a.date || "");
            });
        }
    }

    if (resumeObject.publications && resumeObject.publications.length) {
        if (resumeObject.publications[0].name) {
            resumeObject.publicationsBool = true;
            _.each(resumeObject.publications, function(a){
                a.year = (a.releaseDate || "").substr(0,4);
                a.day = (a.releaseDate || "").substr(8,2);
                a.month = getMonth(a.releaseDate || "");
            });
        }
    }

    if (resumeObject.skills && resumeObject.skills.length) {
        if (resumeObject.skills[0].name) {
            resumeObject.skillsBool = true;
        }
    }

    if (resumeObject.interests && resumeObject.interests.length) {
        if (resumeObject.interests[0].name) {
            resumeObject.interestsBool = true;
        }
    }

    if (resumeObject.languages && resumeObject.languages.length) {
        if (resumeObject.languages[0].language) {
            resumeObject.languagesBool = true;
        }
    }

    if (resumeObject.references && resumeObject.references.length) {
        if (resumeObject.references[0].name) {
            resumeObject.referencesBool = true;
        }
    }

    resumeObject.css = fs.readFileSync(__dirname + "/style.css", "utf-8");
    resumeObject.printcss = fs.readFileSync(__dirname + "/print.css", "utf-8");
    var theme = fs.readFileSync(__dirname + '/resume.template', 'utf8');
    var resumeHTML = Mustache.render(theme, resumeObject);

    return resumeHTML;
};
module.exports = {
    render: render
}
<commit_msg>Updated social networks<commit_after>var fs = require('fs');
var _ = require('lodash')
var Mustache = require('mustache');

var d = new Date();
var curyear = d.getFullYear();

function getMonth(startDateStr) {
    switch (startDateStr.substr(5,2)) {
    case '01':
        return "January ";
    case '02':
        return "February ";
    case '03':
        return "March ";
    case '04':
        return "April ";
    case '05':
        return "May ";
    case '06':
        return "June ";
    case '07':
        return "July ";
    case '08':
        return "August ";
    case '09':
        return "September ";
    case '10':
        return "October ";
    case '11':
        return "November ";
    case '12':
        return "December ";
    }
}

function render(resumeObject) {

    resumeObject.basics.capitalName = resumeObject.basics.name.toUpperCase();

    _.each(resumeObject.basics.profiles, function(p){
        switch(p.network.toLowerCase()) {
            case "Facebook":
            case "facebook":
                p.iconClass = "fa fa-facebook-square";
                break;
            case "Github":
            case "github":
                p.iconClass = "fa fa-github-square";
                break;
            case "Twitter":
            case "twitter":
                p.iconClass = "fa fa-twitter-square";
                break;
            case "googlePlus":
            case "GooglePlus":
            case: "google-plus":
            case "googleplus":
                p.iconClass = "fa fa-google-plus-square";
                break;
            case "youtube":
            case "Youtube":
            case "YouTube":
                p.iconClass = "fa fa-youtube-square";
                break;
            case "vimeo":
            case: "Vimeo":
                p.iconClass = "fa fa-vimeo-square";
                break;
            case "linkedin":
            case "Linkedin":
                p.iconClass = "fa fa-linkedin-square";
                break;
            case "pinterest":
            case "Pinterest":
                p.iconClass = "fa fa-pinterest-square";
                break;
            case "flickr":
            case "flicker":
            case: "Flickr":
                p.iconClass = "fa fa-flickr";
                break;
            case "behance":
            case "Behance":
                p.iconClass = "fa fa-behance-square";
                break;
            case "codepen":
            case "Codepen":
            case "codePen":
                p.iconClass = "fa fa-codepen";
                break;
            case "soundcloud":
            case "Soundcloud":
            case "soundCloud":
                p.iconClass = "fa fa-soundcloud";
                break;
            case "steam":
            case "Steam":
                p.iconClass = "fa fa-steam";
                break;
            case "reddit":
            case "Reddit":
                p.iconClass = "fa fa-reddit";
                break;
            case "tumblr":
            case "Tumblr":
            case "tumbler":
                p.iconClass = "fa fa-tumblr-square";
                break;
            case "stack-overflow":
            case "stackOverflow":
            case "StackOverflow":
                p.iconClass = "fa fa-stack-overflow";
                break;
            case "blog":
            case "Blog":
            case "rss":
                p.iconClass = "fa fa-rss-square";
                break;
        }

        if (p.url) {
            p.text = p.url;
        } else {
            p.text = p.network + ": " + p.username;
        }
    });

    if (resumeObject.work && resumeObject.work.length) {
        resumeObject.workBool = true;
        _.each(resumeObject.work, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.volunteer && resumeObject.volunteer.length) {
        resumeObject.volunteerBool = true;
        _.each(resumeObject.volunteer, function(w){
            if (w.startDate) {
                w.startDateYear = (w.startDate || "").substr(0,4);
                w.startDateMonth = getMonth(w.startDate || "");

            }
            if(w.endDate) {
                w.endDateYear = (w.endDate || "").substr(0,4);
                w.endDateMonth = getMonth(w.endDate || "");
            } else {
                w.endDateYear = 'Present'
            }
            if (w.highlights) {
                if (w.highlights[0]) {
                    if (w.highlights[0] != "") {
                        w.boolHighlights = true;
                    }
                }
            }
        });
    }

    if (resumeObject.education && resumeObject.education.length) {
        if (resumeObject.education[0].institution) {
            resumeObject.educationBool = true;
            _.each(resumeObject.education, function(e){
                if( !e.area || !e.studyType ){
                  e.educationDetail = (e.area == null ? '' : e.area) + (e.studyType == null ? '' : e.studyType);
                } else {
                  e.educationDetail = e.area + ", "+ e.studyType;
                }
                if (e.startDate) {
                    e.startDateYear = e.startDate.substr(0,4);
                    e.startDateMonth = getMonth(e.startDate || "");
                } else {
                    e.endDateMonth = "";
                }
                if (e.endDate) {
                    e.endDateYear = e.endDate.substr(0,4);
                    e.endDateMonth = getMonth(e.endDate || "")

                    if (e.endDateYear > curyear) {
                        e.endDateYear += " (expected)";
                    }
                } else {
                    e.endDateYear = 'Present'
                    e.endDateMonth = '';
                }
                if (e.courses) {
                    if (e.courses[0]) {
                        if (e.courses[0] != "") {
                            e.educationCourses = true;
                        }
                    }
                }
            });
        }
    }

    if (resumeObject.awards && resumeObject.awards.length) {
        if (resumeObject.awards[0].title) {
            resumeObject.awardsBool = true;
            _.each(resumeObject.awards, function(a){
                a.year = (a.date || "").substr(0,4);
                a.day = (a.date || "").substr(8,2);
                a.month = getMonth(a.date || "");
            });
        }
    }

    if (resumeObject.publications && resumeObject.publications.length) {
        if (resumeObject.publications[0].name) {
            resumeObject.publicationsBool = true;
            _.each(resumeObject.publications, function(a){
                a.year = (a.releaseDate || "").substr(0,4);
                a.day = (a.releaseDate || "").substr(8,2);
                a.month = getMonth(a.releaseDate || "");
            });
        }
    }

    if (resumeObject.skills && resumeObject.skills.length) {
        if (resumeObject.skills[0].name) {
            resumeObject.skillsBool = true;
        }
    }

    if (resumeObject.interests && resumeObject.interests.length) {
        if (resumeObject.interests[0].name) {
            resumeObject.interestsBool = true;
        }
    }

    if (resumeObject.languages && resumeObject.languages.length) {
        if (resumeObject.languages[0].language) {
            resumeObject.languagesBool = true;
        }
    }

    if (resumeObject.references && resumeObject.references.length) {
        if (resumeObject.references[0].name) {
            resumeObject.referencesBool = true;
        }
    }

    resumeObject.css = fs.readFileSync(__dirname + "/style.css", "utf-8");
    resumeObject.printcss = fs.readFileSync(__dirname + "/print.css", "utf-8");
    var theme = fs.readFileSync(__dirname + '/resume.template', 'utf8');
    var resumeHTML = Mustache.render(theme, resumeObject);

    return resumeHTML;
};
module.exports = {
    render: render
}
<|endoftext|>


<commit_before>'use strict';
/* eslint eqeqeq: 1, no-console:0 no-else-return: 1, no-cond-assign: 1, consistent-return: 1 */
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const dialog = electron.dialog;
const _ = require('lodash');
const EventEmitter = require('events').EventEmitter;
const autoUpdater = require('./auto-updater');
const debug = require('debug')('hadron-auto-update-manager');
const BrowserWindow = require('electron').BrowserWindow;
const ENOSIGNATURE = 'Could not get code signature for running application';
const app = electron.app;

const IdleState = 'idle';
const CheckingState = 'checking';
const DownloadingState = 'downloading';
const UpdateAvailableState = 'update-available';
const NoUpdateAvailableState = 'no-update-available';
const UnsupportedState = 'unsupported';
const ErrorState = 'error';

function AutoUpdateManager(endpointURL) {
  if (!endpointURL) {
    throw new TypeError('endpointURL is required!');
  }
  this.endpointURL = endpointURL;
  this.version = app.getVersion();
  this.onUpdateError = _.bind(this.onUpdateError, this);
  this.onUpdateNotAvailable = _.bind(this.onUpdateNotAvailable, this);
  this.state = IdleState;
  this.feedURL = `${endpointURL}/updates?version=${this.version}`;
  debug('auto updater ready and waiting.', {
    version: this.version,
    feedURL: this.feedURL
  });

  process.nextTick( () => this.setupAutoUpdater());
}
_.extend(AutoUpdateManager.prototype, EventEmitter.prototype);

AutoUpdateManager.prototype.setupAutoUpdater = function() {
  autoUpdater.setFeedURL(this.feedURL);
  autoUpdater.on('error', (event, message) => {
    if (message === ENOSIGNATURE) {
      return debug('no auto updater for unsigned builds');
    }
    debug('Error Downloading Update: ' + message);
    return this.setState(ErrorState);
  });

  autoUpdater.on('checking-for-update', () => {
    this.setState(CheckingState);
  });

  autoUpdater.on('update-not-available', () => {
    this.setState(NoUpdateAvailableState);
  });
  autoUpdater.on('update-available', () => {
    this.setState(DownloadingState);
  });
  autoUpdater.on('update-downloaded', (event, releaseNotes, releaseVersion) => {
    this.releaseNotes = releaseNotes;
    this.releaseVersion = releaseVersion;
    this.setState(UpdateAvailableState);
    this.emitUpdateAvailableEvent();
  });

  this.check({
    hidePopups: true
  });
  setInterval((function(_this) {
    return function() {
      var ref;
      if ((ref = _this.state) === UpdateAvailableState || ref === UnsupportedState) {
        console.log('Skipping update check... update ready to install, or updater unavailable.');
        return;
      }
      return _this.check({
        hidePopups: true
      });
    };
  })(this), 1000 * 60 * 30);
  if (autoUpdater.supportsUpdates != null) {
    if (!autoUpdater.supportsUpdates()) {
      return this.setState(UnsupportedState);
    }
  }
};

AutoUpdateManager.prototype.emitUpdateAvailableEvent = function() {
  if (!this.releaseVersion) {
    return;
  }
  BrowserWindow.getAllWindows().each((_browserWindow) => {
    debug('sending app:update-available');
    if (_browserWindow.webContents) {
      _browserWindow.webContents.send('app:update-available', {
        releaseVersion: this.releaseVersion,
        releaseNotes: this.releaseNotes
      });
    }
  });
};

AutoUpdateManager.prototype.setState = function(state) {
  if (this.state === state) {
    return;
  }
  this.state = state;
  return this.emit('state-changed', this.state);
};

AutoUpdateManager.prototype.getState = function() {
  return this.state;
};

AutoUpdateManager.prototype.check = function(arg) {
  var hidePopups;
  hidePopups = (arg != null ? arg : {}).hidePopups;
  if (!hidePopups) {
    autoUpdater.once('update-not-available', this.onUpdateNotAvailable);
    autoUpdater.once('error', this.onUpdateError);
  }
  if (process.platform === 'win32') {
    return autoUpdater.downloadAndInstallUpdate();
  } else {
    return autoUpdater.checkForUpdates();
  }
};

AutoUpdateManager.prototype.install = function() {
  if (process.platform === 'win32') {
    return autoUpdater.restartN1();
  } else {
    return autoUpdater.quitAndInstall();
  }
};

AutoUpdateManager.prototype.iconURL = function() {
  var url;
  url = path.join(process.resourcesPath, 'app', 'nylas.png');
  if (!fs.existsSync(url)) {
    return void 0;
  }
  return url;
};

AutoUpdateManager.prototype.onUpdateNotAvailable = function() {
  autoUpdater.removeListener('error', this.onUpdateError);
  return dialog.showMessageBox({
    type: 'info',
    buttons: ['OK'],
    icon: this.iconURL(),
    message: 'No update available.',
    title: 'No Update Available',
    detail: 'You\'re running the latest version of N1 (' + this.version + ').'
  });
};

AutoUpdateManager.prototype.onUpdateError = function(event, message) {
  autoUpdater.removeListener('update-not-available', this.onUpdateNotAvailable);
  return dialog.showMessageBox({
    type: 'warning',
    buttons: ['OK'],
    icon: this.iconURL(),
    message: 'There was an error checking for updates.',
    title: 'Update Error',
    detail: message
  });
};

module.exports = AutoUpdateManager;
<commit_msg>Need to set error event handler before setting feedURL<commit_after>'use strict';
/* eslint eqeqeq: 1, no-console:0 no-else-return: 1, no-cond-assign: 1, consistent-return: 1 */
const path = require('path');
const fs = require('fs');
const electron = require('electron');
const dialog = electron.dialog;
const _ = require('lodash');
const EventEmitter = require('events').EventEmitter;
const autoUpdater = require('./auto-updater');
const debug = require('debug')('hadron-auto-update-manager');
const BrowserWindow = require('electron').BrowserWindow;
const ENOSIGNATURE = 'Could not get code signature for running application';
const app = electron.app;

const IdleState = 'idle';
const CheckingState = 'checking';
const DownloadingState = 'downloading';
const UpdateAvailableState = 'update-available';
const NoUpdateAvailableState = 'no-update-available';
const UnsupportedState = 'unsupported';
const ErrorState = 'error';

function AutoUpdateManager(endpointURL) {
  if (!endpointURL) {
    throw new TypeError('endpointURL is required!');
  }
  this.endpointURL = endpointURL;
  this.version = app.getVersion();
  this.onUpdateError = _.bind(this.onUpdateError, this);
  this.onUpdateNotAvailable = _.bind(this.onUpdateNotAvailable, this);
  this.state = IdleState;
  this.feedURL = `${endpointURL}/updates?version=${this.version}`;
  debug('auto updater ready and waiting.', {
    version: this.version,
    feedURL: this.feedURL
  });

  process.nextTick( () => this.setupAutoUpdater());
}
_.extend(AutoUpdateManager.prototype, EventEmitter.prototype);

AutoUpdateManager.prototype.setupAutoUpdater = function() {
  // Need to set error event handler before setting feedURL.
  // Else we get the default node.js error event handling:
  // die hard if errors are unhandled.
  autoUpdater.on('error', (event, message) => {
    if (message === ENOSIGNATURE) {
      return debug('no auto updater for unsigned builds');
    }
    debug('Error Downloading Update: ' + message);
    return this.setState(ErrorState);
  });

  autoUpdater.setFeedURL(this.feedURL);

  autoUpdater.on('checking-for-update', () => {
    this.setState(CheckingState);
  });

  autoUpdater.on('update-not-available', () => {
    this.setState(NoUpdateAvailableState);
  });
  autoUpdater.on('update-available', () => {
    this.setState(DownloadingState);
  });
  autoUpdater.on('update-downloaded', (event, releaseNotes, releaseVersion) => {
    this.releaseNotes = releaseNotes;
    this.releaseVersion = releaseVersion;
    this.setState(UpdateAvailableState);
    this.emitUpdateAvailableEvent();
  });

  this.check({
    hidePopups: true
  });
  setInterval((function(_this) {
    return function() {
      var ref;
      if ((ref = _this.state) === UpdateAvailableState || ref === UnsupportedState) {
        console.log('Skipping update check... update ready to install, or updater unavailable.');
        return;
      }
      return _this.check({
        hidePopups: true
      });
    };
  })(this), 1000 * 60 * 30);
  if (autoUpdater.supportsUpdates != null) {
    if (!autoUpdater.supportsUpdates()) {
      return this.setState(UnsupportedState);
    }
  }
};

AutoUpdateManager.prototype.emitUpdateAvailableEvent = function() {
  if (!this.releaseVersion) {
    return;
  }
  BrowserWindow.getAllWindows().each((_browserWindow) => {
    debug('sending app:update-available');
    if (_browserWindow.webContents) {
      _browserWindow.webContents.send('app:update-available', {
        releaseVersion: this.releaseVersion,
        releaseNotes: this.releaseNotes
      });
    }
  });
};

AutoUpdateManager.prototype.setState = function(state) {
  if (this.state === state) {
    return;
  }
  this.state = state;
  return this.emit('state-changed', this.state);
};

AutoUpdateManager.prototype.getState = function() {
  return this.state;
};

AutoUpdateManager.prototype.check = function(arg) {
  var hidePopups;
  hidePopups = (arg != null ? arg : {}).hidePopups;
  if (!hidePopups) {
    autoUpdater.once('update-not-available', this.onUpdateNotAvailable);
    autoUpdater.once('error', this.onUpdateError);
  }
  if (process.platform === 'win32') {
    return autoUpdater.downloadAndInstallUpdate();
  } else {
    return autoUpdater.checkForUpdates();
  }
};

AutoUpdateManager.prototype.install = function() {
  if (process.platform === 'win32') {
    return autoUpdater.restartN1();
  } else {
    return autoUpdater.quitAndInstall();
  }
};

AutoUpdateManager.prototype.iconURL = function() {
  var url;
  url = path.join(process.resourcesPath, 'app', 'nylas.png');
  if (!fs.existsSync(url)) {
    return void 0;
  }
  return url;
};

AutoUpdateManager.prototype.onUpdateNotAvailable = function() {
  autoUpdater.removeListener('error', this.onUpdateError);
  return dialog.showMessageBox({
    type: 'info',
    buttons: ['OK'],
    icon: this.iconURL(),
    message: 'No update available.',
    title: 'No Update Available',
    detail: 'You\'re running the latest version of N1 (' + this.version + ').'
  });
};

AutoUpdateManager.prototype.onUpdateError = function(event, message) {
  autoUpdater.removeListener('update-not-available', this.onUpdateNotAvailable);
  return dialog.showMessageBox({
    type: 'warning',
    buttons: ['OK'],
    icon: this.iconURL(),
    message: 'There was an error checking for updates.',
    title: 'Update Error',
    detail: message
  });
};

module.exports = AutoUpdateManager;
<|endoftext|>


<commit_before>import React from 'react';
import D from 'react-dom';

require('./styles/main.scss');

import About from './components/about';
import Fadder from './components/fadder';
import Join from './components/join';

const App = () => {
  return (

      <About />
      <Fadder />
      <Join />

  );
};

D.render(
  <App />,
  document.getElementById('app')
);
<commit_msg>Update scss includes in index.js<commit_after>import React from 'react';
import D from 'react-dom';

require('./styles/base.scss');

import About from './components/about';
import Fadder from './components/fadder';
import Join from './components/join';

const App = () => {
  return (

      <About />
      <Fadder />
      <Join />

  );
};

D.render(
  <App />,
  document.getElementById('app')
);
<|endoftext|>