<commit_before>/**
 * Module dependencies.
 */

var connect = require('connect')
  , Router = require('./router')
  , methods = require('methods')
  , middleware = require('./middleware')
  , debug = require('debug')('express:application')
  , locals = require('./utils').locals
  , View = require('./view')
  , utils = connect.utils
  , path = require('path')
  , http = require('http')
  , join = path.join;

/**
 * Application prototype.
 */

var app = exports = module.exports = {};

/**
 * Initialize the server.
 *
 *   - setup default configuration
 *   - setup default middleware
 *   - setup route reflection methods
 *
 * @api private
 */

app.init = function(){
  this.cache = {};
  this.settings = {};
  this.engines = {};
  this.viewCallbacks = [];
  this.defaultConfiguration();
};

/**
 * Initialize application configuration.
 *
 * @api private
 */

app.defaultConfiguration = function(){
  // default settings
  this.enable('x-powered-by');
  this.set('env', process.env.NODE_ENV || 'development');
  this.set('subdomain offset', 2);
  debug('booting in %s mode', this.get('env'));

  // implicit middleware
  this.use(connect.query());
  this.use(middleware.init(this));

  // inherit protos
  this.on('mount', function(parent){
    this.request.__proto__ = parent.request;
    this.response.__proto__ = parent.response;
    this.engines.__proto__ = parent.engines;
  });

  // router
  this._router = new Router(this);
  this.routes = this._router.map;
  this.__defineGetter__('router', function(){
    this._usedRouter = true;
    this._router.caseSensitive = this.enabled('case sensitive routing');
    this._router.strict = this.enabled('strict routing');
    return this._router.middleware;
  });

  // setup locals
  this.locals = locals(this);

  // default locals
  this.locals.settings = this.settings;

  // default configuration
  this.set('views', process.cwd() + '/views');
  this.set('jsonp callback name', 'callback');

  this.configure('development', function(){
    this.set('json spaces', 2);
  });

  this.configure('production', function(){
    this.enable('view cache');
  });
};

/**
 * Proxy `connect#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} fn
 * @return {app} for chaining
 * @api public
 */

app.use = function(route, fn){
  var app;

  // default route to '/'
  if ('string' != typeof route) fn = route, route = '/';

  // express app
  if (fn.handle && fn.set) app = fn;

  // restore .app property on req and res
  if (app) {
    app.route = route;
    fn = function(req, res, next) {
      var orig = req.app;
      app.handle(req, res, function(err){
        req.app = res.app = orig;
        req.__proto__ = orig.request;
        res.__proto__ = orig.response;
        next(err);
      });
    };
  }

  connect.proto.use.call(this, route, fn);

  // mounted an app
  if (app) {
    app.parent = this;
    app.emit('mount', this);
  }

  return this;
};

/**
 * Register the given template engine callback `fn`
 * as `ext`.
 *
 * By default will `require()` the engine based on the
 * file extension. For example if you try to render
 * a "foo.jade" file Express will invoke the following internally:
 *
 *     app.engine('jade', require('jade').__express);
 *
 * For engines that do not provide `.__express` out of the box,
 * or if you wish to "map" a different extension to the template engine
 * you may use this method. For example mapping the EJS template engine to
 * ".html" files:
 *
 *     app.engine('html', require('ejs').renderFile);
 *
 * In this case EJS provides a `.renderFile()` method with
 * the same signature that Express expects: `(path, options, callback)`,
 * though note that it aliases this method as `ejs.__express` internally
 * so if you're using ".ejs" extensions you dont need to do anything.
 *
 * Some template engines do not follow this convention, the
 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)
 * library was created to map all of node's popular template
 * engines to follow this convention, thus allowing them to
 * work seamlessly within Express.
 *
 * @param {String} ext
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */

app.engine = function(ext, fn){
  if ('function' != typeof fn) throw new Error('callback function required');
  if ('.' != ext[0]) ext = '.' + ext;
  this.engines[ext] = fn;
  return this;
};

/**
 * Map the given param placeholder `name`(s) to the given callback(s).
 *
 * Parameter mapping is used to provide pre-conditions to routes
 * which use normalized placeholders. For example a _:user_id_ parameter
 * could automatically load a user's information from the database without
 * any additional code,
 *
 * The callback uses the samesignature as middleware, the only differencing
 * being that the value of the placeholder is passed, in this case the _id_
 * of the user. Once the `next()` function is invoked, just like middleware
 * it will continue on to execute the route, or subsequent parameter functions.
 *
 *      app.param('user_id', function(req, res, next, id){
 *        User.find(id, function(err, user){
 *          if (err) {
 *            next(err);
 *          } else if (user) {
 *            req.user = user;
 *            next();
 *          } else {
 *            next(new Error('failed to load user'));
 *          }
 *        });
 *      });
 *
 * @param {String|Array} name
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */

app.param = function(name, fn){
  var self = this
    , fns = [].slice.call(arguments, 1);

  // array
  if (Array.isArray(name)) {
    name.forEach(function(name){
      fns.forEach(function(fn){
        self.param(name, fn);
      });
    });
  // param logic
  } else if ('function' == typeof name) {
    this._router.param(name);
  // single
  } else {
    if (':' == name[0]) name = name.substr(1);
    fns.forEach(function(fn){
      self._router.param(name, fn);
    });
  }

  return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 *
 *    app.set('foo', 'bar');
 *    app.get('foo');
 *    // => "bar"
 *
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server} for chaining
 * @api public
 */

app.set = function(setting, val){
  if (1 == arguments.length) {
    if (this.settings.hasOwnProperty(setting)) {
      return this.settings[setting];
    } else if (this.parent) {
      return this.parent.set(setting);
    }
  } else {
    this.settings[setting] = val;
    return this;
  }
};

/**
 * Return the app's absolute pathname
 * based on the parent(s) that have
 * mounted it.
 *
 * For example if the application was
 * mounted as "/admin", which itself
 * was mounted as "/blog" then the
 * return value would be "/blog/admin".
 *
 * @return {String}
 * @api private
 */

app.path = function(){
  return this.parent
    ? this.parent.path() + this.route
    : '';
};

/**
 * Check if `setting` is enabled (truthy).
 *
 *    app.enabled('foo')
 *    // => false
 *
 *    app.enable('foo')
 *    app.enabled('foo')
 *    // => true
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

app.enabled = function(setting){
  return !!this.set(setting);
};

/**
 * Check if `setting` is disabled.
 *
 *    app.disabled('foo')
 *    // => true
 *
 *    app.enable('foo')
 *    app.disabled('foo')
 *    // => false
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

app.disabled = function(setting){
  return !this.set(setting);
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {app} for chaining
 * @api public
 */

app.enable = function(setting){
  return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {app} for chaining
 * @api public
 */

app.disable = function(setting){
  return this.set(setting, false);
};

/**
 * Configure callback for zero or more envs,
 * when no `env` is specified that callback will
 * be invoked for all environments. Any combination
 * can be used multiple times, in any order desired.
 *
 * Examples:
 *
 *    app.configure(function(){
 *      // executed for all envs
 *    });
 *
 *    app.configure('stage', function(){
 *      // executed staging env
 *    });
 *
 *    app.configure('stage', 'production', function(){
 *      // executed for stage and production
 *    });
 *
 * Note:
 *
 *  These callbacks are invoked immediately, and
 *  are effectively sugar for the following:
 *
 *     var env = process.env.NODE_ENV || 'development';
 *
 *      switch (env) {
 *        case 'development':
 *          ...
 *          break;
 *        case 'stage':
 *          ...
 *          break;
 *        case 'production':
 *          ...
 *          break;
 *      }
 *
 * @param {String} env...
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */

app.configure = function(env, fn){
  var envs = 'all'
    , args = [].slice.call(arguments);
  fn = args.pop();
  if (args.length) envs = args;
  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);
  return this;
};

/**
 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
 */

methods.forEach(function(method){
  app[method] = function(path){
    if ('get' == method && 1 == arguments.length) return this.set(path);

    // if no router attacked yet, attach the router
    if (!this._usedRouter) this.use(this.router);

    // setup route
    this._router[method].apply(this._router, arguments);
    return this;
  };
});

/**
 * Special-cased "all" method, applying the given route `path`,
 * middleware, and callback to _every_ HTTP method.
 *
 * @param {String} path
 * @param {Function} ...
 * @return {app} for chaining
 * @api public
 */

app.all = function(path){
  var args = arguments;
  methods.forEach(function(method){
    app[method].apply(this, args);
  }, this);
  return this;
};

// del -> delete alias

app.del = app.delete;

/**
 * Render the given view `name` name with `options`
 * and a callback accepting an error and the
 * rendered template string.
 *
 * Example:
 *
 *    app.render('email', { name: 'Tobi' }, function(err, html){
 *      // ...
 *    })
 *
 * @param {String} name
 * @param {String|Function} options or fn
 * @param {Function} fn
 * @api public
 */

app.render = function(name, options, fn){
  var opts = {}
    , cache = this.cache
    , engines = this.engines
    , view;

  // support callback function as second arg
  if ('function' == typeof options) {
    fn = options, options = {};
  }

  // merge app.locals
  utils.merge(opts, this.locals);

  // merge options._locals
  if (options._locals) utils.merge(opts, options._locals);

  // merge options
  utils.merge(opts, options);

  // set .cache unless explicitly provided
  opts.cache = null == opts.cache
    ? this.enabled('view cache')
    : opts.cache;

  // primed cache
  if (opts.cache) view = cache[name];

  // view
  if (!view) {
    view = new View(name, {
      defaultEngine: this.get('view engine'),
      root: this.get('views'),
      engines: engines
    });

    if (!view.path) {
      var err = new Error('Failed to lookup view "' + name + '"');
      err.view = view;
      return fn(err);
    }

    // prime the cache
    if (opts.cache) cache[name] = view;
  }

  // render
  try {
    view.render(opts, fn);
  } catch (err) {
    fn(err);
  }
};

/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
<commit_msg>fixed typo<commit_after>/**
 * Module dependencies.
 */

var connect = require('connect')
  , Router = require('./router')
  , methods = require('methods')
  , middleware = require('./middleware')
  , debug = require('debug')('express:application')
  , locals = require('./utils').locals
  , View = require('./view')
  , utils = connect.utils
  , path = require('path')
  , http = require('http')
  , join = path.join;

