<commit_before>// VVVV.js -- Visual Web Client Programming
// (c) 2011 Matthias Zauner
// VVVV.js is freely distributable under the MIT license.
// Additional authors of sub components are mentioned at the specific code locations.

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: RGB (Color Join)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.RGBJoin = function(id, graph) {
  this.constructor(id, "RGB (Color Join)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: []
  };

  var redPin = this.addInputPin("Red", [1.0], this);
  var greenPin = this.addInputPin("Green", [1.0], this);
  var bluePin = this.addInputPin("Blue", [1.0], this);
  var alphaPin = this.addInputPin("Alpha", [1.0], this);

  var outPin = this.addOutputPin("Output", ["1.0,1.0,1.0,1.0"], this);

  this.evaluate = function() {
    if (redPin.pinIsChanged() || greenPin.pinIsChanged || bluePin.pinIsChanged() || alphaPin.pinIsChanged()) {
      var maxSize = this.getMaxInputSliceCount();

      for (var i=0; i<maxSize; i++) {
        var r = redPin.getValue(i) || 0.0;
        var g = greenPin.getValue(i) || 0.0;
        var b = bluePin.getValue(i) || 0.0;
        var a = alphaPin.getValue(i) || 0.0;

        outPin.setValue(i, r+","+g+","+b+","+a);
      }
      outPin.setSliceCount(maxSize);

    }

  }

}
VVVV.Nodes.RGBJoin.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: IOBox (Color)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'VVVV Group'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.IOBoxColor = function(id, graph) {
  this.constructor(id, "IOBox (Color)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;

  // input pins
  var colorinputIn = this.addInputPin('Color Input', ['0.0, 1.0, 0.0, 1.0'], this);

  // output pins
  var coloroutputOut = this.addOutputPin('Color Output', ['0.0, 1.0, 0.0, 1.0'], this);

  // invisible pins
  var rowsIn = this.addInvisiblePin('Rows', [0.0], this);

  this.evaluate = function() {

    var maxSize = this.getMaxInputSliceCount();

    for (var i=0; i<maxSize; i++) {
      coloroutputOut.setValue(i, colorinputIn.getValue(i));
    }

    // you also might want to do stuff like this:
    coloroutputOut.setSliceCount(maxSize);
  }

}
VVVV.Nodes.IOBoxColor.prototype = new VVVV.Core.Node();
<commit_msg>adds SetAlpha (Color)<commit_after>// VVVV.js -- Visual Web Client Programming
// (c) 2011 Matthias Zauner
// VVVV.js is freely distributable under the MIT license.
// Additional authors of sub components are mentioned at the specific code locations.

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: RGB (Color Join)
 Author(s): Matthias Zauner
 Original Node Author(s): VVVV Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.RGBJoin = function(id, graph) {
  this.constructor(id, "RGB (Color Join)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: []
  };

  var redPin = this.addInputPin("Red", [1.0], this);
  var greenPin = this.addInputPin("Green", [1.0], this);
  var bluePin = this.addInputPin("Blue", [1.0], this);
  var alphaPin = this.addInputPin("Alpha", [1.0], this);

  var outPin = this.addOutputPin("Output", ["1.0,1.0,1.0,1.0"], this);

  this.evaluate = function() {
    if (redPin.pinIsChanged() || greenPin.pinIsChanged || bluePin.pinIsChanged() || alphaPin.pinIsChanged()) {
      var maxSize = this.getMaxInputSliceCount();

      for (var i=0; i<maxSize; i++) {
        var r = redPin.getValue(i) || 0.0;
        var g = greenPin.getValue(i) || 0.0;
        var b = bluePin.getValue(i) || 0.0;
        var a = alphaPin.getValue(i) || 0.0;

        outPin.setValue(i, r+","+g+","+b+","+a);
      }
      outPin.setSliceCount(maxSize);

    }

  }

}
VVVV.Nodes.RGBJoin.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: IOBox (Color)
 Author(s): 'Matthias Zauner'
 Original Node Author(s): 'VVVV Group'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.IOBoxColor = function(id, graph) {
  this.constructor(id, "IOBox (Color)", graph);

  this.meta = {
    authors: ['Matthias Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;

  // input pins
  var colorinputIn = this.addInputPin('Color Input', ['0.0, 1.0, 0.0, 1.0'], this);

  // output pins
  var coloroutputOut = this.addOutputPin('Color Output', ['0.0, 1.0, 0.0, 1.0'], this);

  // invisible pins
  var rowsIn = this.addInvisiblePin('Rows', [0.0], this);

  this.evaluate = function() {

    var maxSize = this.getMaxInputSliceCount();

    for (var i=0; i<maxSize; i++) {
      coloroutputOut.setValue(i, colorinputIn.getValue(i));
    }

    // you also might want to do stuff like this:
    coloroutputOut.setSliceCount(maxSize);
  }

}
VVVV.Nodes.IOBoxColor.prototype = new VVVV.Core.Node();

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 NODE: SetAlpha (Color)
 Author(s): 'Zauner'
 Original Node Author(s): 'VVVV Group'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

VVVV.Nodes.SetAlphaColor = function(id, graph) {
  this.constructor(id, "SetAlpha (Color)", graph);

  this.meta = {
    authors: ['Zauner'],
    original_authors: ['VVVV Group'],
    credits: [],
    compatibility_issues: []
  };

  this.auto_evaluate = false;

  // input pins
  var inputIn = this.addInputPin('Input', ['0.0, 0.0, 0.0, 0.0'], this);
  var alphaIn = this.addInputPin('Alpha', [1.0], this);

  // output pins
  var outputOut = this.addOutputPin('Output', ['0.0, 0.0, 0.0, 1.0'], this);

  this.evaluate = function() {

    var maxSize = this.getMaxInputSliceCount();

    for (var i=0; i<maxSize; i++) {
      var input = inputIn.getValue(i);
      var alpha = alphaIn.getValue(i);

      outputOut.setValue(i, input.replace(/[^, ]+$/, alpha));
    }

    outputOut.setSliceCount(maxSize);
  }

}
VVVV.Nodes.SetAlphaColor.prototype = new VVVV.Core.Node();
<|endoftext|>


<commit_before>exports.defineModel = function(sequelize, DataTypes) {
  return sequelize.define(
    "Diagnostic", {
      measured_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        validate: {
          isDate: true
        }
      },
      cpu_percent: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 100
        }
      },
      cpu_clock: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 800
        }
      },
      battery_level: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 100
        }
      },
      battery_temperature: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: -20,
          max: 99
        }
      },
      network_search_time: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 300
        }
      },
    },{
      // column naming customization
    });
};<commit_msg>adding luminosity to model<commit_after>exports.defineModel = function(sequelize, DataTypes) {
  return sequelize.define(
    "Diagnostic", {
      measured_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        validate: {
          isDate: true
        }
      },
      cpu_percent: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 100
        }
      },
      cpu_clock: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 800
        }
      },
      battery_level: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 100
        }
      },
      battery_temperature: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: -20,
          max: 99
        }
      },
      network_search_time: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 300
        }
      },
      internal_luminosity: {
        type: DataTypes.INTEGER,
        validate: {
          isInt: true,
          min: 0,
          max: 65536
        }
      },
    },{
      // column naming customization
    });
};<|endoftext|>


<commit_before>var express = require('express')
var mongoose = require('mongoose')
var bodyParser = require('body-parser')
var morgan = require('morgan')

/* models */
require('./app/models/user')
mongoose.connect('mongodb://localhost:27017/mean-machine')

/* routes */
var apiRoute = require('./app/routes/api')

/* init app */
var app = express()

/* logging */
app.use(morgan('dev'))

/* access data from POSTs */
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

/* register routes */
app.use('/api', apiRoute)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})

/* error handling */

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500)
    res.json({
      message: err.message,
      error: err
    })
  })
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500)
  res.json({
    message: err.message,
    error: {}
  })
})

/* start server */
var port = process.env.PORT || 8080
app.listen(port)
<commit_msg>add CORS handling<commit_after>var express = require('express')
var mongoose = require('mongoose')
var bodyParser = require('body-parser')
var morgan = require('morgan')

/* models */
require('./app/models/user')
mongoose.connect('mongodb://localhost:27017/mean-machine')

/* routes */
var apiRoute = require('./app/routes/api')

/* init app */
var app = express()

/* logging */
app.use(morgan('dev'))

/* access data from POSTs */
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

/* handle CORS */
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST')
  res.setHeader('Access-Control-Allow-Headers',
                'X-Requested-With,content-type Authorization')
  next()
})

/* register routes */
app.use('/api', apiRoute)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found')
  err.status = 404
  next(err)
})

/* error handling */

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500)
    res.json({
      message: err.message,
      error: err
    })
  })
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500)
  res.json({
    message: err.message,
    error: {}
  })
})

/* start server */
var port = process.env.PORT || 8080
app.listen(port)
<|endoftext|>


<commit_before>/**
 * Author: Jeff Whelpley
 * Date: 1/26/14
 *
 * This module contain the primary server container code for both the API
 * and the web server.
 */
module.exports = function (Q, _, Hapi, pancakes, log, config, chainPromises) {

    // this contains the list of middleware (in order) for each container
    var mwConfig = {
        api:        ['mwErrorHandling', 'mwServiceInit', 'mwSecurity', 'mwCaller', 'mwApiRoutes'],
        webserver:  ['mwErrorHandling', 'mwServiceInit', 'mwSecurity', 'mwCaller',
                        'mwTasks', 'mwAppContext', 'mwWebRoutes', 'mwTracking']
    };

    /**
     * Get a Hapi server
     */
    function getServer(container) {
        var server = new Hapi.Server();
        server.connection({ port: process.env.PORT || config[container].port });
        return server;
    }

    /**
     * Start the server
     * @param ctx
     */
    function startServer(ctx) {
        var deferred = Q.defer();
        ctx.server.start(function () { deferred.resolve(ctx); });
        return deferred.promise;
    }

    /**
     * Initialize the server and middleware and then start the server
     */
    function init(container) {
        var ctx = {
            container:  container,
            server:     getServer(container)
        };
        var calls = mwConfig[container].map(function (name) {
            var mw = pancakes.cook(name);
            return mw.init;
        });

        // after all the middleware is done, start the server
        calls.push(startServer);

        // execute all the calls
        return chainPromises(calls, ctx);
    }

    return {
        getServer: getServer,
        startServer: startServer,
        init: init
    };
};

<commit_msg>use config port first since PORT env variable is set to 80 by AWS<commit_after>/**
 * Author: Jeff Whelpley
 * Date: 1/26/14
 *
 * This module contain the primary server container code for both the API
 * and the web server.
 */
module.exports = function (Q, _, Hapi, pancakes, log, config, chainPromises) {

    // this contains the list of middleware (in order) for each container
    var mwConfig = {
        api:        ['mwErrorHandling', 'mwServiceInit', 'mwSecurity', 'mwCaller', 'mwApiRoutes'],
        webserver:  ['mwErrorHandling', 'mwServiceInit', 'mwSecurity', 'mwCaller',
                        'mwTasks', 'mwAppContext', 'mwWebRoutes', 'mwTracking']
    };

    /**
     * Get a Hapi server
     */
    function getServer(container) {
        var server = new Hapi.Server();
        server.connection({ port: config[container].port || process.env.PORT });
        return server;
    }

    /**
     * Start the server
     * @param ctx
     */
    function startServer(ctx) {
        var deferred = Q.defer();
        ctx.server.start(function () { deferred.resolve(ctx); });
        return deferred.promise;
    }

    /**
     * Initialize the server and middleware and then start the server
     */
    function init(container) {
        var ctx = {
            container:  container,
            server:     getServer(container)
        };
        var calls = mwConfig[container].map(function (name) {
            var mw = pancakes.cook(name);
            return mw.init;
        });

        // after all the middleware is done, start the server
        calls.push(startServer);

        // execute all the calls
        return chainPromises(calls, ctx);
    }

    return {
        getServer: getServer,
        startServer: startServer,
        init: init
    };
};

<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var pug = require('pug');
var bodyParser = require('body-parser');

var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);

app.set('views', './public');
app.set('view engine', 'pug');

mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});
<commit_msg>modify for deployment on heroku<commit_after>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var pug = require('pug');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');

var app = express();

app.use(favicon(__dirname + '/public/img/favicon.ico'));

require('dotenv').load();
require('./app/config/passport')(passport);

app.set('views', './public');
app.set('view engine', 'pug');

mongoose.connect(process.env.MONGO_URI);
mongoose.Promise = global.Promise;

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});
<|endoftext|>


<commit_before>var domify = require('domify');
var dom = require('ampersand-dom');
var matches = require('matches-selector');

//Replaceable with anything with label, message-container, message-text data-hooks and a <select>
var defaultTemplate = [
    '',
        '',
        '<select></select>',
        '',
            '

',
        '',
    ''
].join('\n');

/* opts:
 *  - name:       name of the field
 *  - parent:     parent form reference
 *  - options:    array/collection of options to render into the select box
 *  - [unselectedText]: text to display if unselected
 *  - [value]:    initial value for the field
 *  - [el]:       dom node to use for the view
 *  - [required]: is field required
 *
 *  - [validClass]: class to apply to root element if valid
 *  - [invalidClass]: class to apply to root element if invalid
 *  - [requiredMessage]: message to display if invalid and required
 *
 *  Additional opts, if options is a collection:
 *  - [idAttribute]: model attribute to use as the id for the option node
 *  - [textAttribute]: model attribute to use as the text of the option node in the select box
 *  - [disabledAttribute]: model attribute to disable the option node
 *  - [yieldModel]: (defaults true) if options is a collection, yields the full model rather than just it's id to .value
 */

function SelectView (opts) {
    opts = opts || {};

    if (typeof opts.name !== 'string') throw new Error('SelectView requires a name property.');
    this.name = opts.name;

    if (!Array.isArray(opts.options) && !opts.options.isCollection) {
        throw new Error('SelectView requires select options.');
    }
    this.options = opts.options;

    if (this.options.isCollection) {
        this.idAttribute = opts.idAttribute || this.options.mainIndex || 'id';
        this.textAttribute = opts.textAttribute || 'text';
        this.disabledAttribute = opts.disabledAttribute || 'disabled';
    }

    this.el = opts.el;
    this.value = null;
    this.label = opts.label || this.name;
    this.parent = opts.parent;
    this.template = opts.template || defaultTemplate;
    this.unselectedText = opts.unselectedText;
    this.yieldModel = (opts.yieldModel === false) ? false : true;

    this.required = opts.required || false;
    this.validClass = opts.validClass || 'input-valid';
    this.invalidClass = opts.invalidClass || 'input-invalid';
    this.requiredMessage = opts.requiredMessage || 'Selection required';

    this.onChange = this.onChange.bind(this);

    this.render();

    this.setValue(opts.value);
}

SelectView.prototype.render = function () {
    if (this.rendered) return;

    if (!this.el) this.el = domify(this.template);

    var label = this.el.querySelector('[data-hook~=label]');
    if (label) {
        label.textContent = this.label;
    }

    this.select = this.el.querySelector('select');
    if (matches(this.el, 'select')) this.select = this.el;

    this.bindDOMEvents();
    this.renderOptions();
    this.updateSelectedOption();

    if (this.options.isCollection) {
        this.options.on('add', function () {
            this.renderOptions();
            this.updateSelectedOption();
        }.bind(this));
    }

    this.rendered = true;
};

SelectView.prototype.onChange = function () {
    var value = this.select.options[this.select.selectedIndex].value;

    if (this.options.isCollection && this.yieldModel) {
        value = this.findModelForId(value);
    }

    this.setValue(value);
};

SelectView.prototype.findModelForId = function (id) {
    return this.options.filter(function (model) {
        if (!model[this.idAttribute]) return false;

        //intentionally coerce for '1' == 1
        return model[this.idAttribute] == id;
    }.bind(this))[0];
};

SelectView.prototype.bindDOMEvents = function () {
    this.el.addEventListener('change', this.onChange, false);
};

SelectView.prototype.renderOptions = function () {
    if (!this.select) return;

    this.select.innerHTML = '';
    if (this.unselectedText) {
        this.select.appendChild(
            createOption(null, this.unselectedText)
        );
    }

    this.options.forEach(function (option) {
        this.select.appendChild(
            createOption(this.getOptionValue(option), this.getOptionText(option), this.getOptionDisabled(option))
        );
    }.bind(this));
};

SelectView.prototype.updateSelectedOption = function () {
    var lookupValue = this.value;

    if (!this.select) return;

    if (!lookupValue) {
        this.select.selectedIndex = 0;
        return;
    }

    //Pull out the id if it's a model
    if (this.options.isCollection && this.yieldModel) {
        lookupValue = lookupValue && lookupValue[this.idAttribute];
    }

    if (lookupValue) {
        for (var i = this.select.options.length; i--; i) {
            if (this.select.options[i].value === lookupValue.toString()) {
                this.select.selectedIndex = i;
                return;
            }
        }
    }

    //If failed to match any
    this.select.selectedIndex = 0;
};

SelectView.prototype.remove = function () {
    if (this.el) this.el.parentNode.removeChild(this.el);
    this.el.removeEventListener('change', this.onChange, false);
};

SelectView.prototype.setValue = function (value) {
    if (value === this.value) return;

    //Coerce and find the right value based on yieldModel
    if (this.options.isCollection) {
        var model;

        if (this.options.indexOf(value) === -1) {
            model = this.findModelForId(value);
        } else {
            model = value;
        }

        if (this.yieldModel) {
            value = model;
        } else {
            if (model) {
                value = model[this.idAttribute];
            } else {
                value = void 0;
            }
        }
    }

    this.value = value;
    this.validate();
    this.updateSelectedOption();
    if (this.parent) this.parent.update(this);
};