/**
 * Application prototype.
 */

var app = exports = module.exports = {};

/**
 * Initialize the server.
 *
 *   - setup default configuration
 *   - setup default middleware
 *   - setup route reflection methods
 *
 * @api private
 */

app.init = function(){
  this.cache = {};
  this.settings = {};
  this.engines = {};
  this.viewCallbacks = [];
  this.defaultConfiguration();
};

/**
 * Initialize application configuration.
 *
 * @api private
 */

app.defaultConfiguration = function(){
  // default settings
  this.enable('x-powered-by');
  this.set('env', process.env.NODE_ENV || 'development');
  this.set('subdomain offset', 2);
  debug('booting in %s mode', this.get('env'));

  // implicit middleware
  this.use(connect.query());
  this.use(middleware.init(this));

  // inherit protos
  this.on('mount', function(parent){
    this.request.__proto__ = parent.request;
    this.response.__proto__ = parent.response;
    this.engines.__proto__ = parent.engines;
  });

  // router
  this._router = new Router(this);
  this.routes = this._router.map;
  this.__defineGetter__('router', function(){
    this._usedRouter = true;
    this._router.caseSensitive = this.enabled('case sensitive routing');
    this._router.strict = this.enabled('strict routing');
    return this._router.middleware;
  });

  // setup locals
  this.locals = locals(this);

  // default locals
  this.locals.settings = this.settings;

  // default configuration
  this.set('views', process.cwd() + '/views');
  this.set('jsonp callback name', 'callback');

  this.configure('development', function(){
    this.set('json spaces', 2);
  });

  this.configure('production', function(){
    this.enable('view cache');
  });
};

/**
 * Proxy `connect#use()` to apply settings to
 * mounted applications.
 *
 * @param {String|Function|Server} route
 * @param {Function|Server} fn
 * @return {app} for chaining
 * @api public
 */

app.use = function(route, fn){
  var app;

  // default route to '/'
  if ('string' != typeof route) fn = route, route = '/';

  // express app
  if (fn.handle && fn.set) app = fn;

  // restore .app property on req and res
  if (app) {
    app.route = route;
    fn = function(req, res, next) {
      var orig = req.app;
      app.handle(req, res, function(err){
        req.app = res.app = orig;
        req.__proto__ = orig.request;
        res.__proto__ = orig.response;
        next(err);
      });
    };
  }

  connect.proto.use.call(this, route, fn);

  // mounted an app
  if (app) {
    app.parent = this;
    app.emit('mount', this);
  }

  return this;
};

/**
 * Register the given template engine callback `fn`
 * as `ext`.
 *
 * By default will `require()` the engine based on the
 * file extension. For example if you try to render
 * a "foo.jade" file Express will invoke the following internally:
 *
 *     app.engine('jade', require('jade').__express);
 *
 * For engines that do not provide `.__express` out of the box,
 * or if you wish to "map" a different extension to the template engine
 * you may use this method. For example mapping the EJS template engine to
 * ".html" files:
 *
 *     app.engine('html', require('ejs').renderFile);
 *
 * In this case EJS provides a `.renderFile()` method with
 * the same signature that Express expects: `(path, options, callback)`,
 * though note that it aliases this method as `ejs.__express` internally
 * so if you're using ".ejs" extensions you dont need to do anything.
 *
 * Some template engines do not follow this convention, the
 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)
 * library was created to map all of node's popular template
 * engines to follow this convention, thus allowing them to
 * work seamlessly within Express.
 *
 * @param {String} ext
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */

app.engine = function(ext, fn){
  if ('function' != typeof fn) throw new Error('callback function required');
  if ('.' != ext[0]) ext = '.' + ext;
  this.engines[ext] = fn;
  return this;
};

/**
 * Map the given param placeholder `name`(s) to the given callback(s).
 *
 * Parameter mapping is used to provide pre-conditions to routes
 * which use normalized placeholders. For example a _:user_id_ parameter
 * could automatically load a user's information from the database without
 * any additional code,
 *
 * The callback uses the samesignature as middleware, the only differencing
 * being that the value of the placeholder is passed, in this case the _id_
 * of the user. Once the `next()` function is invoked, just like middleware
 * it will continue on to execute the route, or subsequent parameter functions.
 *
 *      app.param('user_id', function(req, res, next, id){
 *        User.find(id, function(err, user){
 *          if (err) {
 *            next(err);
 *          } else if (user) {
 *            req.user = user;
 *            next();
 *          } else {
 *            next(new Error('failed to load user'));
 *          }
 *        });
 *      });
 *
 * @param {String|Array} name
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */

app.param = function(name, fn){
  var self = this
    , fns = [].slice.call(arguments, 1);

  // array
  if (Array.isArray(name)) {
    name.forEach(function(name){
      fns.forEach(function(fn){
        self.param(name, fn);
      });
    });
  // param logic
  } else if ('function' == typeof name) {
    this._router.param(name);
  // single
  } else {
    if (':' == name[0]) name = name.substr(1);
    fns.forEach(function(fn){
      self._router.param(name, fn);
    });
  }

  return this;
};

/**
 * Assign `setting` to `val`, or return `setting`'s value.
 *
 *    app.set('foo', 'bar');
 *    app.get('foo');
 *    // => "bar"
 *
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {String} val
 * @return {Server} for chaining
 * @api public
 */

app.set = function(setting, val){
  if (1 == arguments.length) {
    if (this.settings.hasOwnProperty(setting)) {
      return this.settings[setting];
    } else if (this.parent) {
      return this.parent.set(setting);
    }
  } else {
    this.settings[setting] = val;
    return this;
  }
};

/**
 * Return the app's absolute pathname
 * based on the parent(s) that have
 * mounted it.
 *
 * For example if the application was
 * mounted as "/admin", which itself
 * was mounted as "/blog" then the
 * return value would be "/blog/admin".
 *
 * @return {String}
 * @api private
 */

app.path = function(){
  return this.parent
    ? this.parent.path() + this.route
    : '';
};

/**
 * Check if `setting` is enabled (truthy).
 *
 *    app.enabled('foo')
 *    // => false
 *
 *    app.enable('foo')
 *    app.enabled('foo')
 *    // => true
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

app.enabled = function(setting){
  return !!this.set(setting);
};

/**
 * Check if `setting` is disabled.
 *
 *    app.disabled('foo')
 *    // => true
 *
 *    app.enable('foo')
 *    app.disabled('foo')
 *    // => false
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */

app.disabled = function(setting){
  return !this.set(setting);
};

/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {app} for chaining
 * @api public
 */

app.enable = function(setting){
  return this.set(setting, true);
};

/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {app} for chaining
 * @api public
 */

app.disable = function(setting){
  return this.set(setting, false);
};

/**
 * Configure callback for zero or more envs,
 * when no `env` is specified that callback will
 * be invoked for all environments. Any combination
 * can be used multiple times, in any order desired.
 *
 * Examples:
 *
 *    app.configure(function(){
 *      // executed for all envs
 *    });
 *
 *    app.configure('stage', function(){
 *      // executed staging env
 *    });
 *
 *    app.configure('stage', 'production', function(){
 *      // executed for stage and production
 *    });
 *
 * Note:
 *
 *  These callbacks are invoked immediately, and
 *  are effectively sugar for the following:
 *
 *     var env = process.env.NODE_ENV || 'development';
 *
 *      switch (env) {
 *        case 'development':
 *          ...
 *          break;
 *        case 'stage':
 *          ...
 *          break;
 *        case 'production':
 *          ...
 *          break;
 *      }
 *
 * @param {String} env...
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */

app.configure = function(env, fn){
  var envs = 'all'
    , args = [].slice.call(arguments);
  fn = args.pop();
  if (args.length) envs = args;
  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);
  return this;
};

/**
 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
 */

methods.forEach(function(method){
  app[method] = function(path){
    if ('get' == method && 1 == arguments.length) return this.set(path);

    // if no router attached yet, attach the router
    if (!this._usedRouter) this.use(this.router);

    // setup route
    this._router[method].apply(this._router, arguments);
    return this;
  };
});

/**
 * Special-cased "all" method, applying the given route `path`,
 * middleware, and callback to _every_ HTTP method.
 *
 * @param {String} path
 * @param {Function} ...
 * @return {app} for chaining
 * @api public
 */

app.all = function(path){
  var args = arguments;
  methods.forEach(function(method){
    app[method].apply(this, args);
  }, this);
  return this;
};

// del -> delete alias

app.del = app.delete;

/**
 * Render the given view `name` name with `options`
 * and a callback accepting an error and the
 * rendered template string.
 *
 * Example:
 *
 *    app.render('email', { name: 'Tobi' }, function(err, html){
 *      // ...
 *    })
 *
 * @param {String} name
 * @param {String|Function} options or fn
 * @param {Function} fn
 * @api public
 */

app.render = function(name, options, fn){
  var opts = {}
    , cache = this.cache
    , engines = this.engines
    , view;

  // support callback function as second arg
  if ('function' == typeof options) {
    fn = options, options = {};
  }

  // merge app.locals
  utils.merge(opts, this.locals);

  // merge options._locals
  if (options._locals) utils.merge(opts, options._locals);

  // merge options
  utils.merge(opts, options);

  // set .cache unless explicitly provided
  opts.cache = null == opts.cache
    ? this.enabled('view cache')
    : opts.cache;

  // primed cache
  if (opts.cache) view = cache[name];

  // view
  if (!view) {
    view = new View(name, {
      defaultEngine: this.get('view engine'),
      root: this.get('views'),
      engines: engines
    });

    if (!view.path) {
      var err = new Error('Failed to lookup view "' + name + '"');
      err.view = view;
      return fn(err);
    }

    // prime the cache
    if (opts.cache) cache[name] = view;
  }

  // render
  try {
    view.render(opts, fn);
  } catch (err) {
    fn(err);
  }
};

/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
<|endoftext|>


<commit_before>var express = require('express'); // Server
var bodyParser = require('body-parser'); // Parse API request body
var mongoose = require('mongoose'); // Model creation for Mongo
var Folder = require('./models/folder'); // Folder model for mongoose
var config = require('./config'); // Imports Mongo Address setttings
var logger = require('morgan'); // Logger
var jwt = require('express-jwt'); // Authentication
var cors = require('cors'); // Authentication