SelectView.prototype.validate = function () {
    this.valid = this.options.some(function (element) {

        //If it's a collection, ensure it's in the collection
        if (this.options.isCollection) {
            if (this.yieldModel) {
                return this.options.indexOf(this.value) > -1;
            } else {
                return !!this.findModelForId(this.value);
            }
        }

        //[ ['foo', 'Foo Text'], ['bar', 'Bar Text'] ]
        if (Array.isArray(element) && element.length === 2) {
            return element[0] === this.value;
        }

        //[ 'foo', 'bar', 'baz' ]
        return element === this.value;
    }.bind(this));

    if (!this.valid && this.required) {
        this.setMessage(this.requiredMessage);
    } else {
        this.setMessage();
    }

    return this.valid;
};

SelectView.prototype.getOptionValue = function (option) {
    if (Array.isArray(option)) return option[0];

    if (this.options.isCollection) {
        if (this.idAttribute && option[this.idAttribute]) {
            return option[this.idAttribute];
        }
    }

    return option;
};

SelectView.prototype.getOptionDisabled = function (option) {
    if (Array.isArray(option)) return;

    if (this.options.isCollection) {
        if (this.disabledAttribute && option[this.disabledAttribute]) {
            return option[this.disabledAttribute];
        } else {
            return false;
        }
    }

    return option;
};

SelectView.prototype.setMessage = function (message) {
    var mContainer = this.el.querySelector('[data-hook~=message-container]');
    var mText = this.el.querySelector('[data-hook~=message-text]');

    if (!mContainer || !mText) return;

    if (message) {
        dom.show(mContainer);
        mText.textContent = message;
        dom.addClass(this.el, this.invalidClass);
        dom.removeClass(this.el, this.validClass);
    } else {
        dom.hide(mContainer);
        mText.textContent = '';
        dom.addClass(this.el, this.validClass);
        dom.removeClass(this.el, this.invalidClass);
    }
};

SelectView.prototype.getOptionText = function (option) {
    if (Array.isArray(option)) return option[1];

    if (this.options.isCollection) {
        if (this.textAttribute && option[this.textAttribute]) {
            return option[this.textAttribute];
        }
    }

    return option;
};

function createOption (value, text, disabled) {
    var node = document.createElement('option');

    //Set to empty-string if undefined or null, but not if 0, false, etc
    if (value === null || value === undefined) { value = ''; }

    //console.log(disabled);

    if(disabled) {
        node.disabled = true;
    }

    node.textContent = text;
    node.value = value;

    return node;
}

module.exports = SelectView;
<commit_msg>Set name on Select element, return valid if value is empty and required set to false<commit_after>var domify = require('domify');
var dom = require('ampersand-dom');
var matches = require('matches-selector');

//Replaceable with anything with label, message-container, message-text data-hooks and a <select>
var defaultTemplate = [
    '',
        '',
        '<select></select>',
        '',
            '

',
        '',
    ''
].join('\n');

/* opts:
 *  - name:       name of the field
 *  - parent:     parent form reference
 *  - options:    array/collection of options to render into the select box
 *  - [unselectedText]: text to display if unselected
 *  - [value]:    initial value for the field
 *  - [el]:       dom node to use for the view
 *  - [required]: is field required
 *
 *  - [validClass]: class to apply to root element if valid
 *  - [invalidClass]: class to apply to root element if invalid
 *  - [requiredMessage]: message to display if invalid and required
 *
 *  Additional opts, if options is a collection:
 *  - [idAttribute]: model attribute to use as the id for the option node
 *  - [textAttribute]: model attribute to use as the text of the option node in the select box
 *  - [disabledAttribute]: model attribute to disable the option node
 *  - [yieldModel]: (defaults true) if options is a collection, yields the full model rather than just it's id to .value
 */

function SelectView (opts) {
    opts = opts || {};

    if (typeof opts.name !== 'string') throw new Error('SelectView requires a name property.');
    this.name = opts.name;

    if (!Array.isArray(opts.options) && !opts.options.isCollection) {
        throw new Error('SelectView requires select options.');
    }
    this.options = opts.options;

    if (this.options.isCollection) {
        this.idAttribute = opts.idAttribute || this.options.mainIndex || 'id';
        this.textAttribute = opts.textAttribute || 'text';
        this.disabledAttribute = opts.disabledAttribute || 'disabled';
    }

    this.el = opts.el;
    this.value = null;
    this.label = opts.label || this.name;
    this.parent = opts.parent;
    this.template = opts.template || defaultTemplate;
    this.unselectedText = opts.unselectedText;
    this.yieldModel = (opts.yieldModel === false) ? false : true;

    this.required = opts.required || false;
    this.validClass = opts.validClass || 'input-valid';
    this.invalidClass = opts.invalidClass || 'input-invalid';
    this.requiredMessage = opts.requiredMessage || 'Selection required';

    this.onChange = this.onChange.bind(this);

    this.render();

    this.setValue(opts.value);
}

SelectView.prototype.render = function () {
    if (this.rendered) return;

    if (!this.el) this.el = domify(this.template);

    var label = this.el.querySelector('[data-hook~=label]');
    if (label) {
        label.textContent = this.label;
    }

    this.select = this.el.querySelector('select');
    this.select.name = this.name;
    if (matches(this.el, 'select')) this.select = this.el;

    this.bindDOMEvents();
    this.renderOptions();
    this.updateSelectedOption();

    if (this.options.isCollection) {
        this.options.on('add', function () {
            this.renderOptions();
            this.updateSelectedOption();
        }.bind(this));
    }

    this.rendered = true;
};

SelectView.prototype.onChange = function () {
    var value = this.select.options[this.select.selectedIndex].value;

    if (this.options.isCollection && this.yieldModel) {
        value = this.findModelForId(value);
    }

    this.setValue(value);
};

SelectView.prototype.findModelForId = function (id) {
    return this.options.filter(function (model) {
        if (!model[this.idAttribute]) return false;

        //intentionally coerce for '1' == 1
        return model[this.idAttribute] == id;
    }.bind(this))[0];
};

SelectView.prototype.bindDOMEvents = function () {
    this.el.addEventListener('change', this.onChange, false);
};

SelectView.prototype.renderOptions = function () {
    if (!this.select) return;

    this.select.innerHTML = '';
    if (this.unselectedText) {
        this.select.appendChild(
            createOption(null, this.unselectedText)
        );
    }

    this.options.forEach(function (option) {
        this.select.appendChild(
            createOption(this.getOptionValue(option), this.getOptionText(option), this.getOptionDisabled(option))
        );
    }.bind(this));
};

SelectView.prototype.updateSelectedOption = function () {
    var lookupValue = this.value;

    if (!this.select) return;

    if (!lookupValue) {
        this.select.selectedIndex = 0;
        return;
    }

    //Pull out the id if it's a model
    if (this.options.isCollection && this.yieldModel) {
        lookupValue = lookupValue && lookupValue[this.idAttribute];
    }

    if (lookupValue) {
        for (var i = this.select.options.length; i--; i) {
            if (this.select.options[i].value === lookupValue.toString()) {
                this.select.selectedIndex = i;
                return;
            }
        }
    }

    //If failed to match any
    this.select.selectedIndex = 0;
};

SelectView.prototype.remove = function () {
    if (this.el) this.el.parentNode.removeChild(this.el);
    this.el.removeEventListener('change', this.onChange, false);
};

SelectView.prototype.setValue = function (value) {
    if (value === this.value) return;

    //Coerce and find the right value based on yieldModel
    if (this.options.isCollection) {
        var model;

        if (this.options.indexOf(value) === -1) {
            model = this.findModelForId(value);
        } else {
            model = value;
        }

        if (this.yieldModel) {
            value = model;
        } else {
            if (model) {
                value = model[this.idAttribute];
            } else {
                value = void 0;
            }
        }
    }

    this.value = value;
    this.validate();
    this.updateSelectedOption();
    if (this.parent) this.parent.update(this);
};

SelectView.prototype.validate = function () {
    if(!this.value && !this.required) {
        this.valid = true;
    } else {
        this.valid = this.options.some(function (element) {

            //If it's a collection, ensure it's in the collection
            if (this.options.isCollection) {
                if (this.yieldModel) {
                    return this.options.indexOf(this.value) > -1;
                } else {
                    return !!this.findModelForId(this.value);
                }
            }

            //[ ['foo', 'Foo Text'], ['bar', 'Bar Text'] ]
            if (Array.isArray(element) && element.length === 2) {
                return element[0] === this.value;
            }

            //[ 'foo', 'bar', 'baz' ]
            return element === this.value;
        }.bind(this));
    }

    if (!this.valid && this.required) {
        this.setMessage(this.requiredMessage);
    } else {
        this.setMessage();
    }

    return this.valid;
};