var data = { rob: 'testrob' }; // This is the data being written to which we need to change.
var folderData = { folderStuff: 'folderData'}

var jedis = [
  {
    id: 1,
    name: 'Luke Skywalker',
    image: 'http://localhost:7000/images/luke-skywalker.jpg'
  },
  {
    id: 2,
    name: 'Anakin Skywalker',
    image: 'http://localhost:7000/images/anakin-skywalker.png'
  },
  {
    id: 3,
    name: 'Yoda',
    image: 'http://localhost:7000/images/yoda.png'
  },
  {
    id: 4,
    name: 'Obi-Wan Kenobi',
    image: 'http://localhost:7000/images/obi-wan-kenobi.jpg'
  },
  {
    id: 5,
    name: 'Mace Windu',
    image: 'http://localhost:7000/images/mace-windu.jpg'
  }
];

const authCheck = jwt({
  secret: 'AUTH0_SECRET',
  audience: 'AUTH_CLIENT_ID'
});

express()
.use(cors()) // Authentication
.use(express.static(__dirname + '/public')) // Setup static directory
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(logger(':method :url :status :response-time ms - :res[content-length]'))
.get('/api/data', (req, res) => res.json(data))
.post('/api/data', (req, res) => res.json(data = req.body))
.post('api/test', function(req, res) {
  res.json({ message: 'hooray! welcome to our api!' }); //Use postman post localhost:3333/test to test
})
.post('/api/folder', function(req,res) {

  var folder = new Folder(); // Create an new mongoose folder schema
  folder.name = req.body.name;
  console.log( folder.name );

  folder.save(function(err) {
    if (err)
    res.send(err); // Switch this off when in production
    res.json({ name: folder.name});
    console.log('Folder was saved success')
    //res.json({ message: 'Bear created!' });
 });
})
.post('api/process', function(req, res)) {
    var process = new Process();// Create a new mongoose folder schema
    process.name = req.body.name;
    console.log( process.name );

    folder.save(function(err){
        if (err)
            res.send(err);
        res.json({ name: process.name});
        console.log('Process was saved success')

    });
})
.get('/api/getfolders', function(req,res) {

    Folder.find(function(err, turkeys) {
        if (err)
            res.send(err);
            res.json(turkeys);
    });
})
.get('/api/jedis', (req, res) => {
  const allJedis = jedis.map(jedi => {
    return { id: jedi.id, name: jedi.name }
  });
  res.json(allJedis);
})
.get('/api/jedis/:id', authCheck, (req, res) => {
  res.json(jedis.filter(jedi => jedi.id === parseInt(req.params.id))[0]);
})
.get('*', (req, res) => res.sendFile(__dirname + '/public/index.html')) // Needs to be last in chain
.listen(80);

// Authentication middleware provided by express-jwt.
// This middleware will check incoming requests for a valid
// JWT on any routes that it is applied to.

mongoose.connect(config.database);
mongoose.connection.on('error', function() {
  console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?1');
});
<commit_msg>fixed some process model issues<commit_after>var express = require('express'); // Server
var bodyParser = require('body-parser'); // Parse API request body
var mongoose = require('mongoose'); // Model creation for Mongo
var Folder = require('./models/folder'); // Folder model for mongoose
var Process = require('./models/folder');
var config = require('./config'); // Imports Mongo Address setttings
var logger = require('morgan'); // Logger
var jwt = require('express-jwt'); // Authentication
var cors = require('cors'); // Authentication

var data = { rob: 'testrob' }; // This is the data being written to which we need to change.
var folderData = { folderStuff: 'folderData'}

var jedis = [
  {
    id: 1,
    name: 'Luke Skywalker',
    image: 'http://localhost:7000/images/luke-skywalker.jpg'
  },
  {
    id: 2,
    name: 'Anakin Skywalker',
    image: 'http://localhost:7000/images/anakin-skywalker.png'
  },
  {
    id: 3,
    name: 'Yoda',
    image: 'http://localhost:7000/images/yoda.png'
  },
  {
    id: 4,
    name: 'Obi-Wan Kenobi',
    image: 'http://localhost:7000/images/obi-wan-kenobi.jpg'
  },
  {
    id: 5,
    name: 'Mace Windu',
    image: 'http://localhost:7000/images/mace-windu.jpg'
  }
];

const authCheck = jwt({
  secret: 'AUTH0_SECRET',
  audience: 'AUTH_CLIENT_ID'
});

express()
.use(cors()) // Authentication
.use(express.static(__dirname + '/public')) // Setup static directory
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(logger(':method :url :status :response-time ms - :res[content-length]'))
.get('/api/data', (req, res) => res.json(data))
.post('/api/data', (req, res) => res.json(data = req.body))
.post('api/test', function(req, res) {
  res.json({ message: 'hooray! welcome to our api!' }); //Use postman post localhost:3333/test to test
})
.post('/api/folder', function(req,res) {

  var folder = new Folder(); // Create an new mongoose folder schema
  folder.name = req.body.name;
  console.log( folder.name );

  folder.save(function(err) {
    if (err)
    res.send(err); // Switch this off when in production
    res.json({ name: folder.name});
    console.log('Folder was saved success')
    //res.json({ message: 'Bear created!' });
 });
})
.post('/api/process', function(req, res) {
    var process = new Process();// Create a new mongoose folder schema
    process.name = req.body.name;
    console.log( process.name );

    process.save(function(err){
        if (err)
            res.send(err);
        res.json({ name: process.name});
        console.log('Process was saved success')

    });
})
.get('/api/getfolders', function(req,res) {

    Folder.find(function(err, turkeys) {
        if (err)
            res.send(err);
            res.json(turkeys);
    });
})
.get('/api/jedis', (req, res) => {
  const allJedis = jedis.map(jedi => {
    return { id: jedi.id, name: jedi.name }
  });
  res.json(allJedis);
})
.get('/api/jedis/:id', authCheck, (req, res) => {
  res.json(jedis.filter(jedi => jedi.id === parseInt(req.params.id))[0]);
})
.get('*', (req, res) => res.sendFile(__dirname + '/public/index.html')) // Needs to be last in chain
.listen(80);

// Authentication middleware provided by express-jwt.
// This middleware will check incoming requests for a valid
// JWT on any routes that it is applied to.

mongoose.connect(config.database);
mongoose.connection.on('error', function() {
  console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?1');
});
<|endoftext|>


<commit_before>/*
 * CoursesLib
 * This file contains useful helper functions that do various course- and event-related tasks.
 */
window.coursesLib = {};

window.coursesLib.baseUrl = "https://courses2015.dalton.org";

window.coursesLib.checkLoggedIn = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/login/index.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.isLoggedIn = ($response.find(".loginform").length == 0);

		doneFunc(respObj);
	});
};

window.coursesLib.getCourseEvents = function(courseId, doneFunc) {
	$.get(window.coursesLib.baseUrl + "/course/view.php" + "?id=" + courseId, function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.id = courseId;
		respObj.title = $response.children("#page-content")
								.children("#region-main-box")
								.children("#region-post-box")
								.children("#region-main-wrap")
								.children("#region-main")
								.children("#region-main-box")
								.children(".region-content")
								.children(".course-content")
								.text();

		doneFunc(respObj);
	});
};

window.coursesLib.getCourseInfo = function(courseId, doneFunc) {
	$.get(window.coursesLib.baseUrl + "/course/view.php" + "?id=" + courseId, function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.id = courseId;
		respObj.title = $response.children("#page-header").children(".headermain").text();

		doneFunc(respObj);
	});
};

window.coursesLib.getCourseList = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/index.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.classes = [];
		$response.find(".coursename > a").each(function() {
			respObj.classes.push({	courseId: parseInt($(this).attr("href").replace(window.coursesLib.baseUrl + "/course/view.php?id=", "")),
									name: $(this).text(),
									url: $(this).attr("href")
								});
		})

		doneFunc(respObj);
	});
};

window.coursesLib.getUpcomingCourseEvents = function(courseId, doneFunc) {
	$.get(window.coursesLib.baseUrl + "/calendar/view.php" + "?course=" + courseId, function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.id = courseId;
		respObj.events = [];

		$response.children("#page-content")
					.children("#region-main-box")
					.children("#region-post-box")
					.children("#region-main-wrap")
					.children("#region-main")
					.children(".region-content")
					.children(".maincalendar")
					.children(".heightcontainer")
					.children(".eventlist")
					.children(".event").each(function() {
						// !!!
						var eventTitle = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").text().replace(/\s{2,}/g, " ");
						var eventCourse = $(this).children("tbody").children(".r0").children(".topic").children(".course").children("a").text().replace(/\s{2,}/g, " ");
						var eventHtml = $(this).children("tbody").children(".r1").children(".description").html();
						var eventText = $(this).children("tbody").children(".r1").children(".description").text();
						var eventNormText = $(this).children("tbody").children(".r1").children(".description").text().replace(/\r/g, "").replace(/\n/g, " ");
						var eventLink = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").attr("href");

						var eventObj = {title: eventTitle, course: eventCourse, text: eventText, normText: eventNormText, html: eventHtml, link: eventLink};

						respObj.events.push(eventObj);
					});

		doneFunc(respObj);
	});
};

window.coursesLib.getUpcomingEvents = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/calendar/view.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.events = [];

		$response.children("#page-content")
					.children("#region-main-box")
					.children("#region-post-box")
					.children("#region-main-wrap")
					.children("#region-main")
					.children(".region-content")
					.children(".maincalendar")
					.children(".heightcontainer")
					.children(".eventlist")
					.children(".event").each(function() {
						// !!!
						var eventTitle = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").text().replace(/\s{2,}/g, " ");
						var eventCourse = $(this).children("tbody").children(".r0").children(".topic").children(".course").children("a").text().replace(/\s{2,}/g, " ");
						var eventHtml = $(this).children("tbody").children(".r1").children(".description").html();
						var eventText = $(this).children("tbody").children(".r1").children(".description").text();
						var eventNormText = $(this).children("tbody").children(".r1").children(".description").text().replace(/\r/g, "").replace(/\n/g, " ");
						var eventLink = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").attr("href");

						var eventObj = {title: eventTitle, course: eventCourse, text: eventText, normText: eventNormText, html: eventHtml, link: eventLink};

						respObj.events.push(eventObj);
					});

		doneFunc(respObj);
	});
};