SelectView.prototype.getOptionValue = function (option) {
    if (Array.isArray(option)) return option[0];

    if (this.options.isCollection) {
        if (this.idAttribute && option[this.idAttribute]) {
            return option[this.idAttribute];
        }
    }

    return option;
};

SelectView.prototype.getOptionDisabled = function (option) {
    if (Array.isArray(option)) return;

    if (this.options.isCollection) {
        if (this.disabledAttribute && option[this.disabledAttribute]) {
            return option[this.disabledAttribute];
        } else {
            return false;
        }
    }

    return option;
};

SelectView.prototype.setMessage = function (message) {
    var mContainer = this.el.querySelector('[data-hook~=message-container]');
    var mText = this.el.querySelector('[data-hook~=message-text]');

    if (!mContainer || !mText) return;

    if (message) {
        dom.show(mContainer);
        mText.textContent = message;
        dom.addClass(this.el, this.invalidClass);
        dom.removeClass(this.el, this.validClass);
    } else {
        dom.hide(mContainer);
        mText.textContent = '';
        dom.addClass(this.el, this.validClass);
        dom.removeClass(this.el, this.invalidClass);
    }
};

SelectView.prototype.getOptionText = function (option) {
    if (Array.isArray(option)) return option[1];

    if (this.options.isCollection) {
        if (this.textAttribute && option[this.textAttribute]) {
            return option[this.textAttribute];
        }
    }

    return option;
};

function createOption (value, text, disabled) {
    var node = document.createElement('option');

    //Set to empty-string if undefined or null, but not if 0, false, etc
    if (value === null || value === undefined) { value = ''; }

    if(disabled) {
        node.disabled = true;
    }

    node.textContent = text;
    node.value = value;

    return node;
}

module.exports = SelectView;
<|endoftext|>


<commit_before>var Config = require('getconfig');
var Crypto = require('crypto');
var Hapi = require('hapi');
var Jade = require('jade');
var Markdown = require('./lib/markdown');
var Path = require('path');

var server = new Hapi.Server();

Jade.filters.markdown = Markdown.parseSync;

server.connection({
    host: Config.host,
    port: Config.port
});

server.views({
    engines: {
        jade: Jade
    },
    path: Path.join(__dirname, 'templates'),
    isCached: Config.getconfig.env === 'production'
});

server.ext('onPreResponse', function (request, reply) {

    if (!request.response.isBoom) {
        return reply.continue();
    }

    reply.view('error', request.response).code(request.response.output.statusCode);
});

server.method(require('./lib/npm').methods);
server.method(require('./lib/github').methods);
server.method(require('./lib/markdown').methods);

server.route(require('./lib/routes').routes);

var start = function (err) {

    if (err) {
        throw err;
    }

    server.start(function () {

        console.log('hapijs.com running at: ' + server.info.uri);
    });
};

if (Config.getconfig.env === 'dev') {
    server.register(require('building-static-server'), start);
}
else {
    start();
}
<commit_msg>load catbox-redis in production<commit_after>var Config = require('getconfig');
var Crypto = require('crypto');
var Hapi = require('hapi');
var Jade = require('jade');
var Markdown = require('./lib/markdown');
var Path = require('path');

var serverConfig = {};
if (Config.getconfig.env === 'production') {
    serverConfig.cache = require('catbox-redis');
}
var server = new Hapi.Server(serverConfig);

Jade.filters.markdown = Markdown.parseSync;

server.connection({
    host: Config.host,
    port: Config.port
});

server.views({
    engines: {
        jade: Jade
    },
    path: Path.join(__dirname, 'templates'),
    isCached: Config.getconfig.env === 'production'
});

server.ext('onPreResponse', function (request, reply) {

    if (!request.response.isBoom) {
        return reply.continue();
    }

    reply.view('error', request.response).code(request.response.output.statusCode);
});

server.method(require('./lib/npm').methods);
server.method(require('./lib/github').methods);
server.method(require('./lib/markdown').methods);

server.route(require('./lib/routes').routes);

var start = function (err) {

    if (err) {
        throw err;
    }

    server.start(function () {

        console.log('hapijs.com running at: ' + server.info.uri);
    });
};

if (Config.getconfig.env === 'dev') {
    server.register(require('building-static-server'), start);
}
else {
    start();
}
<|endoftext|>


<commit_before>var express =       require('express')
    , http =        require('http')
    , passport =    require('passport')
    , path =        require('path')
    , User =        require('./server/models/User.js');

var app = module.exports = express();

app.set('views', __dirname + '/client/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'))
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.cookieSession(
    {
        secret: process.env.COOKIE_SECRET || "Superdupersecret"
    }));

app.configure('development', 'production', function() {
    app.use(express.csrf());
});

app.use(passport.initialize());
app.use(passport.session());

passport.use(User.localStrategy);
passport.use(User.twitterStrategy());  // Comment out this line if you don't want to enable login via Twitter
passport.use(User.facebookStrategy()); // Comment out this line if you don't want to enable login via Facebook
passport.use(User.googleStrategy());   // Comment out this line if you don't want to enable login via Google
passport.use(User.linkedInStrategy()); // Comment out this line if you don't want to enable login via LinkedIn

passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);

require('./server/routes.js')(app);

app.set('port', process.env.PORT || 8000);
http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});<commit_msg>Fixed bug where xsrf-token wasn't set properly server-side<commit_after>var express =       require('express')
    , http =        require('http')
    , passport =    require('passport')
    , path =        require('path')
    , User =        require('./server/models/User.js');

var app = module.exports = express();

app.set('views', __dirname + '/client/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'))
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'client')));
app.use(express.cookieParser());
app.use(express.cookieSession(
    {
        secret: process.env.COOKIE_SECRET || "Superdupersecret"
    }));

app.configure('development', 'production', function() {
    app.use(express.csrf());
});

app.use(function(req, res, next) {
    res.cookie('XSRF-TOKEN', req.csrfToken());
    next();
});

app.use(passport.initialize());
app.use(passport.session());

passport.use(User.localStrategy);
passport.use(User.twitterStrategy());  // Comment out this line if you don't want to enable login via Twitter
passport.use(User.facebookStrategy()); // Comment out this line if you don't want to enable login via Facebook
passport.use(User.googleStrategy());   // Comment out this line if you don't want to enable login via Google
passport.use(User.linkedInStrategy()); // Comment out this line if you don't want to enable login via LinkedIn

passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);

require('./server/routes.js')(app);

app.set('port', process.env.PORT || 8000);
http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});<|endoftext|>


<commit_before>var express = require('express');
var childProcess = require('child_process');
var middleware = require('./config/initializers/middleware.js');
var router = require('./config/routes.js');
var host = process.env.HOST;
var port = process.env.PORT || 4000;
var app = express();

middleware.configure(app);
router.route(app);

host ? app.listen(port, host) : app.listen(port);

var paymentApi = childProcess.spawn("node", ["ripple-simple/app.js"]);

paymentApi.stdout.on('data', function(data) {
  console.log(data.toString());
});

setTimeout(function(){
  var outgoingPaymentsMonitor = childProcess.spawn("node", ["workers/outgoing_ripple_payments.js"]);
  outgoingPaymentsMonitor.stdout.on('data', function(data) {
    console.log(data.toString());
  });

  outgoingPaymentsMonitor.stderr.on('data', function(data) {
    console.log(data.toString());
  });
},10000);

console.log('Serving HTTP on', (host || 'localhost')+":"+port);

<commit_msg>[CHORE] Log payment api stderr to parent stdout.<commit_after>var express = require('express');
var childProcess = require('child_process');
var middleware = require('./config/initializers/middleware.js');
var router = require('./config/routes.js');
var host = process.env.HOST;
var port = process.env.PORT || 4000;
var app = express();

middleware.configure(app);
router.route(app);

host ? app.listen(port, host) : app.listen(port);

var paymentApi = childProcess.spawn("node", ["ripple-simple/app.js"]);

paymentApi.stdout.on('data', function(data) {
  console.log(data.toString());
});
paymentApi.stderr.on('data', function(data) {
  console.log(data.toString());
});

setTimeout(function(){
  var outgoingPaymentsMonitor = childProcess.spawn("node", ["workers/outgoing_ripple_payments.js"]);
  outgoingPaymentsMonitor.stdout.on('data', function(data) {
    console.log(data.toString());
  });

  outgoingPaymentsMonitor.stderr.on('data', function(data) {
    console.log(data.toString());
  });
},10000);

console.log('Serving HTTP on', (host || 'localhost')+":"+port);

<|endoftext|>


<commit_before>var keystone = require('keystone'),
Types = keystone.Field.Types;

// Create model. Additional options allow menu name to be used what auto-generating URLs
var Placement = new keystone.List('Placement', {
    track: true,
    autokey: { path: 'key', from: 'slug', unique: true },
    map: { name: 'slug' }
});

// Create fields
Placement.add('Placement', {
    placementDate: { type: Types.Text, label: 'placement date', note: 'mm/dd/yyyy', initial: true },
    child: { type: Types.Relationship, label: 'child', ref: 'Child', many: true, required: true, index: true, initial: true },
    childPlacedWithMAREFamily: { type: Types.Boolean, label: 'child placed with MARE family', initial: true },
    prospectiveParentOrFamily: { type: Types.Relationship, label: 'prospective parent or family', ref: 'Prospective Parent or Family', dependsOn: { childPlacedWithMAREFamily: true }, required: true, index: true, initial: true },
    familyAgency: { type: Types.Relationship, label: 'family\'s agency', ref: 'Agency', dependsOn: { childPlacedWithMAREFamily: true }, required: true, initial: true },
    constellation: { type: Types.Relationship, label: 'constellation', ref: 'Family Constellation', dependsOn: { childPlacedWithMAREFamily: false }, index: true, initial: true },
    race: { type: Types.Relationship, label: 'race', ref: 'Race', dependsOn: { childPlacedWithMAREFamily: false }, many: true, index: true, initial: true },
    source: { type: Types.Relationship, label: 'sources', ref: 'Source', index: true, initial: true },
    notes: { type: Types.Textarea, label: 'notes', initial: true }

}, 'Family', {

    family: {
        name: { type: Types.Text, label: 'family name', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },

        address: {
            street1: { type: Types.Text, label: 'address Line 1', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            street2: { type: Types.Text, label: 'address Line 2', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            city: { type: Types.Text, label: 'city', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            state: { type: Types.Relationship, label: 'state', ref: 'State', dependsOn: { childPlacedWithMAREFamily: true }, index: true, initial: true },
            zipCode: { type: Types.Text, label: 'zip code', dependsOn: { childPlacedWithMAREFamily: true }, index: true, initial: true },
            country: { type: Types.Text, label: 'country', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            region: { type: Types.Relationship, label: 'region', dependsOn: { childPlacedWithMAREFamily: true }, ref: 'Region', initial: true }
        },

        phone: {
            work: { type: Types.Text, label: 'work phone number', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            home: { type: Types.Text, label: 'home phone number', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            cell: { type: Types.Text, label: 'cell phone number', dependsOn: { childPlacedWithMAREFamily: true }, initial: true },
            preferred: { type: Types.Select, label: 'preferred phone', options: 'work, home, cell', dependsOn: { childPlacedWithMAREFamily: true }, initial: true }
        },

        email: { type: Types.Email, label: 'email address', dependsOn: { childPlacedWithMAREFamily: true }, index: true, initial: true },
    }

}, 'Disruption', {
    disruptionDate: { type: Types.Text, label: 'disruption date', note: 'mm/dd/yyyy', initial: true }
});

// Define default columns in the admin interface and register the model
Placement.defaultColumns = 'child, family, constellation';
Placement.register();<commit_msg>Update Placement model to show correct fields depending on whether the child was placed with the MARE system or not.<commit_after>var keystone = require('keystone'),
Types = keystone.Field.Types;

// Create model. Additional options allow menu name to be used what auto-generating URLs
var Placement = new keystone.List('Placement', {
    track: true,
    autokey: { path: 'key', from: 'slug', unique: true },
    map: { name: 'slug' }
});

// Create fields
Placement.add('Placement', {
    placementDate: { type: Types.Text, label: 'placement date', note: 'mm/dd/yyyy', initial: true },
    child: { type: Types.Relationship, label: 'child', ref: 'Child', many: true, required: true, index: true, initial: true },
    childPlacedWithMAREFamily: { type: Types.Boolean, label: 'child placed with MARE family', initial: true },
    prospectiveParentOrFamily: { type: Types.Relationship, label: 'prospective parent or family', ref: 'Prospective Parent or Family', dependsOn: { childPlacedWithMAREFamily: true }, required: true, index: true, initial: true },
    familyAgency: { type: Types.Relationship, label: 'family\'s agency', ref: 'Agency', dependsOn: { childPlacedWithMAREFamily: true }, required: true, initial: true },
    constellation: { type: Types.Relationship, label: 'constellation', ref: 'Family Constellation', dependsOn: { childPlacedWithMAREFamily: false }, index: true, initial: true },
    race: { type: Types.Relationship, label: 'race', ref: 'Race', dependsOn: { childPlacedWithMAREFamily: false }, many: true, index: true, initial: true },
    source: { type: Types.Relationship, label: 'sources', ref: 'Source', index: true, initial: true },
    notes: { type: Types.Textarea, label: 'notes', initial: true }

}, 'Family', {

    family: {
        name: { type: Types.Text, label: 'family name', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },

        address: {
            street1: { type: Types.Text, label: 'address Line 1', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            street2: { type: Types.Text, label: 'address Line 2', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            city: { type: Types.Text, label: 'city', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            state: { type: Types.Relationship, label: 'state', ref: 'State', dependsOn: { childPlacedWithMAREFamily: false }, index: true, initial: true },
            zipCode: { type: Types.Text, label: 'zip code', dependsOn: { childPlacedWithMAREFamily: false }, index: true, initial: true },
            country: { type: Types.Text, label: 'country', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            region: { type: Types.Relationship, label: 'region', dependsOn: { childPlacedWithMAREFamily: false }, ref: 'Region', initial: true }
        },

        phone: {
            work: { type: Types.Text, label: 'work phone number', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            home: { type: Types.Text, label: 'home phone number', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            cell: { type: Types.Text, label: 'cell phone number', dependsOn: { childPlacedWithMAREFamily: false }, initial: true },
            preferred: { type: Types.Select, label: 'preferred phone', options: 'work, home, cell', dependsOn: { childPlacedWithMAREFamily: false }, initial: true }
        },

        email: { type: Types.Email, label: 'email address', dependsOn: { childPlacedWithMAREFamily: false }, index: true, initial: true },
    }

}, 'Disruption', {
    disruptionDate: { type: Types.Text, label: 'disruption date', note: 'mm/dd/yyyy', initial: true }
});

// Define default columns in the admin interface and register the model
Placement.defaultColumns = 'child, family, constellation';
Placement.register();<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.set('port', port)
const request = require('request');

// MIDDLEWARE (transform stream)
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', (req, res) => {
  let apiCall = req.url.slice('/maps/api/'.length)
  let apiReq = `https://maps.googleapis.com/${apiCall}`
  request.get(apiReq, (err, _, body) => {
    res.send(body)
  });
});

app.listen(port, () =>
  console.log(`Listening on port: ${port}`)
)
<commit_msg>fixed?<commit_after>'use strict'

const express = require('express')
const app = express()
const port = process.env.PORT || 3000
app.set('port', port)
const request = require('request');

// MIDDLEWARE (transform stream)
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/maps/api/geocode/json?', (req, res) => {
  let apiCall = req.url.slice('/maps/api/geocode/json?'.length)
  let apiReq = `https://maps.googleapis.com${apiCall}`
  request.get(apiReq, (err, _, body) => {
    res.send(body)
  });
});

app.listen(port, () =>
  console.log(`Listening on port: ${port}`)
)
<|endoftext|>


<commit_before>/*
    This script starts a web server and waits for incoming http requests. Requests should have the form:
    http://myserver:port/VIN[?refresh]

    VIN is your vehicle identification number
        for example WBAXXXXXXXV123456

    ?refresh is an optional parameter.
        If set, fresh data is download from the BMW servers. If left out, a cached copy
        from stored JSON files is returned instead
 */

var http = require("http");
var url = require('url');
var fs = require('fs');

var vehicle = require('./vehicle.js');

http.createServer(function (req, res)
{
    var requestUrl = url.parse(req.url);
    var path = requestUrl.pathname;
    var search = requestUrl.search;

    var vin = path.substring(1);

    if(search === '?refresh')
    {
        console.log("Requesting new data from BMW ConnectedDrive API server");

        vehicle.writeAllVehiclesData(function() {}, function(err)
        {
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Request Error: ' + err);
        });
    }
    else
    {
        console.log("Returning cached version of data for VIN " + vin);
    }

    fs.readFile('result_' + vin + '.json', 'utf8', function(_err, _data)
    {
        if(_err)
        {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end("Failed to open file " + vin + ": " + _err);
        }
        else
        {
            res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
            res.end(_data);
        }
    })

}).listen(8777);
<commit_msg>mode server port to a variable<commit_after>/*
    This script starts a web server and waits for incoming http requests. Requests should have the form:
    http://myserver:port/VIN[?refresh]

    VIN is your vehicle identification number
        for example WBAXXXXXXXV123456

    ?refresh is an optional parameter.
        If set, fresh data is download from the BMW servers. If left out, a cached copy
        from stored JSON files is returned instead
 */

var http = require("http");
var url = require('url');
var fs = require('fs');

const g_serverListenPort = 8777;

var vehicle = require('./vehicle.js');

http.createServer(function (req, res)
{
    var requestUrl = url.parse(req.url);
    var path = requestUrl.pathname;
    var search = requestUrl.search;

    var vin = path.substring(1);

    if(search === '?refresh')
    {
        console.log("Requesting new data from BMW ConnectedDrive API server");

        vehicle.writeAllVehiclesData(function() {}, function(err)
        {
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Request Error: ' + err);
        });
    }
    else
    {
        console.log("Returning cached version of data for VIN " + vin);
    }

    fs.readFile('result_' + vin + '.json', 'utf8', function(_err, _data)
    {
        if(_err)
        {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end("Failed to open file " + vin + ": " + _err);
        }
        else
        {
            res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
            res.end(_data);
        }
    })

}).listen(g_serverListenPort);
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 **
 ** - Fennel Card-/CalDAV -
 **
 ** Copyright 2014-16 by
 ** SwordLord - the coding crew - http://www.swordlord.com
 ** and contributing authors
 **
 ** This program is free software; you can redistribute it and/or modify it
 ** under the terms of the GNU General Public License as published by the Free
 ** Software Foundation, either version 3 of the License, or (at your option)
 ** any later version.
 **
 ** This program is distributed in the hope that it will be useful, but WITHOUT
 ** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 ** FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 ** more details.
 **
 ** You should have received a copy of the GNU General Public License along
 ** with this program. If not, see <http://www.gnu.org/licenses/>.
 **
 **-----------------------------------------------------------------------------
 **
 ** Original Authors:
 ** LordEidi@swordlord.com
 ** LordLightningBolt@swordlord.com
 **
 ** $Id:
 **
-----------------------------------------------------------------------------*/
var config = require('./config').config;
var authlib = require('./libs/authentication');
var http = require('http');
var url = require('url');
var log = require('./libs/log').log;
var handler = require('./libs/requesthandler');

var communication = require('./libs/communication');
var httpauth = require('http-auth');

var crossroads = require('crossroads');
crossroads.ignoreState = true;

var basic = httpauth.basic(
    {
        realm: "Fennel"
    }, function (username, password, callback)
    {
        authlib.checkLogin(basic, username, password, callback);
    }
);

/**
 * Called when the URL is not matched against any known/defined pattern
 * @param comm
 * @param path
 */
function onBypass(comm, path)
{
    log.info('URL unknown: ' + path);

    var res = comm.getRes();

    res.writeHead(500);
    res.write(comm.url + " is not known");
    res.end();
}

/**
 * Gets called when the / URL is hit
 * @param comm
 */
function onHitRoot(comm)
{
    log.debug("Called the root. Redirecting to /p/");

    comm.getRes().writeHead(302,
        {
            'Location': '/p/'
            //todo: add other headers here...?
        });
    comm.flushResponse();
}

function onHitWellKnown(comm, params)
{
    log.debug("Called .well-known URL for " + params + ". Redirecting to /p/");

    comm.getRes().writeHead(302,
        {
            'Location': '/p/'
            //todo: add other headers here...?
        });
    comm.flushResponse();
}

function onHitPrincipal(comm, params)
{
    comm.params = params;

    handler.handlePrincipal(comm);
}

function onHitCalendar(comm, username, cal, params)
{
    comm.username = username;
    comm.cal = cal;
    comm.params = params;

    handler.handleCalendar(comm);
}

function onHitCard(comm, username, card, params)
{
    comm.username = username;
    comm.card = card;
    comm.params = params;

    handler.handleCard(comm);
}

crossroads.addRoute('/p/:params*:', onHitPrincipal);
crossroads.addRoute('/cal/:username:/:cal:/:params*:', onHitCalendar);
crossroads.addRoute('/card/:username:/:card:/:params*:', onHitCard);
crossroads.addRoute('/.well-known/:params*:', onHitWellKnown);
crossroads.addRoute('/', onHitRoot);
crossroads.bypassed.add(onBypass);

// Listen on port 8888, IP defaults to 127.0.0.1
var server = http.createServer(basic, function (req, res)
{
    //log.debug("Request started");
	log.debug("Method: " + req.method + ", URL: " + req.url);

	var reqBody = "";

    req.on('data', function (data)
    {
        reqBody += data.toString();
    });

    req.on('end',function()
    {
        var comm = new communication(req, res, reqBody);

        var sUrl = url.parse(req.url).pathname;
        log.info("URL requested: " + sUrl);
        crossroads.parse(sUrl, [comm]);
    });
});

server.listen(config.port);

server.on('error', function (e)
{
    log.debug("Error: " + e);
});

process.on('uncaughtException', function(err)
{
    log.warn('Caught exception: ' + err.message);
    log.debug(err.stack);
});

// Put a friendly message on the terminal
log.info("Server running at http://" + config.ip + ":" + config.port + "/");
<commit_msg>Cleaning up debug output.<commit_after>/*-----------------------------------------------------------------------------
 **
 ** - Fennel Card-/CalDAV -
 **
 ** Copyright 2014-16 by
 ** SwordLord - the coding crew - http://www.swordlord.com
 ** and contributing authors
 **
 ** This program is free software; you can redistribute it and/or modify it
 ** under the terms of the GNU General Public License as published by the Free
 ** Software Foundation, either version 3 of the License, or (at your option)
 ** any later version.
 **
 ** This program is distributed in the hope that it will be useful, but WITHOUT
 ** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 ** FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 ** more details.
 **
 ** You should have received a copy of the GNU General Public License along
 ** with this program. If not, see <http://www.gnu.org/licenses/>.
 **
 **-----------------------------------------------------------------------------
 **
 ** Original Authors:
 ** LordEidi@swordlord.com
 ** LordLightningBolt@swordlord.com
 **
 ** $Id:
 **
-----------------------------------------------------------------------------*/
var config = require('./config').config;
var authlib = require('./libs/authentication');
var http = require('http');
var url = require('url');
var log = require('./libs/log').log;
var handler = require('./libs/requesthandler');

var communication = require('./libs/communication');
var httpauth = require('http-auth');

var crossroads = require('crossroads');
crossroads.ignoreState = true;

var basic = httpauth.basic(
    {
        realm: "Fennel"
    }, function (username, password, callback)
    {
        authlib.checkLogin(basic, username, password, callback);
    }
);

/**
 * Called when the URL is not matched against any known/defined pattern
 * @param comm
 * @param path
 */
function onBypass(comm, path)
{
    log.info('URL unknown: ' + path);

    var res = comm.getRes();

    res.writeHead(500);
    res.write(comm.url + " is not known");
    res.end();
}

/**
 * Gets called when the / URL is hit
 * @param comm
 */
function onHitRoot(comm)
{
    log.debug("Called the root. Redirecting to /p/");

    comm.getRes().writeHead(302,
        {
            'Location': '/p/'
            //todo: add other headers here...?
        });
    comm.flushResponse();
}

function onHitWellKnown(comm, params)
{
    log.debug("Called .well-known URL for " + params + ". Redirecting to /p/");

    comm.getRes().writeHead(302,
        {
            'Location': '/p/'
            //todo: add other headers here...?
        });
    comm.flushResponse();
}

function onHitPrincipal(comm, params)
{
    comm.params = params;

    handler.handlePrincipal(comm);
}

function onHitCalendar(comm, username, cal, params)
{
    comm.username = username;
    comm.cal = cal;
    comm.params = params;

    handler.handleCalendar(comm);
}

function onHitCard(comm, username, card, params)
{
    comm.username = username;
    comm.card = card;
    comm.params = params;

    handler.handleCard(comm);
}

crossroads.addRoute('/p/:params*:', onHitPrincipal);
crossroads.addRoute('/cal/:username:/:cal:/:params*:', onHitCalendar);
crossroads.addRoute('/card/:username:/:card:/:params*:', onHitCard);
crossroads.addRoute('/.well-known/:params*:', onHitWellKnown);
crossroads.addRoute('/', onHitRoot);
crossroads.bypassed.add(onBypass);

// Listen on port 8888, IP defaults to 127.0.0.1
var server = http.createServer(basic, function (req, res)
{
    //log.debug("Request started");
	log.debug("Method: " + req.method + ", URL: " + req.url);

	var reqBody = "";

    req.on('data', function (data)
    {
        reqBody += data.toString();
    });

    req.on('end',function()
    {
        var comm = new communication(req, res, reqBody);

        var sUrl = url.parse(req.url).pathname;
        log.debug("Request body: " + reqBody);
        crossroads.parse(sUrl, [comm]);
    });
});

server.listen(config.port);

server.on('error', function (e)
{
    log.warn('Caught error: ' + e.message);
    log.debug(e.stack);
});

process.on('uncaughtException', function(err)
{
    log.warn('Caught exception: ' + err.message);
    log.debug(err.stack);
});

// Put a friendly message on the terminal
log.info("Server running at http://" + config.ip + ":" + config.port + "/");
<|endoftext|>


<commit_before>/**
 * This is an example of a basic node.js script that performs
 * the Authorization Code oAuth2 flow to authenticate against
 * the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow
 */

var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
const admin = require('firebase-admin');
if (process.env.NODE_ENV === 'development') {
  require('./.secrets/spotify.js');
  require('./.secrets/attune-d8afe-firebase-adminsdk-m5rub-8c85814d02.js'); // this will mutate the process.env object with your secrets.
}

console.log('PRIV KEY', process.env.private_key)

var attune = admin.initializeApp({
  "credential": admin.credential.cert({
  "type": process.env.type,
  "project_id": process.env.project_id,
  "private_key": process.env.private_key,
  "client_email": process.env.client_email,
  "private_key_id": process.env.private_key_id,

  "client_id": process.env.client_id,
  "auth_uri": process.env.auth_uri,
  "token_uri": process.env.token_uri,
  "auth_provider_x509_cert_url": process.env.auth_provider_x509_cert_url,
  "client_x509_cert_ur": process.env.client_x509_cert_url
  })
, "databaseURL": 'https://attune-d8afe.firebaseio.com/'});

var redirect_uri = (process.env.NODE_ENV === 'development' ? 'http://localhost:1337/callback' : 'http://attune-music.herokuapp.com/callback'); // Your cal uri

/**
 * Generates a random string containing numbers and letters
 * @param  {number} length The length of the string
 * @return {string} The generated string
 */
var generateRandomString = function(length) {
  var text = '';
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

var stateKey = 'spotify_auth_state';

var app = express();

app.use(express.static(__dirname + '/public'))
   .use(cookieParser());

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

  var state = generateRandomString(16);
  res.cookie(stateKey, state);

  // your application requests authorization
  var scope = 'user-follow-read user-top-read user-read-recently-played user-read-private user-read-email user-library-read user-read-birthdate';
  res.redirect('https://accounts.spotify.com/authorize?' +
    querystring.stringify({
      response_type: 'code',
      client_id: process.env.spotify_client_id,
      scope: scope,
      redirect_uri: redirect_uri,
      state: state
    }));
});

app.get('/callback', function(req, res) {
  // your application requests refresh and access tokens
  // after checking the state parameter

  var code = req.query.code || null;
  var state = req.query.state || null;
  var storedState = req.cookies ? req.cookies[stateKey] : null;

  if (state === null || state !== storedState) {
    res.redirect('/#' +
      querystring.stringify({
        error: 'State mismatch between request and cookie'
      }));
  } else {
    res.clearCookie(stateKey);
    var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        code: code,
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (new Buffer(process.env.spotify_client_id + ':' + process.env.spotify_client_secret).toString('base64'))
      },
      json: true
    };

    request.post(authOptions, function(error, response, body) {
      if (!error && response.statusCode === 200) {

        var access_token = body.access_token,
            refresh_token = body.refresh_token;

        var options = {
          url: 'https://api.spotify.com/v1/me',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
        };

        // use the access token to access the Spotify Web API
        request.get(options, function(error, response, body) {
          console.log("BODY!", body)
          if (body.birthdate === null || undefined) body.birthdate = '0'
          if (body.display_name === null || undefined)  body.display_name = body.id
          if(!body.images.length) body.images.push({url: 'https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAfRAAAAJGY5YjFhN2Q2LTUyNjMtNDQ4OS04Mzk5LTcyMGQyM2E0MTgwOA.jpg'})
          const {uri, id, display_name, images: [{url: profilePic}], birthdate} = body

          createFirebaseAccount(uri, display_name, profilePic, birthdate, access_token, refresh_token)
            .then(firebaseToken => {
              res.send(signInFirebaseTemplate(firebaseToken));
            })
            .catch(console.error)
        });

      } else {
        res.redirect('/#' +
          querystring.stringify({
            error: 'invalid_token'
          }));
      }
    });
  }
});

app.get('/refresh_token', function(req, res) {
  // requesting access token from refresh token
  var refresh_token = req.query.refresh_token;
  var authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: { 'Authorization': 'Basic ' + (process.env.spotify_client_id + ':' + process.env.spotify_client_secret).toString('base64') },
    form: {
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    },
    json: true
  };

  request.post(authOptions, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      var access_token = body.access_token;
      res.send({
        'access_token': access_token
      });
    }
  });
});

app.get('/*', (req, res) => res.sendFile(__dirname + '/public/index.html'))

/**
 * Generates the HTML template that signs the user in Firebase using the given token and closes the
 * popup.
 */
function signInFirebaseTemplate(token) {
  return `
    <script src="https://www.gstatic.com/firebasejs/3.6.0/firebase.js"></script>
    <script>
      var token = ${JSON.stringify(token)};
      var config = ${JSON.stringify(require('./fire/config'))};
      var app = firebase.initializeApp(config);
      app.auth().signInWithCustomToken(token).then(() => location.replace('/dashboard')).catch(console.error);
    </script>`;
}

function createFirebaseAccount(uid, displayName, photoURL, birthdate, accessToken, refreshToken) {

  const optionsRecent = {
      url: 'https://api.spotify.com/v1/me/player/recently-played?limit=50',
      headers: { 'Authorization': 'Bearer ' + accessToken },
      json: true
    };

    const optionsTopArtists = {
      url: 'https://api.spotify.com/v1/me/top/artists?limit=50',
      headers: { 'Authorization': 'Bearer ' + accessToken },
      json: true
    };

    const optionsTopTracks = {
      url: 'https://api.spotify.com/v1/me/top/tracks?limit=50',
      headers: { 'Authorization': 'Bearer ' + accessToken },
      json: true
    }

    //set Spotify profile information on the db
    // admin.database().ref(`/Users/${uid}/`)
    //       .update({userProfile: {uid, displayName, photoURL, birthdate}})

    admin.database().ref(`/Users/${uid}/userProfile`)
        .set({uid, displayName, photoURL, birthdate})

    request.get(optionsRecent, function(error, response, body){
      const items = body.items
      const getRecentSongs = admin.database().ref(`/Users/${uid}/recentSongs`)
        .set({songs: items})
    })

    request.get(optionsTopArtists, function(error, response, body){
      const items = body.items
      const getTopArists = admin.database().ref(`/Users/${uid}/topArtists`)
        .set({artists: items})
    })

    request.get(optionsTopTracks, function(error, response, body){
      const items = body.items
      const getTopTracks = admin.database().ref(`/Users/${uid}/topTracks`)
        .set({tracks: items})
    })

    const databaseTask = admin.database().ref(`/spotifyAccessToken/${uid}`)
        .set({accessToken, refreshToken});
    const userCreationTask = admin.auth().updateUser(uid, {
      displayName: displayName,
      photoURL: photoURL
    }).catch(error => {
      if (error.code === 'auth/user-not-found') {
        return admin.auth().createUser({
          uid: uid,
          displayName: displayName,
          photoURL: photoURL
        });
      }
      throw error;
    });

    return Promise.all([userCreationTask, databaseTask]).then(() => {
      const token = admin.auth().createCustomToken(uid);
      console.log('Created Custom token for UID "', uid, '" Token:', token);
      return token;
    });
  }

console.log('Listening on 1337');
app.listen((process.env.PORT || 1337), function(){
  console.log('listening on 1337');
});
<commit_msg>console<commit_after>/**
 * This is an example of a basic node.js script that performs
 * the Authorization Code oAuth2 flow to authenticate against
 * the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow
 */

var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
const admin = require('firebase-admin');
if (process.env.NODE_ENV === 'development') {
  require('./.secrets/spotify.js');
  require('./.secrets/attune-d8afe-firebase-adminsdk-m5rub-8c85814d02.js'); // this will mutate the process.env object with your secrets.
}

console.log('PRIV KEY', process.env.private_key)
console.log('type of PRIV KEY', typeof process.env.private_key)

var attune = admin.initializeApp({
  "credential": admin.credential.cert({
  "type": process.env.type,
  "project_id": process.env.project_id,
  "private_key": process.env.private_key,
  "client_email": process.env.client_email,
  "private_key_id": process.env.private_key_id,

  "client_id": process.env.client_id,
  "auth_uri": process.env.auth_uri,
  "token_uri": process.env.token_uri,
  "auth_provider_x509_cert_url": process.env.auth_provider_x509_cert_url,
  "client_x509_cert_ur": process.env.client_x509_cert_url
  })
, "databaseURL": 'https://attune-d8afe.firebaseio.com/'});

var redirect_uri = (process.env.NODE_ENV === 'development' ? 'http://localhost:1337/callback' : 'http://attune-music.herokuapp.com/callback'); // Your cal uri

/**
 * Generates a random string containing numbers and letters
 * @param  {number} length The length of the string
 * @return {string} The generated string
 */
var generateRandomString = function(length) {
  var text = '';
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

var stateKey = 'spotify_auth_state';

var app = express();

app.use(express.static(__dirname + '/public'))
   .use(cookieParser());

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

  var state = generateRandomString(16);
  res.cookie(stateKey, state);

  // your application requests authorization
  var scope = 'user-follow-read user-top-read user-read-recently-played user-read-private user-read-email user-library-read user-read-birthdate';
  res.redirect('https://accounts.spotify.com/authorize?' +
    querystring.stringify({
      response_type: 'code',
      client_id: process.env.spotify_client_id,
      scope: scope,
      redirect_uri: redirect_uri,
      state: state
    }));
});

app.get('/callback', function(req, res) {
  // your application requests refresh and access tokens
  // after checking the state parameter

  var code = req.query.code || null;
  var state = req.query.state || null;
  var storedState = req.cookies ? req.cookies[stateKey] : null;

  if (state === null || state !== storedState) {
    res.redirect('/#' +
      querystring.stringify({
        error: 'State mismatch between request and cookie'
      }));
  } else {
    res.clearCookie(stateKey);
    var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        code: code,
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (new Buffer(process.env.spotify_client_id + ':' + process.env.spotify_client_secret).toString('base64'))
      },
      json: true
    };

    request.post(authOptions, function(error, response, body) {
      if (!error && response.statusCode === 200) {

        var access_token = body.access_token,
            refresh_token = body.refresh_token;

        var options = {
          url: 'https://api.spotify.com/v1/me',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
        };

        // use the access token to access the Spotify Web API
        request.get(options, function(error, response, body) {
          console.log("BODY!", body)
          if (body.birthdate === null || undefined) body.birthdate = '0'
          if (body.display_name === null || undefined)  body.display_name = body.id
          if(!body.images.length) body.images.push({url: 'https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAfRAAAAJGY5YjFhN2Q2LTUyNjMtNDQ4OS04Mzk5LTcyMGQyM2E0MTgwOA.jpg'})
          const {uri, id, display_name, images: [{url: profilePic}], birthdate} = body

          createFirebaseAccount(uri, display_name, profilePic, birthdate, access_token, refresh_token)
            .then(firebaseToken => {
              res.send(signInFirebaseTemplate(firebaseToken));
            })
            .catch(console.error)
        });

      } else {
        res.redirect('/#' +
          querystring.stringify({
            error: 'invalid_token'
          }));
      }
    });
  }
});