window.coursesLib.getProfile = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/user/profile.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.fullName = $response.find(".userprofile").children("h2").text();
		respObj.firstName = respObj.fullName.split(' ')[0];
		respObj.lastName = respObj.fullName.split(' ')[1];
		respObj.avatarUrl = $response.find(".userpicture").attr("src");

		doneFunc(respObj);
	});
};

console.log("CoursesLib ready!");<commit_msg>More new year stuff<commit_after>/*
 * CoursesLib
 * This file contains useful helper functions that do various course- and event-related tasks.
 */
window.coursesLib = {};

window.coursesLib.baseUrl = "https://courses2016.dalton.org";

window.coursesLib.checkLoggedIn = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/login/index.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.isLoggedIn = ($response.find(".loginform").length == 0);

		doneFunc(respObj);
	});
};

window.coursesLib.getCourseEvents = function(courseId, doneFunc) {
	$.get(window.coursesLib.baseUrl + "/course/view.php" + "?id=" + courseId, function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.id = courseId;
		respObj.title = $response.children("#page-content")
								.children("#region-main-box")
								.children("#region-post-box")
								.children("#region-main-wrap")
								.children("#region-main")
								.children("#region-main-box")
								.children(".region-content")
								.children(".course-content")
								.text();

		doneFunc(respObj);
	});
};

window.coursesLib.getCourseInfo = function(courseId, doneFunc) {
	$.get(window.coursesLib.baseUrl + "/course/view.php" + "?id=" + courseId, function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.id = courseId;
		respObj.title = $response.children("#page-header").children(".headermain").text();

		doneFunc(respObj);
	});
};

window.coursesLib.getCourseList = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/index.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.classes = [];
		$response.find(".coursename > a").each(function() {
			respObj.classes.push({	courseId: parseInt($(this).attr("href").replace(window.coursesLib.baseUrl + "/course/view.php?id=", "")),
									name: $(this).text(),
									url: $(this).attr("href")
								});
		})

		doneFunc(respObj);
	});
};

window.coursesLib.getUpcomingCourseEvents = function(courseId, doneFunc) {
	$.get(window.coursesLib.baseUrl + "/calendar/view.php" + "?course=" + courseId, function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.id = courseId;
		respObj.events = [];

		$response.children("#page-content")
					.children("#region-main-box")
					.children("#region-post-box")
					.children("#region-main-wrap")
					.children("#region-main")
					.children(".region-content")
					.children(".maincalendar")
					.children(".heightcontainer")
					.children(".eventlist")
					.children(".event").each(function() {
						// !!!
						var eventTitle = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").text().replace(/\s{2,}/g, " ");
						var eventCourse = $(this).children("tbody").children(".r0").children(".topic").children(".course").children("a").text().replace(/\s{2,}/g, " ");
						var eventHtml = $(this).children("tbody").children(".r1").children(".description").html();
						var eventText = $(this).children("tbody").children(".r1").children(".description").text();
						var eventNormText = $(this).children("tbody").children(".r1").children(".description").text().replace(/\r/g, "").replace(/\n/g, " ");
						var eventLink = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").attr("href");

						var eventObj = {title: eventTitle, course: eventCourse, text: eventText, normText: eventNormText, html: eventHtml, link: eventLink};

						respObj.events.push(eventObj);
					});

		doneFunc(respObj);
	});
};

window.coursesLib.getUpcomingEvents = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/calendar/view.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.events = [];

		$response.children("#page-content")
					.children("#region-main-box")
					.children("#region-post-box")
					.children("#region-main-wrap")
					.children("#region-main")
					.children(".region-content")
					.children(".maincalendar")
					.children(".heightcontainer")
					.children(".eventlist")
					.children(".event").each(function() {
						// !!!
						var eventTitle = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").text().replace(/\s{2,}/g, " ");
						var eventCourse = $(this).children("tbody").children(".r0").children(".topic").children(".course").children("a").text().replace(/\s{2,}/g, " ");
						var eventHtml = $(this).children("tbody").children(".r1").children(".description").html();
						var eventText = $(this).children("tbody").children(".r1").children(".description").text();
						var eventNormText = $(this).children("tbody").children(".r1").children(".description").text().replace(/\r/g, "").replace(/\n/g, " ");
						var eventLink = $(this).children("tbody").children(".r0").children(".topic").children(".referer").children("a").attr("href");

						var eventObj = {title: eventTitle, course: eventCourse, text: eventText, normText: eventNormText, html: eventHtml, link: eventLink};

						respObj.events.push(eventObj);
					});

		doneFunc(respObj);
	});
};

window.coursesLib.getProfile = function(doneFunc) {
	$.get(window.coursesLib.baseUrl + "/user/profile.php", function (resText) {
		var $response = $(resText);
		var respObj = {};

		respObj.fullName = $response.find(".userprofile").children("h2").text();
		respObj.firstName = respObj.fullName.split(' ')[0];
		respObj.lastName = respObj.fullName.split(' ')[1];
		respObj.avatarUrl = $response.find(".userpicture").attr("src");

		doneFunc(respObj);
	});
};

console.log("CoursesLib ready!");<|endoftext|>


<commit_before>// MODULE DEPENDENCIES
require('colors')

var express = require('express'),
  app = module.exports = express(),
  server = require('http').createServer(app),
  tesla, port;

// REQUIRE CONFIG FILES
require('./config/_settings')(app); // MAIN
require('./config/environment')(app); // ENVIRONMENT SPECIFIC

// LOAD TESLA LIB
tesla = require('./lib/tesla')(app);

tesla.log(' ');
tesla.log(' ');
tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # # #'.rainbow);
tesla.log('    > > > FIRING UP THE '.white + 'TESLA'.red + ' SERVER. GET HAPPY! < < < '.white);
tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # # #'.rainbow);
tesla.log(' ');

// REQUIRE ADDITIONAL CONFIG FILES
require('./config/express')(app, tesla); //express settings
require('./app/routes/_setup')(app, tesla); // routes

// START THE APP BY LISTEN ON <PORT>
port = process.env.PORT || app.config.port;

server.listen(port, function(err) {

  tesla.log(' ');
  tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # #'.green);
  tesla.log('        IT\'S ALIVE!'.white + ' TESLA'.red + ' IS UP AND RUNNING.'.white);
  tesla.log('   POINT YOUR BROWSER TO: '.grey + app.site.url.white);
  tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # #'.green);

});

// EXPOSE APP
exports = module.exports = app;<commit_msg>set default node env<commit_after>process.env.NODE_ENV = process.env.NODE_ENV || 'production';

// MODULE DEPENDENCIES
require('colors')

var express = require('express'),
  app = module.exports = express(),
  server = require('http').createServer(app),
  tesla, port;

// REQUIRE CONFIG FILES
require('./config/_settings')(app); // MAIN
require('./config/environment')(app); // ENVIRONMENT SPECIFIC

// LOAD TESLA LIB
tesla = require('./lib/tesla')(app);

tesla.log(' ');
tesla.log(' ');
tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # # #'.rainbow);
tesla.log('    > > > FIRING UP THE '.white + 'TESLA'.red + ' SERVER. GET HAPPY! < < < '.white);
tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # # #'.rainbow);
tesla.log(' ');

// REQUIRE ADDITIONAL CONFIG FILES
require('./config/express')(app, tesla); //express settings
require('./app/routes/_setup')(app, tesla); // routes

// START THE APP BY LISTEN ON <PORT>
port = process.env.PORT || app.config.port;

server.listen(port, function(err) {

  tesla.log(' ');
  tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # #'.green);
  tesla.log('        IT\'S ALIVE!'.white + ' TESLA'.red + ' IS UP AND RUNNING.'.white);
  tesla.log('   POINT YOUR BROWSER TO: '.grey + app.site.url.white);
  tesla.log('# # # # # # # # # # # # # # # # # # # # # # # # # # # #'.green);

});

// EXPOSE APP
exports = module.exports = app;<|endoftext|>


<commit_before>var bindable = require("bindable"),
_            = require("underscore"),
type         = require("type-component"),
paperclip    = require("mojo-paperclip"),
nofactor     = require("nofactor"),
protoclass   = require("protoclass"),
poolpaerty   = require("poolparty"),
pools        = require("./pools"),
Animator     = require("./animator"),
RegisteredClasses = require("./registeredClasses"),

defaultComponents = require("./plugins/defaultComponents"),
decorators        = require("./plugins/decor");

/**
 * Main entry point to your application. This is where everything is initialized.
 *
 * @module mojo
 * @class Application
 * @param {Object} options
 */

function Application (options) {
  if (!options) options = {};

  Application.parent.call(this, this);

  this.nodeFactory = options.nodeFactory || nofactor["default"];
  this.models      = new bindable.Object();
  this.fake        = !!options.fake;

  /**
   * List of registered model classes
   * @property modelClasses
   * @type RegisteredClasses
   */

  this.modelClasses = new RegisteredClasses(this);

  /**
   * List of registered view classes
   * @property viewClasses
   * @type RegisteredClasses
   */

  this.viewClasses = new RegisteredClasses(this);

  // makes changes to the application view state.
  this._animator = new Animator(this);

  // default plugins to use for every mojo application
  this.use(defaultComponents, decorators, paperclip, pools.plugin);
}

protoclass(bindable.Object, Application, {

  /**
   * Plugins to use for the mojo application.
   *
   * @method use
   * @param {Function} plugins... must be defined as `function (app) { }`
   */

  use: function (test) {

    // simple impl - go through each arg and pass self ref
    for(var i = 0, n = arguments.length; i < n; i++) {
      arguments[i](this);
    }

    return this;
  },

  /**
   * DEPRECATED
   */

  getViewClass: function (name) {
    return this.viewClasses.get(name);
  },

  registerViewClass: function (name, clazz) {
    return this.viewClasses.add(name, clazz);
  },

  createView: function (name, options) {
    return this.viewClasses.create(name, options);
  },

  /**
   * DEPRECATED
   */

  getModelClass: function (name) {
    return this.modelClasses.get(name);
  },
  registerModelClass: function (name, clazz) {
    return this.modelClasses.add(name, clazz);
  },
  createModel: function (name, options) {
    return this.modelClasses.create(name, options);
  },

  /**
   * Runs `update()` on requestAnimationFrame. Used whenever the UI changes.
   * @method animate
   * @param {Object} animatable Must have `update()` defined.
   * @see Animator
   */

  animate: function (animatable) {
    this._animator.animate(animatable);
  }
});

module.exports = Application;<commit_msg>added comments<commit_after>var bindable = require("bindable"),
_            = require("underscore"),
type         = require("type-component"),
paperclip    = require("mojo-paperclip"),
nofactor     = require("nofactor"),
protoclass   = require("protoclass"),
poolpaerty   = require("poolparty"),
pools        = require("./pools"),
Animator     = require("./animator"),
RegisteredClasses = require("./registeredClasses"),

defaultComponents = require("./plugins/defaultComponents"),
decorators        = require("./plugins/decor");

/**
 * Main entry point to your application. This is where everything is initialized.
 *
 * @module mojo
 * @class Application
 * @param {Object} options
 * @extends BindableObject
 */

function Application (options) {
  if (!options) options = {};

  Application.parent.call(this, this);

  /**
   * The node factory to use. Changes depending on the platform.
   * @property nodeFactory
   * @type NodeFactory
   */

  this.nodeFactory = options.nodeFactory || nofactor["default"];

  /**
   * Where all the instantiated models live.
   * @property models
   * @type BindableObject
   */

  this.models      = new bindable.Object();

  /**
   * TRUE if testing mode
   * @property fake
   * @type {Boolean}
   */

  this.fake        = !!options.fake;

  /**
   * List of registered model classes
   * @property modelClasses
   * @type RegisteredClasses
   */

  this.modelClasses = new RegisteredClasses(this);

  /**
   * List of registered view classes
   * @property viewClasses
   * @type RegisteredClasses
   */

  this.viewClasses = new RegisteredClasses(this);

  // makes changes to the application view state.
  this._animator = new Animator(this);

  // default plugins to use for every mojo application
  this.use(defaultComponents, decorators, paperclip, pools.plugin);
}

protoclass(bindable.Object, Application, {

  /**
   * Plugins to use for the mojo application.
   *
   * @method use
   * @param {Function} plugins... must be defined as `function (app) { }`
   */

  use: function (test) {

    // simple impl - go through each arg and pass self ref
    for(var i = 0, n = arguments.length; i < n; i++) {
      arguments[i](this);
    }

    return this;
  },

  /**
   * DEPRECATED
   */

  getViewClass: function (name) {
    return this.viewClasses.get(name);
  },

  registerViewClass: function (name, clazz) {
    return this.viewClasses.add(name, clazz);
  },

  createView: function (name, options) {
    return this.viewClasses.create(name, options);
  },

  /**
   * DEPRECATED
   */

  getModelClass: function (name) {
    return this.modelClasses.get(name);
  },
  registerModelClass: function (name, clazz) {
    return this.modelClasses.add(name, clazz);
  },
  createModel: function (name, options) {
    return this.modelClasses.create(name, options);
  },

  /**
   * Runs `update()` on requestAnimationFrame. Used whenever the UI changes.
   * @method animate
   * @param {Object} animatable Must have `update()` defined.
   * @see Animator
   */

  animate: function (animatable) {
    this._animator.animate(animatable);
  }
});

module.exports = Application;<|endoftext|>


<commit_before>/*!
 * --------------------------------------------------------------------
 *  SIMPLE TEXT SELECTION LIBRARY FOR ONLINE TEXT EDITING (2016-02-15)
 * --------------------------------------------------------------------
 *  https://github.com/tovic/simple-text-editor-library
 * --------------------------------------------------------------------
 *
 *    Author : Taufik Nurrohman
 *    URL    : http://latitudu.com
 *
 * --------------------------------------------------------------------
 *
 */

var Editor=function(e){function t(e){return void 0!==e}function n(e){return"object"==typeof e}function r(e){return"function"==typeof e}var a=this,o=document,l=[];a.keys={8:"backspace",9:"tab",13:"enter",16:"shift",17:"control",18:"alt",19:"pause",20:"capslock",27:"escape",33:"pageup",34:"pagedown",37:"arrowleft",38:"arrowup",39:"arrowright",40:"arrowdown",44:"printscreen",45:"insert",46:"delete",91:"os",93:"contextmenu",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12",48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",32:" ",59:[";",":"],61:["=","+"],173:["-","_"],188:[",","<"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']},a.index={undo:0,redo:0},a.area=t(e)?e:o.getElementsByTagName("textarea")[0],a.escape=/([!$^*\(\)\-=+\[\]\{\}\\|:<>,.\/?])/g,l[a.index.undo]={value:a.area.value,start:0,end:0},a.key=function(e,r){var o=e.keyCode||e.which,l=null;t(e.key)?l=e.key.toLowerCase():(l=a.keys[o]||null,n(l)&&(l=e.shiftKey?l[1]||l[0]:l[0]));var c={alternate:"alt",option:"alt",ctrl:"control",cmd:"control",command:"control",meta:"control",context:"contextmenu","return":"enter",ins:"insert",del:"delete",esc:"escape",home:"pageup",end:"pagedown",left:"arrowleft",up:"arrowup",right:"arrowright",down:"arrowdown",space:" "};return r=c[r.toLowerCase()]||r.toLowerCase()||null,r?l===r:l},a.selection=function(){var e=a.area.value.replace(/\r/g,""),t=a.area.selectionStart,n=a.area.selectionEnd,r={start:t,end:n,value:e.substring(t,n),before:e.substring(0,t),after:e.substring(n)};return r},a.select=function(e,n,l){var c=o.documentElement.scrollTop,u=o.body.scrollTop,s=a.area.scrollTop,d=a.selection();a.area.focus(),t(e)||(e=d.start,n=d.end),t(n)||(n=e),(r(n)||n===!0)&&(l=n,n=e),a.area.setSelectionRange(e,n),o.documentElement.scrollTop=c,o.body.scrollTop=u,a.area.scrollTop=s,l===!0?a.updateHistory():r(l)&&l()},a.replace=function(e,t,n){var r=a.selection(),o=r.start,l=(r.end,r.value.replace(e,t));a.area.value=r.before+l+r.after,a.select(o,o+l.length,n||!0)},a.insert=function(e,t){{var n=a.selection(),r=n.start;n.end}a.area.value=n.before+e+n.after,a.select(r+e.length,t||!0)},a.wrap=function(e,t,n,r){var o=a.selection(),l=o.value,c=o.before,u=o.after;r?a.replace(/^([\s\S]*?)$/,e+"$1"+t):(a.area.value=c+e+l+t+u,a.select((c+e).length,(c+e+l).length,n||!0))},a.indent=function(e,t){var n=a.selection();n.value.length>0?a.replace(/(^|\n)([^\n])/g,"$1"+e+"$2",t):(a.area.value=n.before+e+n.value+n.after,a.select(n.start+e.length,t||!0))},a.outdent=function(e,t,n){var r=a.selection(),o=n?e:e.replace(a.escape,"\\$1");if(r.value.length>0)a.replace(RegExp("(^|\n)"+o,"g"),"$1",t);else{var l=r.before.replace(RegExp(o+"$"),"");a.area.value=l+r.value+r.after,a.select(l.length,t||!0)}},a.callHistory=function(e){return e?l[e]:l},a.updateHistory=function(e,n){var r=a.selection(),o=t(e)?e:{value:a.area.value,start:r.start,end:r.end};a.index.undo++,l[n?n:a.index.undo]=o},a.undo=function(e){a.index.undo>0?a.index.undo--:a.index.undo=0,a.index.redo=a.index.undo;var t=l[a.index.undo];a.area.value=t.value,a.select(t.start,t.end,e)},a.redo=function(e){a.index.redo<l.length-1?a.index.redo++:a.index.redo=l.length-1,a.index.undo=a.index.redo;var t=l[a.index.redo];a.area.value=t.value,a.select(t.start,t.end,e)}};<commit_msg>ditto<commit_after>/*!
 * --------------------------------------------------------------------
 *  SIMPLE TEXT SELECTION LIBRARY FOR ONLINE TEXT EDITING (2016-02-15)
 * --------------------------------------------------------------------
 *  https://github.com/tovic/simple-text-editor-library
 * --------------------------------------------------------------------
 *
 *    Author : Taufik Nurrohman
 *    URL    : http://latitudu.com
 *
 * --------------------------------------------------------------------
 *
 */

var Editor=function(e){function t(e){return void 0!==e}function n(e){return"object"==typeof e}function r(e){return"function"==typeof e}var a=this,o=document,l=[];a.keys={8:"backspace",9:"tab",13:"enter",16:"shift",17:"control",18:"alt",19:"pause",20:"capslock",27:"escape",33:"pageup",34:"pagedown",37:"arrowleft",38:"arrowup",39:"arrowright",40:"arrowdown",44:"printscreen",45:"insert",46:"delete",91:"os",93:"contextmenu",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12",48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",32:" ",59:[";",":"],61:["=","+"],173:["-","_"],188:[",","<"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']},a.index={undo:0,redo:0},a.area=t(e)?e:o.getElementsByTagName("textarea")[0],a.escape=/([!$^*\(\)\-=+\[\]\{\}\\|:<>,.\/?])/g,l[a.index.undo]={value:a.area.value,start:0,end:0},a.key=function(e,r){var o=e.keyCode||e.which,l=null;t(e.key)?l=e.key.toLowerCase():(l=a.keys[o]||null,n(l)&&(l=e.shiftKey?l[1]||l[0]:l[0]));var c={alternate:"alt",option:"alt",ctrl:"control",cmd:"control",command:"control",meta:"control",context:"contextmenu","return":"enter",ins:"insert",del:"delete",esc:"escape",home:"pageup",end:"pagedown",left:"arrowleft",up:"arrowup",right:"arrowright",down:"arrowdown",space:" "};return t(r)?l===(c[r.toLowerCase()]||r.toLowerCase()):l},a.selection=function(){var e=a.area.value.replace(/\r/g,""),t=a.area.selectionStart,n=a.area.selectionEnd,r={start:t,end:n,value:e.substring(t,n),before:e.substring(0,t),after:e.substring(n)};return r},a.select=function(e,n,l){var c=o.documentElement.scrollTop,u=o.body.scrollTop,s=a.area.scrollTop,d=a.selection();a.area.focus(),t(e)||(e=d.start,n=d.end),t(n)||(n=e),(r(n)||n===!0)&&(l=n,n=e),a.area.setSelectionRange(e,n),o.documentElement.scrollTop=c,o.body.scrollTop=u,a.area.scrollTop=s,l===!0?a.updateHistory():r(l)&&l()},a.replace=function(e,t,n){var r=a.selection(),o=r.start,l=(r.end,r.value.replace(e,t));a.area.value=r.before+l+r.after,a.select(o,o+l.length,n||!0)},a.insert=function(e,t){{var n=a.selection(),r=n.start;n.end}a.area.value=n.before+e+n.after,a.select(r+e.length,t||!0)},a.wrap=function(e,t,n,r){var o=a.selection(),l=o.value,c=o.before,u=o.after;r?a.replace(/^([\s\S]*?)$/,e+"$1"+t):(a.area.value=c+e+l+t+u,a.select((c+e).length,(c+e+l).length,n||!0))},a.indent=function(e,t){var n=a.selection();n.value.length>0?a.replace(/(^|\n)([^\n])/g,"$1"+e+"$2",t):(a.area.value=n.before+e+n.value+n.after,a.select(n.start+e.length,t||!0))},a.outdent=function(e,t,n){var r=a.selection(),o=n?e:e.replace(a.escape,"\\$1");if(r.value.length>0)a.replace(RegExp("(^|\n)"+o,"g"),"$1",t);else{var l=r.before.replace(RegExp(o+"$"),"");a.area.value=l+r.value+r.after,a.select(l.length,t||!0)}},a.callHistory=function(e){return e?l[e]:l},a.updateHistory=function(e,n){var r=a.selection(),o=t(e)?e:{value:a.area.value,start:r.start,end:r.end};a.index.undo++,l[n?n:a.index.undo]=o},a.undo=function(e){a.index.undo>0?a.index.undo--:a.index.undo=0,a.index.redo=a.index.undo;var t=l[a.index.undo];a.area.value=t.value,a.select(t.start,t.end,e)},a.redo=function(e){a.index.redo<l.length-1?a.index.redo++:a.index.redo=l.length-1,a.index.undo=a.index.redo;var t=l[a.index.redo];a.area.value=t.value,a.select(t.start,t.end,e)}};<|endoftext|>


<commit_before>var WebSocketServer = require("ws").Server
var http = require('http');
var express = require('express');
var exphbs  = require('express-handlebars');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();
var server;
var ws;

mongoose.connect(process.env.MONGOLAB_URI);

var db = mongoose.connection;
var Gif;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {

    var gifSchema = mongoose.Schema({
        paths: {
            preview: String,
            high_resolution: String
        },
        hearts: Number
    });

    Gif = mongoose.model('gifs', gifSchema);

    var seedData = [
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-adrian-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-adrian.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-arash-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-arash.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-jamie-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-jamie.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-chad-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-chad.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-chad-creepy-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-chad-creepy.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animationadrian-spin-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animationadrian-spin.gif'
            },
            hearts: 0
        })
    ];

    // Seed Gifs if emmpty
    Gif.find({}, function(err, gifs) {

        if (!gifs.length) {
            seedData.forEach(function (elem) {
                elem.save();
            });
        }

    });

});

var hbs = exphbs.create({
    defaultLayout: '_layout',
    layoutsDir: 'dist/views/shared/',
    partialsDir: 'dist/views/shared/partials/',
    extname: '.hbs'
});

app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
app.set('port', (process.env.PORT || 3000));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

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

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

    var data,
        criticalCss = process.env.NODE_ENV === 'production' ? fs.readFileSync('./static/css/critical.css') : '/* This is empty in dev */';

    Gif.find({}, function(err, gifs) {

        data = gifs.reverse() || [];
        res.render('../dist/views/home', {title: 'HOME', data : data, criticalCss: criticalCss});

    });

});

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

    var data,
        criticalCss = process.env.NODE_ENV === 'production' ? fs.readFileSync('./static/css/critical.css') : '/* This is empty in dev */';

    Gif.find({}, function(err, gifs) {

        data = gifs || [];

        Gif.findById(req.params.id, function (err, gif) {

            try {
                res.render('../dist/views/home', {title: 'HOME', id : gif._id, paths : gif.paths, data : data, criticalCss: criticalCss});
            } catch (err) {
                res.status(404).render('../dist/views/404', {title: '404'});
            }

        });

    });

});