app.get('/refresh_token', function(req, res) {
  // requesting access token from refresh token
  var refresh_token = req.query.refresh_token;
  var authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: { 'Authorization': 'Basic ' + (process.env.spotify_client_id + ':' + process.env.spotify_client_secret).toString('base64') },
    form: {
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    },
    json: true
  };

  request.post(authOptions, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      var access_token = body.access_token;
      res.send({
        'access_token': access_token
      });
    }
  });
});

app.get('/*', (req, res) => res.sendFile(__dirname + '/public/index.html'))

/**
 * Generates the HTML template that signs the user in Firebase using the given token and closes the
 * popup.
 */
function signInFirebaseTemplate(token) {
  return `
    <script src="https://www.gstatic.com/firebasejs/3.6.0/firebase.js"></script>
    <script>
      var token = ${JSON.stringify(token)};
      var config = ${JSON.stringify(require('./fire/config'))};
      var app = firebase.initializeApp(config);
      app.auth().signInWithCustomToken(token).then(() => location.replace('/dashboard')).catch(console.error);
    </script>`;
}

function createFirebaseAccount(uid, displayName, photoURL, birthdate, accessToken, refreshToken) {

  const optionsRecent = {
      url: 'https://api.spotify.com/v1/me/player/recently-played?limit=50',
      headers: { 'Authorization': 'Bearer ' + accessToken },
      json: true
    };

    const optionsTopArtists = {
      url: 'https://api.spotify.com/v1/me/top/artists?limit=50',
      headers: { 'Authorization': 'Bearer ' + accessToken },
      json: true
    };

    const optionsTopTracks = {
      url: 'https://api.spotify.com/v1/me/top/tracks?limit=50',
      headers: { 'Authorization': 'Bearer ' + accessToken },
      json: true
    }

    //set Spotify profile information on the db
    // admin.database().ref(`/Users/${uid}/`)
    //       .update({userProfile: {uid, displayName, photoURL, birthdate}})

    admin.database().ref(`/Users/${uid}/userProfile`)
        .set({uid, displayName, photoURL, birthdate})

    request.get(optionsRecent, function(error, response, body){
      const items = body.items
      const getRecentSongs = admin.database().ref(`/Users/${uid}/recentSongs`)
        .set({songs: items})
    })

    request.get(optionsTopArtists, function(error, response, body){
      const items = body.items
      const getTopArists = admin.database().ref(`/Users/${uid}/topArtists`)
        .set({artists: items})
    })

    request.get(optionsTopTracks, function(error, response, body){
      const items = body.items
      const getTopTracks = admin.database().ref(`/Users/${uid}/topTracks`)
        .set({tracks: items})
    })

    const databaseTask = admin.database().ref(`/spotifyAccessToken/${uid}`)
        .set({accessToken, refreshToken});
    const userCreationTask = admin.auth().updateUser(uid, {
      displayName: displayName,
      photoURL: photoURL
    }).catch(error => {
      if (error.code === 'auth/user-not-found') {
        return admin.auth().createUser({
          uid: uid,
          displayName: displayName,
          photoURL: photoURL
        });
      }
      throw error;
    });

    return Promise.all([userCreationTask, databaseTask]).then(() => {
      const token = admin.auth().createCustomToken(uid);
      console.log('Created Custom token for UID "', uid, '" Token:', token);
      return token;
    });
  }