app.post('/api/heart', function (req, res) {
    var id = req.body.id,
        action = req.body.action;

    Gif.findById(id, function (err, gif) {

        if (err) {
            res.send({ success: false, error: err });
        }

        gif.hearts = action === 'heart' ? gif.hearts + 1 : gif.hearts - 1;
        gif.save(function (err) {
            if (err) {
                res.send({ success: false, error: err });
            }
            res.send({ success: true, hearts: gif.hearts });
        });

    });
});

server = http.createServer(app);
server.listen(app.get('port'));

ws = new WebSocketServer({server: server})
console.log("websocket server created")

ws.on("connection", function(socket) {
  var id = setInterval(function() {
    socket.send(JSON.stringify(new Date()), function() {  })
  }, 1000)

  console.log("websocket connection open")

  socket.on("close", function() {
    console.log("websocket connection close")
    clearInterval(id)
  })
})
<commit_msg>Websocket events<commit_after>var WebSocketServer = require("ws").Server
var http = require('http');
var express = require('express');
var exphbs  = require('express-handlebars');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();
var server;
var ws;

mongoose.connect(process.env.MONGOLAB_URI);

var db = mongoose.connection;
var Gif;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {

    var gifSchema = mongoose.Schema({
        paths: {
            preview: String,
            high_resolution: String
        },
        hearts: Number
    });

    Gif = mongoose.model('gifs', gifSchema);

    var seedData = [
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-adrian-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-adrian.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-arash-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-arash.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-jamie-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-jamie.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-chad-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-chad.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animation-chad-creepy-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animation-chad-creepy.gif'
            },
            hearts: 0
        }),
        new Gif({
            paths: {
                preview: 'https://fotomat.herokuapp.com/img/gifs/animationadrian-spin-preview.gif',
                high_resolution: 'https://fotomat.herokuapp.com/img/gifs/animationadrian-spin.gif'
            },
            hearts: 0
        })
    ];

    // Seed Gifs if emmpty
    Gif.find({}, function(err, gifs) {

        if (!gifs.length) {
            seedData.forEach(function (elem) {
                elem.save();
            });
        }

    });

});

var hbs = exphbs.create({
    defaultLayout: '_layout',
    layoutsDir: 'dist/views/shared/',
    partialsDir: 'dist/views/shared/partials/',
    extname: '.hbs'
});

app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
app.set('port', (process.env.PORT || 3000));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

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

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

    var data,
        criticalCss = process.env.NODE_ENV === 'production' ? fs.readFileSync('./static/css/critical.css') : '/* This is empty in dev */';

    Gif.find({}, function(err, gifs) {

        data = gifs.reverse() || [];
        res.render('../dist/views/home', {title: 'HOME', data : data, criticalCss: criticalCss});

    });

});

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

    var data,
        criticalCss = process.env.NODE_ENV === 'production' ? fs.readFileSync('./static/css/critical.css') : '/* This is empty in dev */';

    Gif.find({}, function(err, gifs) {

        data = gifs || [];

        Gif.findById(req.params.id, function (err, gif) {

            try {
                res.render('../dist/views/home', {title: 'HOME', id : gif._id, paths : gif.paths, data : data, criticalCss: criticalCss});
            } catch (err) {
                res.status(404).render('../dist/views/404', {title: '404'});
            }

        });

    });

});

app.post('/api/heart', function (req, res) {
    var id = req.body.id,
        action = req.body.action;

    Gif.findById(id, function (err, gif) {

        if (err) {
            res.send({ success: false, error: err });
        }

        gif.hearts = action === 'heart' ? gif.hearts + 1 : gif.hearts - 1;
        gif.save(function (err) {
            if (err) {
                res.send({ success: false, error: err });
            }
            res.send({ success: true, hearts: gif.hearts });
        });

    });
});

server = http.createServer(app);
server.listen(app.get('port'));

ws = new WebSocketServer({server: server})
console.log("websocket server created")

ws.on("connection", function(socket) {

    console.log("websocket connection open");

    ws.on('message', function(data, flags) {
        var parsed = JSON.parse(data);

        console.log(parsed);

        if (parsed.type === 'RFID') {
            ws.broadcast(data);
        }
    });

    socket.on("close", function() {
        console.log("websocket connection close")
    });
})

ws.broadcast = function broadcast(data) {
    ws.clients.forEach(function each(client) {
        client.send(data);
    });
};
<|endoftext|>


<commit_before>// Endowments UI
// Michael Thomas, 2014

// Signal Hook
var EndowmentsUI = {
	start : new signals.Signal()
};

// Add Listener
EndowmentsUI.start.add(onStart);

// (Re)Start Endowments UI
function onStart() {
	WebUI.startLoad();
	// Load Featured Endowments
	fetchFeaturedEndowments(function() {
		// Fetch Subscribed Endowments
		fetchSubscribedEndowments(function() {
			WebUI.stopLoad();
		});
	});
}

// Get Subscribed Endowments
function fetchSubscribedEndowments(callback) {
	$.ajax({
	  url: 'https://api.giv2giv.org/api/donors/subscriptions.json',
	  method: 'GET',
	}).done(function(data) {
  	log(data);
  	// did we get anything
  	if(data.length == 0) {
  		// Display not found card
  		$("#sub-not-found-card").parent().removeClass('hide');
  	} else {
  		// Parse Results Here
  		$.each(data, function(k, v) {
  			var i = v[0];
  			// Get Object
  			var ii = Object.keys(i);
  			var sub = i[ii[0]];
  			log(sub);
  			// Now Build A Card
  			// Start Body & Name
  			var body = "

"+sub.endowment_name+"
";
  			// Donation Amount
  			body += "
Donation Amount: $"+sub.endowment_donation_amount+" ("+sub.endowment_donation_type+")
";
  			// # of Donors
  			if(sub.endowment_donor_count == 1) {
  				var donor_string = "donor";
  			} else {
  				var donor_string = "donors";
  			}
  			body += "
"+sub.endowment_donor_count+" "+donor_string+".
";
  			// Donor Balance
  			body += "
My Balance: $"+sub.endowment_donor_current_balance+".
";
  			body += "
"+sub.endowment_donor_total_donations+" donations.
";
  			// Endowment Balance & Donations
  			body += "
Endowment Balance: $"+sub.endowment_total_balance+".
";
  			body += "
"+sub.endowment_total_donations+" total donations.
";
  			// Action Buttons
  			var actions = "
<button class='btn btn-success'>More Details</button> <button class='btn btn-danger'>Unsubscribe</button>
";
  			var card_html = "

"+body+"
"+actions+"

";
  			// Add the Card
  			var $card = $("#sub-endowments").append(card_html);
  		});
  	}
	}).fail(function(data) {
	  log(data);
	  growlError("Opps! An error occured while loading your Subscribed Endowments.");
	}).always(function(data) {
		// Callbacks
		if(typeof callback === "function") {
    	// Call it, since we have confirmed it is callable
      callback();
    }
	});
}

// Get Featured Endowments
function fetchFeaturedEndowments(callback) {
	$.ajax({
	  url: 'https://api.giv2giv.org/api/endowment.json',
	  method: 'GET',
	  data: {
	    page: '1',
	    per_page: '10'
	  }
	}).done(function(data) {
  	if(data.message == "Not found") {
  		// Display not found card
  		$("#featured-not-found-card").removeClass('hide');
  	} else {
  		// Display results
  		log(data);
  	}
  }).fail(function(data) {
  	log(data);
  	growlError("Opps! An error occured while loading the Featured Endowments.");
	}).always(function() {
		// Callbacks
		if(typeof callback === "function") {
    	// Call it, since we have confirmed it is callable
      callback();
    }
	});
}<commit_msg>Fix number format in endowments.js for sub cards.<commit_after>// Endowments UI
// Michael Thomas, 2014

// Signal Hook
var EndowmentsUI = {
	start : new signals.Signal()
};

// Add Listener
EndowmentsUI.start.add(onStart);

// (Re)Start Endowments UI
function onStart() {
	WebUI.startLoad();
	// Load Featured Endowments
	fetchFeaturedEndowments(function() {
		// Fetch Subscribed Endowments
		fetchSubscribedEndowments(function() {
			WebUI.stopLoad();
		});
	});
}

// Get Subscribed Endowments
function fetchSubscribedEndowments(callback) {
	$.ajax({
	  url: 'https://api.giv2giv.org/api/donors/subscriptions.json',
	  method: 'GET',
	}).done(function(data) {
  	log(data);
  	// did we get anything
  	if(data.length == 0) {
  		// Display not found card
  		$("#sub-not-found-card").parent().removeClass('hide');
  	} else {
  		// Parse Results Here
  		$.each(data, function(k, v) {
  			var i = v[0];
  			// Get Object
  			var ii = Object.keys(i);
  			var sub = i[ii[0]];
  			log(sub);
  			// Now Build A Card
  			// Start Body & Name
  			var body = "

"+sub.endowment_name+"
";
  			// Donation Amount
  			body += "
Donation Amount: $"+sub.endowment_donation_amount.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')+" ("+sub.endowment_donation_type+")
";
  			// # of Donors
  			if(sub.endowment_donor_count == 1) {
  				var donor_string = "donor";
  			} else {
  				var donor_string = "donors";
  			}
  			body += "
"+sub.endowment_donor_count+" "+donor_string+".
";
  			// Donor Balance
  			body += "
My Balance: $"+sub.endowment_donor_current_balance.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')+".
";
  			body += "
"+sub.endowment_donor_total_donations+" donations.
";
  			// Endowment Balance & Donations
  			body += "
Endowment Balance: $"+sub.endowment_total_balance.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')+".
";
  			body += "
"+sub.endowment_total_donations+" total donations.
";
  			// Action Buttons
  			var actions = "
<button class='btn btn-success'>More Details</button> <button class='btn btn-danger'>Unsubscribe</button>
";
  			var card_html = "

"+body+"
"+actions+"

";
  			// Add the Card
  			var $card = $("#sub-endowments").append(card_html);
  		});
  	}
	}).fail(function(data) {
	  log(data);
	  growlError("Opps! An error occured while loading your Subscribed Endowments.");
	}).always(function(data) {
		// Callbacks
		if(typeof callback === "function") {
    	// Call it, since we have confirmed it is callable
      callback();
    }
	});
}

// Get Featured Endowments
function fetchFeaturedEndowments(callback) {
	$.ajax({
	  url: 'https://api.giv2giv.org/api/endowment.json',
	  method: 'GET',
	  data: {
	    page: '1',
	    per_page: '10'
	  }
	}).done(function(data) {
  	if(data.message == "Not found") {
  		// Display not found card
  		$("#featured-not-found-card").removeClass('hide');
  	} else {
  		// Display results
  		log(data);
  	}
  }).fail(function(data) {
  	log(data);
  	growlError("Opps! An error occured while loading the Featured Endowments.");
	}).always(function() {
		// Callbacks
		if(typeof callback === "function") {
    	// Call it, since we have confirmed it is callable
      callback();
    }
	});
}<|endoftext|>


<commit_before>var express = require('express');
var http = require('http');
var app;
var router;
var server;
var routeData = {};
var bodyParser = require('body-parser')

function start(options, done) {
  app = express();
    app.use(bodyParser.json());
  app.use(router);

  server = app.listen(options.port, function() {
    done();
  });
}

function close(done) {
  if (server) {
    server.close(done);
  } else {
    done();
  }
}

function defineRoute(options) {
  router = express.Router();
  if (options.verb && options.verb == 'POST') {
    router.post(options.route, function(req, res) {

      routeData[options.route] = req.body;
      if (options.statusCode) {
        res.sendStatus(options.statusCode);
      } else {
        res.sendStatus(200);
      }
    });
  } else {
    router.get(options.route, function(req, res) {
      if (options.statusCode) {
        res.sendStatus(options.statusCode);
      } else {
        res.sendStatus(200);
      }
    });
  }
}

function received(route) {
  return routeData[route];
}

module.exports.start = start;
module.exports.close = close;
module.exports.defineRoute = defineRoute;
module.exports.received = received;
<commit_msg>Remove unnecessary callback<commit_after>var express = require('express');
var http = require('http');
var app;
var router;
var server;
var routeData = {};
var bodyParser = require('body-parser')

function start(options, done) {
  app = express();
  app.use(bodyParser.json());
  app.use(router);

  server = app.listen(options.port, done);
}

function close(done) {
  if (server) {
    server.close(done);
  } else {
    done();
  }
}

function defineRoute(options) {
  router = express.Router();
  if (options.verb && options.verb == 'POST') {
    router.post(options.route, function(req, res) {

      routeData[options.route] = req.body;
      if (options.statusCode) {
        res.sendStatus(options.statusCode);
      } else {
        res.sendStatus(200);
      }
    });
  } else {
    router.get(options.route, function(req, res) {
      if (options.statusCode) {
        res.sendStatus(options.statusCode);
      } else {
        res.sendStatus(200);
      }
    });
  }
}

function received(route) {
  return routeData[route];
}

module.exports.start = start;
module.exports.close = close;
module.exports.defineRoute = defineRoute;
module.exports.received = received;
<|endoftext|>


<commit_before>'use strict';

/*
 * Backchannel server allows workers to stream messages back to the Node server
 * in a line-buffered way. Uses SSL.
 */

var _ = require('lodash');
var async = require('async');
var jobs = require('./jobs');
var common = require('./common');
var utils = require('./utils');
var config = require('./config');
var models = require('./models');

var Job = models.Job;
var User = models.User;
var Project = models.Project;

function striderJson(provider, project, ref, done) {
  function finished(err, contents) {
    if (err || !contents) return done(err);

    var data = {};

    try {
      data = JSON.parse(contents);
    } catch (e) {
      console.warn('Strider config is invalid JSON for', project, ref);
      console.log(contents);
    }

    done(undefined, data);
  }

  if (!provider.hosted) {
    return provider.getFile('strider.json', ref, project.provider.config, project, finished);
  }

  var account = project.creator.account(project.provider.id, project.provider.account);

  provider.getFile('strider.json', ref, account, project.provider.config, project, finished);
}

// Prepare the job for execution, save to database, and fire off a `job.new` event.
//
// job is expected to be populated with:
// - a trigger
// - a ref
// - the project name
// - the user id (if applicable)
// - type
// - created timestamp
// XXX: should this function go in a different file? idk. We'll
//      definitely move it around when we make strider OO.
function prepareJob(emitter, job) {
  Project.findOne({name: job.project}).populate('creator').exec(function (err, project) {
    if (err || !project) return console.error('job.prepare - failed to get project', job.project, err)
    // ok so the project is real, we can go ahead and save this job
    var provider = common.extensions.provider[project.provider.id];

    if (!provider) {
      return console.error('job.prepare - provider not found for project', job.project, project.provider.id);
    }

    Job.create(job, function (err, mjob) {
      if (err) return console.error('job.prepare - failed to save job', job, err);

      var jjob = mjob.toJSON();

      jjob.project = project;
      jjob.providerConfig = project.provider.config;
      jjob.fromStriderJson = true;

      striderJson(provider, project, job.ref, function (err, config) {
        if (err) {
          if (err.status === 403 || err.statusCode === 403) {
            console.log('job.prepare - access to strider.json is forbidden, skipping config merge');
            config = {};
            jjob.fromStriderJson = false;
          } else if (err.status === 404 || err.statusCode === 404) {
            console.log('job.prepare - strider.json not found, skipping config merge');
            config = {};
            jjob.fromStriderJson = false;
          } else {
            return console.error('job.prepare - error opening/processing project\'s `strider.json` file: ', err);
          }
        }

        var branch = project.branch(job.ref.branch || 'master');

        if (!branch) {
          return console.error('job.prepare - branch not found', job.ref.branch || 'master', project.name);
        }

        branch = branch.mirror_master ? project.branch('master') : branch;
        jjob.providerConfig = _.extend({}, project.provider.config, config.provider || {});
        config.runner = branch.runner;

        if (config) {
          delete config.provider;
          config = utils.mergeConfigs(branch, config);
        }

        emitter.emit('job.new', jjob, config);

        if (!mjob.runner) mjob.runner = {};

        mjob.runner.id = config.runner.id;
        mjob.save();
      })
    })
  })
}