console.log('Listening on 1337');
app.listen((process.env.PORT || 1337), function(){
  console.log('listening on 1337');
});
<|endoftext|>


<commit_before>const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;

const ComponentSchema = new Schema({
    componentId: { type: String, unique: true, required: true },
    name: { type: String, unique: true, required: true },
    price: { type: Number, requred: true },
    type: { type: Number, required: true }, //is is a base component or is it composite
    typeString: { type: String, required: true },
    components: { type: [this] }
});

module.exports = Mongoose.model('component', ComponentSchema);
<commit_msg>added component model<commit_after>const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;

const ComponentSchema = new Schema({
    componentId: { type: String, unique: true, required: true },
    name: { type: String, unique: true, required: true },
    price: { type: Number, requred: true },
    type: { type: Number, required: true }, //is is a base component or is it composite
    typeString: { type: String, required: true },
    components: { type: [this] }
});

module.exports = Mongoose.model('component', ComponentSchema);
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const http = require('http');

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Testing
slapp.command('/bible', /.*/, (msg, text) => {
  console.log('received bible command')
  console.log('msg: ', msg)
  console.log('text: ', text)
  var verse = sendRequest()
  console.log('got this from sendRequest():', verse)
  msg.say('Received slash command for Bible. Command entered:' + text)
  msg.say('Here\'s your verse!\n' + verse)
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// Send HTTP Request
function sendRequest(callback) {
  var body;
  var options = {
    host: 'labs.bible.org',
    path: '/api/?passage=John+3:16-17',
  }

  var request = http.get(options, function(response){
    console.log('STATUS: ' + response.statusCode);
    console.log('HEADERS: ' + JSON.stringify(response.headers));

    // Buffer the body entirely for processing as a whole.
    var bodyStream = [];
    response.on('data', function(chunk) {
      // Partially streamed body
      bodyStream.push(chunk);
    }).on('end', function() {
      // Completely streamed body
      body = Buffer.concat(bodyStream);
      console.log('BODY: ' + body);
      reply(body.stringify);
      return body
    })
  });

  request.on('error', function(e) {
    console.log('error occurred in HTTP GET request: ', e.message);
  });
}

function reply(body) {
  console.log('got body:', body);
}

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>trying more stuff<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const http = require('http');

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Testing
slapp.command('/bible', /.*/, (msg, text) => {
  var verse = '';
  console.log('received bible command')
  console.log('msg: ', msg)
  console.log('text: ', text)
  var verse = sendRequest();
  console.log('got this from sendRequest():', verse)
  msg.say('Received slash command for Bible. Command entered:' + text)
  msg.say('Here\'s your verse!\n' + verse)
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// Send HTTP Request
function sendRequest(callback) {
  var body;
  var options = {
    host: 'labs.bible.org',
    path: '/api/?passage=John+3:16-17',
  }

  var request = http.get(options, function(response){
    console.log('STATUS: ' + response.statusCode);
    console.log('HEADERS: ' + JSON.stringify(response.headers));

    // Buffer the body entirely for processing as a whole.
    var bodyStream = [];
    response.on('data', function(chunk) {
      // Partially streamed body
      bodyStream.push(chunk);
    }).on('end', function() {
      // Completely streamed body
      body = Buffer.concat(bodyStream);
      console.log('BODY: ' + body);
      reply(body.stringify);
      return body
    })
  });

  request.on('error', function(e) {
    console.log('error occurred in HTTP GET request: ', e.message);
  });
}

function reply(body) {
  console.log('got body:', body);
}

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>