function BackChannel(emitter, ws) {
  this.ws = ws;
  this.users = {};
  this.public = {};
  this.waiting = {};

  emitter.on('job.prepare', prepareJob.bind(null, emitter));
  emitter.on('job.new', this.newJob.bind(this));
  emitter.on('browser.update', this.onUpdate.bind(this));
  emitter.on('job.done', this.jobDone.bind(this, emitter));
}

BackChannel.prototype = {
  send: function (project, event, args) {
    if (this.users[project]) {
      this.ws.send(this.users[project], [event, args, 'yours'])
    }
    if (this.public[project]) {
      this.ws.sendPublic(this.users[project], [event, args, 'public'])
    }
  },

  newJob: function (job) {
    var self = this;
    var name = job.project.name;

    this.waiting[name] = [];
    this.public[name] = job.project.public;

    async.parallel({
      collaborators: function (paraCallback) {
        User.collaborators(name, 0, function (err, users) {
          paraCallback(err, users);
        });
      },

      admins: function (paraCallback) {
        User.admins(paraCallback);
      }
    }, function (err, users) {
      if (err) return console.error('new job: Failed to query for users')
      if (!users.collaborators) return console.error('new job: no users found')
      self.users[name] = []

      users.collaborators.forEach(function (user) {
        self.users[name].push(user._id.toString())
      })
      // also send to system admins
      users.admins.forEach(function (user) {
        self.users[name].push(user._id.toString())
      })

      // Admins maybe collaborators, so unique the array
      self.users[name] = _.uniq(self.users[name])

      var njob = jobs.small(job)

      njob.project = utils.sanitizeProject(job.project)
      self.send(name, 'job.new', [njob])

      self.waiting[name].forEach(function (item) {
        self.send.apply(self, [name].concat(item))
      })

      delete self.waiting[name]
    });
  },
  // [project name, event name, [list of arguments]]
  onUpdate: function (project, event, args) {
    if (this.waiting[project]) {
      return this.waiting[project].push([event, args])
    }
    this.send(project, event, args)
    if (event === 'job.status.started') {
      Job.findById(args[0], function (err, job) {
        if (err) return console.error('[backchannel][job.status.started] error getting job', args[0], err)
        if (!job) return console.error('[backchannel][job.status.started] job not found', args[0])
        job.started = args[1]
        job.save()
      })
    }
  },
  jobDone: function (emitter, data) {
    var self = this
    Job.findById(data.id, function (err, job) {
      if (err) return console.error('Error finding job', err.message)
      if (!job) return console.error('job.done but job not found:', data.id)
      _.extend(job, data)
      try {
        job.duration = data.finished.getTime() - data.started.getTime()
      } catch (ignore) {
        job.duration = 1
      }
      job.markModified('phases')
      job.markModified('plugin_data')
      job.test_exitcode = job.phases.test && job.phases.test.exitCode
      job.deploy_exitcode = job.phases.deploy && job.phases.deploy.exitCode
      job.save()
      job = job.toJSON()

      Project.findOne({name: job.project}).lean().exec(function (err, project) {
        if (err) return console.error('Error finding project for job', err.message, job.project)
        if (!project) return console.error('Project for job.done not found', job.project)

        job.project = utils.sanitizeProject(project)
        job.status = jobs.status(job)
        self.send(project.name, 'job.done', [job])
        emitter.emit('job.doneAndSaved', job)
      })
    })
  }
}

module.exports = BackChannel
<commit_msg>(fix/backchannel.js): Prevent strider from crashing when 2 jobs from the same project are queued simulatenously [Fixes #745]<commit_after>'use strict';

/*
 * Backchannel server allows workers to stream messages back to the Node server
 * in a line-buffered way. Uses SSL.
 */

var _ = require('lodash');
var async = require('async');
var jobs = require('./jobs');
var common = require('./common');
var utils = require('./utils');
var config = require('./config');
var models = require('./models');

var Job = models.Job;
var User = models.User;
var Project = models.Project;

function striderJson(provider, project, ref, done) {
  function finished(err, contents) {
    if (err || !contents) return done(err);

    var data = {};

    try {
      data = JSON.parse(contents);
    } catch (e) {
      console.warn('Strider config is invalid JSON for', project, ref);
      console.log(contents);
    }

    done(undefined, data);
  }

  if (!provider.hosted) {
    return provider.getFile('strider.json', ref, project.provider.config, project, finished);
  }

  var account = project.creator.account(project.provider.id, project.provider.account);

  provider.getFile('strider.json', ref, account, project.provider.config, project, finished);
}

// Prepare the job for execution, save to database, and fire off a `job.new` event.
//
// job is expected to be populated with:
// - a trigger
// - a ref
// - the project name
// - the user id (if applicable)
// - type
// - created timestamp
// XXX: should this function go in a different file? idk. We'll
//      definitely move it around when we make strider OO.
function prepareJob(emitter, job) {
  Project.findOne({name: job.project}).populate('creator').exec(function (err, project) {
    if (err || !project) return console.error('job.prepare - failed to get project', job.project, err)
    // ok so the project is real, we can go ahead and save this job
    var provider = common.extensions.provider[project.provider.id];

    if (!provider) {
      return console.error('job.prepare - provider not found for project', job.project, project.provider.id);
    }

    Job.create(job, function (err, mjob) {
      if (err) return console.error('job.prepare - failed to save job', job, err);

      var jjob = mjob.toJSON();

      jjob.project = project;
      jjob.providerConfig = project.provider.config;
      jjob.fromStriderJson = true;

      striderJson(provider, project, job.ref, function (err, config) {
        if (err) {
          if (err.status === 403 || err.statusCode === 403) {
            console.log('job.prepare - access to strider.json is forbidden, skipping config merge');
            config = {};
            jjob.fromStriderJson = false;
          } else if (err.status === 404 || err.statusCode === 404) {
            console.log('job.prepare - strider.json not found, skipping config merge');
            config = {};
            jjob.fromStriderJson = false;
          } else {
            return console.error('job.prepare - error opening/processing project\'s `strider.json` file: ', err);
          }
        }

        var branch = project.branch(job.ref.branch || 'master');

        if (!branch) {
          return console.error('job.prepare - branch not found', job.ref.branch || 'master', project.name);
        }

        branch = branch.mirror_master ? project.branch('master') : branch;
        jjob.providerConfig = _.extend({}, project.provider.config, config.provider || {});
        config.runner = branch.runner;

        if (config) {
          delete config.provider;
          config = utils.mergeConfigs(branch, config);
        }

        emitter.emit('job.new', jjob, config);

        if (!mjob.runner) mjob.runner = {};

        mjob.runner.id = config.runner.id;
        mjob.save();
      })
    })
  })
}

function BackChannel(emitter, ws) {
  this.ws = ws;
  this.users = {};
  this.public = {};
  this.waiting = {};

  emitter.on('job.prepare', prepareJob.bind(null, emitter));
  emitter.on('job.new', this.newJob.bind(this));
  emitter.on('browser.update', this.onUpdate.bind(this));
  emitter.on('job.done', this.jobDone.bind(this, emitter));
}

BackChannel.prototype = {
  send: function (project, event, args) {
    if (this.users[project]) {
      this.ws.send(this.users[project], [event, args, 'yours'])
    }
    if (this.public[project]) {
      this.ws.sendPublic(this.users[project], [event, args, 'public'])
    }
  },

  newJob: function (job) {
    var self = this;
    var name = job.project.name;

    this.waiting[name] = [];
    this.public[name] = job.project.public;

    async.parallel({
      collaborators: function (paraCallback) {
        User.collaborators(name, 0, function (err, users) {
          paraCallback(err, users);
        });
      },

      admins: function (paraCallback) {
        User.admins(paraCallback);
      }
    }, function (err, users) {
      if (err) return console.error('new job: Failed to query for users')
      if (!users.collaborators) return console.error('new job: no users found')
      self.users[name] = []

      users.collaborators.forEach(function (user) {
        self.users[name].push(user._id.toString())
      })
      // also send to system admins
      users.admins.forEach(function (user) {
        self.users[name].push(user._id.toString())
      })

      // Admins maybe collaborators, so unique the array
      self.users[name] = _.uniq(self.users[name])

      var njob = jobs.small(job)

      njob.project = utils.sanitizeProject(job.project)
      self.send(name, 'job.new', [njob])

      var waiting = self.waiting[name]
      if(Array.isArray(waiting)) {
        waiting.forEach(function (item) {
          self.send.apply(self, [name].concat(item))
        })
      }
      delete self.waiting[name]
    });
  },
  // [project name, event name, [list of arguments]]
  onUpdate: function (project, event, args) {
    if (this.waiting[project]) {
      return this.waiting[project].push([event, args])
    }
    this.send(project, event, args)
    if (event === 'job.status.started') {
      Job.findById(args[0], function (err, job) {
        if (err) return console.error('[backchannel][job.status.started] error getting job', args[0], err)
        if (!job) return console.error('[backchannel][job.status.started] job not found', args[0])
        job.started = args[1]
        job.save()
      })
    }
  },
  jobDone: function (emitter, data) {
    var self = this
    Job.findById(data.id, function (err, job) {
      if (err) return console.error('Error finding job', err.message)
      if (!job) return console.error('job.done but job not found:', data.id)
      _.extend(job, data)
      try {
        job.duration = data.finished.getTime() - data.started.getTime()
      } catch (ignore) {
        job.duration = 1
      }
      job.markModified('phases')
      job.markModified('plugin_data')
      job.test_exitcode = job.phases.test && job.phases.test.exitCode
      job.deploy_exitcode = job.phases.deploy && job.phases.deploy.exitCode
      job.save()
      job = job.toJSON()

      Project.findOne({name: job.project}).lean().exec(function (err, project) {
        if (err) return console.error('Error finding project for job', err.message, job.project)
        if (!project) return console.error('Project for job.done not found', job.project)

        job.project = utils.sanitizeProject(project)
        job.status = jobs.status(job)
        self.send(project.name, 'job.done', [job])
        emitter.emit('job.doneAndSaved', job)
      })
    })
  }
}

module.exports = BackChannel
<|endoftext|>