<commit_before>/* Copyright 2015 Sébastien Maccagnoni-Munch
 *
 * This file is part of AwesomeShop.
 *
 * AwesomeShop is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * AwesomeShop is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with AwesomeShop. If not, see <http://www.gnu.org/licenses/>.
 */

// Adapted from http://stackoverflow.com/a/21189057
(function() {
  var $http = angular.injector(['ng']).get('$http');
  $http.get('/api/config').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);
      angular.element(document).ready(function() {
        angular.bootstrap(document, ['awesomeshop']);
      });
    }
  );
})();

angular.module('spinner', ['ui.bootstrap'])
.config(function($httpProvider) {
    loading_count = 0;
    function show_or_hide_spinner(inc) {
        loading_count += inc;
        if (loading_count > 0) {
            document.getElementById('spinner').className="";
        } else {
            document.getElementById('spinner').className="ng-hide";
        };
    }
    $httpProvider.interceptors.push(function($rootScope, $q) {
        return {
            'response': function(response) {
                show_or_hide_spinner(-1);
                return response;
            },
            'responseError': function(rejection) {
                show_or_hide_spinner(-1);
                $rootScope.$emit('apierror', rejection.data.message)
                return $q.reject(rejection);
            }
        };
    });
    $httpProvider.defaults.transformRequest.push(function(data){
        show_or_hide_spinner(+1);
        return data;
    });
})
.directive('enableErrorHandler', function($uibModal){
    return {
        link: function(scope, elem, attrs) {
                scope.$on('apierror', function(evt, data) {
                    var template_url;
                    if (data.type == 'message') {
                        scope.message = data.message;
                        template_url = '/part/stringerror'
                    } else if (data.type == 'fields') {
                        scope.errors = data.errors;
                        template_url = '/part/fieldserror'
                    };
                    $uibModal.open({
                            templateUrl: template_url
                    });
                });
        }
    };
});

angular.module('authentication', ['http-auth-interceptor', 'ui.bootstrap'])
.controller('AuthenticationCtrl', function($scope, $http, authService) {
    $scope.login = function() {
        $http.post('/api/login', {
                email: $scope.auth.email,
                password: $scope.auth.password
        })
            .then(function(response) {
                var success = response.data.auth;
                $scope.auth.success = success;
                if (success) {
                    $scope.$close();
                    authService.loginConfirmed();
                }
            });
    }
})
.directive('triggerAuth', ['$uibModal', function($uibModal) {
    return {
        link: function(scope, elem, attrs) {
                scope.$on('event:auth-loginRequired', function() {
                    var modalInstance = $uibModal.open({
                        backdrop: 'static',
                        templateUrl: '/part/login',
                        controller: 'AuthenticationCtrl'
                    });
                });
        }
    };
}]);
<commit_msg>Hide the spinner when there is no request<commit_after>/* Copyright 2015 Sébastien Maccagnoni-Munch
 *
 * This file is part of AwesomeShop.
 *
 * AwesomeShop is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * AwesomeShop is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with AwesomeShop. If not, see <http://www.gnu.org/licenses/>.
 */

// Adapted from http://stackoverflow.com/a/21189057
(function() {
  var $http = angular.injector(['ng']).get('$http');
  $http.get('/api/config').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);
      angular.element(document).ready(function() {
        angular.bootstrap(document, ['awesomeshop']);
      });
    }
  );
})();

angular.module('spinner', ['ui.bootstrap'])
.config(function($httpProvider) {
    loading_count = 0;
    function show_or_hide_spinner(inc) {
        loading_count += inc;
        if (loading_count > 0) {
            document.getElementById('spinner').className="";
        } else {
            document.getElementById('spinner').className="ng-hide";
        };
    }
    show_or_hide_spinner(0);
    $httpProvider.interceptors.push(function($rootScope, $q) {
        return {
            'response': function(response) {
                show_or_hide_spinner(-1);
                return response;
            },
            'responseError': function(rejection) {
                show_or_hide_spinner(-1);
                $rootScope.$emit('apierror', rejection.data.message)
                return $q.reject(rejection);
            }
        };
    });
    $httpProvider.defaults.transformRequest.push(function(data){
        show_or_hide_spinner(+1);
        return data;
    });
})
.directive('enableErrorHandler', function($uibModal){
    return {
        link: function(scope, elem, attrs) {
                scope.$on('apierror', function(evt, data) {
                    var template_url;
                    if (data.type == 'message') {
                        scope.message = data.message;
                        template_url = '/part/stringerror'
                    } else if (data.type == 'fields') {
                        scope.errors = data.errors;
                        template_url = '/part/fieldserror'
                    };
                    $uibModal.open({
                            templateUrl: template_url
                    });
                });
        }
    };
});

angular.module('authentication', ['http-auth-interceptor', 'ui.bootstrap'])
.controller('AuthenticationCtrl', function($scope, $http, authService) {
    $scope.login = function() {
        $http.post('/api/login', {
                email: $scope.auth.email,
                password: $scope.auth.password
        })
            .then(function(response) {
                var success = response.data.auth;
                $scope.auth.success = success;
                if (success) {
                    $scope.$close();
                    authService.loginConfirmed();
                }
            });
    }
})
.directive('triggerAuth', ['$uibModal', function($uibModal) {
    return {
        link: function(scope, elem, attrs) {
                scope.$on('event:auth-loginRequired', function() {
                    var modalInstance = $uibModal.open({
                        backdrop: 'static',
                        templateUrl: '/part/login',
                        controller: 'AuthenticationCtrl'
                    });
                });
        }
    };
}]);
<|endoftext|>


<commit_before>const path=require("path");
const fs=require("fs-extra");
const Cue=require("./Cue");
const WebVTT=require("webvtt/lib/WebVTT");

class ExternalMedia {

    constructor(path,webvtt) {
        this.pathIsIndexed=false;
        this.displayName="";
        this.webvtt=webvtt;
        this.path=path;
        return this;
    }

    get pathIsIndexed() {return this._pathIsIndexed}
    set pathIsIndexed(newvalue) {
        this._pathIsIndexed=newvalue;
        this.displayName=this.pathIsIndexed?path.basename(this.path):this.path;
    }

    get path() {return this._path}
    set path(path) {
        this._path=path;
        this.displayName=this.pathIsIndexed?path.basename(this.path):this.path;
        this.createList();
    }

    get webvtt() {return this._webvtt}
    set webvtt(webvtt) {
        if( webvtt instanceof WebVTT ) this._webvtt=webvtt;
        else this._webvtt=new WebVTT(webvtt);
        // Sanitization, remove hidden control characters from cue content:
        this._webvtt.data.map(obj=>obj.content=obj.content.replace(/[^\u{0020}-\u{FFFF}]/gu,""));
        this.createList();
    }

    get source() {return this}
    get filename() {return path.basename(this.path)}
    get extension() {return path.extname(this.path).toLowerCase()}

    isImage() {return (ExternalMedia.IMAGEEXT.indexOf(this.extension)>=0)}
    isVideo() {return (ExternalMedia.VIDEOEXT.indexOf(this.extension)>=0)}
    valid() {return this.path && this.path.length && fs.existsSync(this.path)}

    createList() {
        var list=[];
        if( this.valid() && this.isVideo() ) {
            this.webvtt.data.forEach(cue=>{
                if( list.length && list[list.length-1].end==cue.start ) {
                    var last=list[list.length-1];
                    last.end=cue.end;
                    last.max=cue.end;
                    last.content=last.content.split("-")[0]+"-"+cue.content;
                } else {
                    list.push(new Cue(cue.start,cue.end,cue.content));
                }
            });
        }
        this.list=list;
    }

    calcPlayLength() {
        var sum=this.isImage()?ExternalMedia.IMAGE_DURATION:0;
        for( var cue of this.list ) sum+=cue.end-cue.start;
        return sum;
    }

    toString() {return this.displayName}

}

ExternalMedia.IMAGE_DURATION=6;
ExternalMedia.IMAGEEXT=[".png",".jpg",".gif",".jpeg",".bmp"];
ExternalMedia.VIDEOEXT=[".mov",".mp4",".m4v",".avi",".webm"];
ExternalMedia.ALLEXT=ExternalMedia.IMAGEEXT.concat(ExternalMedia.VIDEOEXT);

module.exports=ExternalMedia;<commit_msg>Fix ExternalMedia to report its filename as the toString() value.<commit_after>const path=require("path");
const fs=require("fs-extra");
const Cue=require("./Cue");
const WebVTT=require("webvtt/lib/WebVTT");

class ExternalMedia {

    constructor(path,webvtt) {
        this.pathIsIndexed=false;
        this.displayName="";
        this.webvtt=webvtt;
        this.path=path;
        return this;
    }

    get pathIsIndexed() {return this._pathIsIndexed}
    set pathIsIndexed(newvalue) {
        this._pathIsIndexed=newvalue;
        this.displayName=this.pathIsIndexed?path.basename(this.path):this.path;
    }

    get path() {return this._path}
    set path(path) {
        this._path=path;
        this.displayName=this.pathIsIndexed?path.basename(this.path):this.path;
        this.createList();
    }

    get webvtt() {return this._webvtt}
    set webvtt(webvtt) {
        if( webvtt instanceof WebVTT ) this._webvtt=webvtt;
        else this._webvtt=new WebVTT(webvtt);
        // Sanitization, remove hidden control characters from cue content:
        this._webvtt.data.map(obj=>obj.content=obj.content.replace(/[^\u{0020}-\u{FFFF}]/gu,""));
        this.createList();
    }

    get source() {return this}
    get filename() {return path.basename(this.path)}
    get extension() {return path.extname(this.path).toLowerCase()}

    isImage() {return (ExternalMedia.IMAGEEXT.indexOf(this.extension)>=0)}
    isVideo() {return (ExternalMedia.VIDEOEXT.indexOf(this.extension)>=0)}
    valid() {return this.path && this.path.length && fs.existsSync(this.path)}

    createList() {
        var list=[];
        if( this.valid() && this.isVideo() ) {
            this.webvtt.data.forEach(cue=>{
                if( list.length && list[list.length-1].end==cue.start ) {
                    var last=list[list.length-1];
                    last.end=cue.end;
                    last.max=cue.end;
                    last.content=last.content.split("-")[0]+"-"+cue.content;
                } else {
                    list.push(new Cue(cue.start,cue.end,cue.content));
                }
            });
        }
        this.list=list;
    }

    calcPlayLength() {
        var sum=this.isImage()?ExternalMedia.IMAGE_DURATION:0;
        for( var cue of this.list ) sum+=cue.end-cue.start;
        return sum;
    }

    // TODO: Maybe this should be changed to "path" if not indexed, and "filename" if indexed?
    toString() {return this.filename}

}

ExternalMedia.IMAGE_DURATION=6;
ExternalMedia.IMAGEEXT=[".png",".jpg",".gif",".jpeg",".bmp"];
ExternalMedia.VIDEOEXT=[".mov",".mp4",".m4v",".avi",".webm"];
ExternalMedia.ALLEXT=ExternalMedia.IMAGEEXT.concat(ExternalMedia.VIDEOEXT);

module.exports=ExternalMedia;<|endoftext|>


<commit_before>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  fastboot: service(),

  headTags() {
    return [
      {
        type: 'meta',
        attrs: {
          name: 'description',
          content: 'cargo is the package manager and crate host for rust',
        },
      },
    ];
  },

  setupController(controller) {
    this.controllerFor('application').set('searchQuery', null);

    let promise = controller.dataTask.perform();
    if (this.fastboot.isFastBoot) {
      this.fastboot.deferRendering(promise);
    }
  },
});
<commit_msg>Auto merge of #2474 - Turbo87:loading, r=locks<commit_after>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  fastboot: service(),

  headTags() {
    return [
      {
        type: 'meta',
        attrs: {
          name: 'description',
          content: 'cargo is the package manager and crate host for rust',
        },
      },
    ];
  },

  setupController(controller) {
    this.controllerFor('application').set('searchQuery', null);

    if (!controller.dataTask.hasData) {
      let promise = controller.dataTask.perform();
      if (this.fastboot.isFastBoot) {
        this.fastboot.deferRendering(promise);
      }
    }
  },
});
<|endoftext|>


<commit_before>var mapnik = require('mapnik'),
  mercator = new(require('sphericalmercator')),
  nfs = require('node-fs'),
  path = require('path'),
  fs = require('fs');

// register geojson as a datasource in mapnik
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input'));

module.exports = {

  get: function(params, data, callback ){
    var x = parseInt( params.x ),
      y = parseInt( params.y ),
      z = parseInt( params.z ),
      key = params.key,
      format = params.format;

    var style = params.style;

    if (!params.x || !params.y || !params.z || !format || !key){
      callback('Missing parameters', null);
    } else {
      // check the cache - the local file system
      this._check( x, y, z, key, format, data, function( err, file ){
        if ( file ){
          if ( format == 'json' ){
            callback( err, require(file) );
          } else {
            callback( err, file );
          }
        } else {
          callback( 'Something went wrong with the tiles', null );
        }
      });
    }

  },

  _check: function( x, y, z, key, format, data, callback ){
    var self = this;
    var p = [ config.data_dir + 'tiles', key, format, z, x].join('/');
    var file = p + '/' + y + '.' + format;

    nfs.mkdir( p, '0777', true, function(){
      if ( !nfs.existsSync( file ) ) {
        self._stash( file, format, data, z, x, y, function( err, newfile ){
          callback( err, newfile );
        });
      } else {
        callback( null, file );
      }
    });
  },

  _stash: function( file, format, geojson, z, x, y, callback ){
    var feature;

      if ( format == 'json' ){
        fs.writeFile( file, JSON.stringify( geojson ), function(){
          callback( null, file );
        });
      } else {

          function render(){

            if ( format == 'png' ){
              var map = new mapnik.Map(256, 256);
              map.loadSync(__dirname + '/../templates/renderers/style.xml');

              var layer = new mapnik.Layer('tile');
              layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );

              // add styles
              layer.styles = [geojson.features[0].geometry.type.toLowerCase()];

              map.add_layer(layer);

              var image = new mapnik.Image(256, 256);
              map.extent = mercator.bbox(x, y, z, false, '4326');

              map.render( image, {}, function( err, im ) {
                if (err) {
                  callback( err, null );
                } else {
                  im.encode( 'png', function( err, buffer ) {
                    fs.writeFile( file, buffer, function( err ) {
                      callback( null, file );
                    });
                  });
                }
              });

            } else if (format == 'vector.pbf') {

              var map = new mapnik.Map(256, 256);

              var layer = new mapnik.Layer('tile');
              layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );
              map.add_layer(layer);

              var vtile = new mapnik.VectorTile( z, x, y );
              map.extent = mercator.bbox(x, y, z, false, '4326');

              map.render( vtile, {}, function( err, vtile ) {
                if (err) {
                  callback( err, null );
                } else {
                  fs.writeFileSync( file, vtile.getData() );
                  callback( null, file );
                }
              });

            } else if ( format == 'utf') {
              var grid = new mapnik.Grid(256, 256);
              var map = new mapnik.Map(256, 256);
              map.loadSync(__dirname + '/../templates/renderers/style.xml');
              var layer = new mapnik.Layer('tile');
              layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );
              // add styles
              layer.styles = [geojson.features[0].geometry.type.toLowerCase()];
              map.add_layer(layer);

              map.extent = mercator.bbox(x, y, z, false, '4326');

              map.render( grid, {layer: 0}, function( err, g ) {
                if (err) {
                  callback( err, null );
                } else {
                    fs.writeFile( file, JSON.stringify(g), function( err ) {
                      callback( null, file );
                    });
                }
              });

            }
          };

          var jsonFile = file.replace(/png|utf|vector\.pbf/g, 'json');

          if ( !nfs.existsSync( jsonFile ) ) {

            var dir = jsonFile.split('/');
            var f = dir.pop();

            nfs.mkdir( dir.join('/'), '0777', true, function(){
              fs.writeFile( jsonFile, JSON.stringify( geojson ), function(){
                render();
              });
            });

          } else if ( format == 'utf' && nfs.existsSync( file )){

            fs.readFile(file, function(err, data){
              callback(null, JSON.parse(data));
            });

          } else {
            render();
          }

      }
  }

};
<commit_msg>fix missing geom<commit_after>var mapnik = require('mapnik'),
  mercator = new(require('sphericalmercator')),
  nfs = require('node-fs'),
  path = require('path'),
  fs = require('fs');

// register geojson as a datasource in mapnik
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input'));

module.exports = {

  get: function(params, data, callback ){
    var x = parseInt( params.x ),
      y = parseInt( params.y ),
      z = parseInt( params.z ),
      key = params.key,
      format = params.format;

    var style = params.style;

    if (!params.x || !params.y || !params.z || !format || !key){
      callback('Missing parameters', null);
    } else {
      // check the cache - the local file system
      this._check( x, y, z, key, format, data, function( err, file ){
        if ( file ){
          if ( format == 'json' ){
            callback( err, require(file) );
          } else {
            callback( err, file );
          }
        } else {
          callback( 'Something went wrong with the tiles', null );
        }
      });
    }

  },

  _check: function( x, y, z, key, format, data, callback ){
    var self = this;
    var p = [ config.data_dir + 'tiles', key, format, z, x].join('/');
    var file = p + '/' + y + '.' + format;

    nfs.mkdir( p, '0777', true, function(){
      if ( !nfs.existsSync( file ) ) {
        self._stash( file, format, data, z, x, y, function( err, newfile ){
          callback( err, newfile );
        });
      } else {
        callback( null, file );
      }
    });
  },

  _stash: function( file, format, geojson, z, x, y, callback ){
    var feature;

      if ( format == 'json' ){
        fs.writeFile( file, JSON.stringify( geojson ), function(){
          callback( null, file );
        });
      } else {

          function render(){

            if ( format == 'png' ){
              var map = new mapnik.Map(256, 256);
              map.loadSync(__dirname + '/../templates/renderers/style.xml');

              var layer = new mapnik.Layer('tile');
              layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );

              // add styles
              if (geojson && geojson.features && geojson.features.length){
                layer.styles = [geojson.features[0].geometry.type.toLowerCase()];
              }
              map.add_layer(layer);

              var image = new mapnik.Image(256, 256);
              map.extent = mercator.bbox(x, y, z, false, '4326');

              map.render( image, {}, function( err, im ) {
                if (err) {
                  callback( err, null );
                } else {
                  im.encode( 'png', function( err, buffer ) {
                    fs.writeFile( file, buffer, function( err ) {
                      callback( null, file );
                    });
                  });
                }
              });

            } else if (format == 'vector.pbf') {

              var map = new mapnik.Map(256, 256);

              var layer = new mapnik.Layer('tile');
              layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );
              map.add_layer(layer);

              var vtile = new mapnik.VectorTile( z, x, y );
              map.extent = mercator.bbox(x, y, z, false, '4326');

              map.render( vtile, {}, function( err, vtile ) {
                if (err) {
                  callback( err, null );
                } else {
                  fs.writeFileSync( file, vtile.getData() );
                  callback( null, file );
                }
              });

            } else if ( format == 'utf') {
              var grid = new mapnik.Grid(256, 256);
              var map = new mapnik.Map(256, 256);
              map.loadSync(__dirname + '/../templates/renderers/style.xml');
              var layer = new mapnik.Layer('tile');
              layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );
              // add styles
              layer.styles = [geojson.features[0].geometry.type.toLowerCase()];
              map.add_layer(layer);

              map.extent = mercator.bbox(x, y, z, false, '4326');

              map.render( grid, {layer: 0}, function( err, g ) {
                if (err) {
                  callback( err, null );
                } else {
                    fs.writeFile( file, JSON.stringify(g), function( err ) {
                      callback( null, file );
                    });
                }
              });

            }
          };

          var jsonFile = file.replace(/png|utf|vector\.pbf/g, 'json');

          if ( !nfs.existsSync( jsonFile ) ) {

            var dir = jsonFile.split('/');
            var f = dir.pop();

            nfs.mkdir( dir.join('/'), '0777', true, function(){
              fs.writeFile( jsonFile, JSON.stringify( geojson ), function(){
                render();
              });
            });

          } else if ( format == 'utf' && nfs.existsSync( file )){

            fs.readFile(file, function(err, data){
              callback(null, JSON.parse(data));
            });

          } else {
            render();
          }

      }
  }

};
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();

	app.route('/')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.get('/t/:test', function (req, res) {
		res.send("test num: " + req.params.test);
		console.log(req.params.test);
	});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);
};
<commit_msg>route test<commit_after>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();

	app.route('/')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/index.html');
		});

	app.route('/login')
		.get(function (req, res) {
			res.sendFile(path + '/public/login.html');
		});

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.sendFile(path + '/public/profile.html');
		});

	app.route('/api/:id')
		.get(isLoggedIn, function (req, res) {
			res.json(req.user.github);
		});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);
};
<|endoftext|>


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

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

// Create fields
InternalNotes.add( 'Target', {
    target: { type: Types.Select, label: 'target', options: 'child, family, social worker', initial: true },
    child: { type: Types.Relationship, label: 'child', ref: 'Child', dependsOn: { target: 'child' }, initial: true },
    family: { type: Types.Relationship, label: 'family', ref: 'Family', dependsOn: { target: 'family' }, filters: { isActive: true }, initial: true },
    socialWorker: { type: Types.Relationship, label: 'social worker', ref: 'Social Worker', dependsOn: { target: 'social worker' }, filters: { isActive: true }, initial: true }

}, 'Note Details', {

    date: { type: Types.Date, label: 'note date', format: 'MM/DD/YYYY', default: Date.now, required: true, noedit: true },
    employee: { type: Types.Relationship, label: 'note creator', ref: 'Admin', filters: { isActive: true }, required: true, noedit: true, initial: true },
    note: { type: Types.Textarea, label: 'note', required: true, initial: true }

});

// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date|15%, note|70%';
InternalNotes.register();<commit_msg>adjusts default display of internal notes model list view<commit_after>var keystone = require('keystone'),
    Types = keystone.Field.Types;

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

// Create fields
InternalNotes.add( 'Target', {
    target: { type: Types.Select, label: 'target', options: 'child, family, social worker', initial: true },
    child: { type: Types.Relationship, label: 'child', ref: 'Child', dependsOn: { target: 'child' }, initial: true },
    family: { type: Types.Relationship, label: 'family', ref: 'Family', dependsOn: { target: 'family' }, filters: { isActive: true }, initial: true },
    socialWorker: { type: Types.Relationship, label: 'social worker', ref: 'Social Worker', dependsOn: { target: 'social worker' }, filters: { isActive: true }, initial: true }

}, 'Note Details', {

    date: { type: Types.Date, label: 'note date', format: 'MM/DD/YYYY', default: Date.now, required: true, noedit: true },
    employee: { type: Types.Relationship, label: 'note creator', ref: 'Admin', filters: { isActive: true }, required: true, noedit: true, initial: true },
    note: { type: Types.Textarea, label: 'note', required: true, initial: true }

});

// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date|10%, child|10%, family|10%, socialWorker|10% note|60%';
InternalNotes.register();<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var handlebars  = require('handlebars');
var fs = require('fs');
var request = require('request');

module.exports = function (app) {

function callAPI(res){
		var url = 'http://dev.markitondemand.com/MODApis/Api/interactive?parameters=%7B%22Normalized%22:false,%22StartDate%22:%222013-07-15T00:00:00-00%22,%22EndOffsetDays%22:100,%22NumberOfDays%22:100,%22DataPeriod%22:%22Day%22,%22DataInterval%22:0,%22LabelPeriod%22:%22Day%22,%22LabelInterval%22:1,%22ExtraPoints%22:0,%22Elements%22:%5B%7B%22Symbol%22:%22GOOG%22,%22ElementType%22:%22price%22,%22Params%22:%5B%22ohlc%22%5D%7D%5D,%22RealTime%22:false%7D';
		request(url, function (error, response, body) {
  		if (!error && response.statusCode == 200) {
    	var marketresponse = JSON.parse(body);
    		console.log("Got a response: ", marketresponse);
    		loadPage(res, marketresponse);
  		} else {
			 console.log("Got an error: ", error, ", status code: ", response.statusCode);
  		}
		});

}

function loadPage(res, marketresponse){
		var data = {
					stocks: marketresponse.toString()

				}

			    fs.readFile('public/index.html', 'utf-8', function(error, source){
                	var template = handlebars.compile(source);
                	var html = template(data);
            		 res.send(html);

                });

}

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

			callAPI(res);

		});

};
<commit_msg>stringified json<commit_after>'use strict';

var path = process.cwd();
var handlebars  = require('handlebars');
var fs = require('fs');
var request = require('request');

module.exports = function (app) {

function callAPI(res){
		var url = 'http://dev.markitondemand.com/MODApis/Api/interactive?parameters=%7B%22Normalized%22:false,%22StartDate%22:%222013-07-15T00:00:00-00%22,%22EndOffsetDays%22:100,%22NumberOfDays%22:100,%22DataPeriod%22:%22Day%22,%22DataInterval%22:0,%22LabelPeriod%22:%22Day%22,%22LabelInterval%22:1,%22ExtraPoints%22:0,%22Elements%22:%5B%7B%22Symbol%22:%22GOOG%22,%22ElementType%22:%22price%22,%22Params%22:%5B%22ohlc%22%5D%7D%5D,%22RealTime%22:false%7D';
		request(url, function (error, response, body) {
  		if (!error && response.statusCode == 200) {
    	var marketresponse = JSON.parse(body);
    		console.log("Got a response: ", marketresponse);
    		loadPage(res, JSON.stringify(marketresponse));
  		} else {
			 console.log("Got an error: ", error, ", status code: ", response.statusCode);
  		}
		});

}

function loadPage(res, marketresponse){
		var data = {
					stocks: marketresponse

				}

			    fs.readFile('public/index.html', 'utf-8', function(error, source){
                	var template = handlebars.compile(source);
                	var html = template(data);
            		 res.send(html);

                });

}

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

			callAPI(res);

		});

};
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 * @preventMunge
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var {Vector, Map, OrderedMap, Record}            = require('immutable');
var {isSchema, isList, isMapping, isScalar}      = require('./schema');
var ValidationResult                             = require('./ValidationResult');
var mergeInto                                    = require('./mergeInto');
var merge                                        = require('./merge');
var invariant                                    = require('./invariant');
var validate                                     = require('./validate');
var emptyFunction                                = require('./emptyFunction');
var toArray                                      = require('./toArray');

var DIRTY_KEY = '__react_forms_dirty__';

/**
 * Serves as a immutable container for form value attributes.
 */
var ValueAttributes = Record({
  schema: null,
  value: null,
  validation: null,
  externalValidation: null,
  serialized: null
}, 'ValueAttributes');

/**
 * Reference to the current form value.
 */
class Value {

  constructor(attributes, root, path) {
    this._attributes = attributes;
    this._root = root;
    this._cache = {};
    this._schema = null;
    this.path = path;
  }

  equals(other) {
    return (
      this.path.toString() === other.path.toString() &&
      this.schema.equals(other.schema) &&
      (
        this.value && this.value.equals ?
        this.value.equals(other.value) :
        this.value === other.value
      ) &&
      (
        this.serialized && this.serialized.equals ?
        this.serialized.equals(other.serialized) :
        this.serialized === other.serialized
      ) &&
      this.validation.equals(other.validation) &&
      this.externalValidation.equals(other.externalValidation) &&
      this.dirty === other.dirty &&
      this._root.get('onUpdate') === other._root.get('onUpdate')
    );
  }

  _child(key) {
    if (this._cache[key]) {
      return this._cache[key];
    }

    var schema = this.schema.child(key);
    var value = this.value.get(key);
    var schemaInstance = instantiateSchema(schema, value);
    var serialized = this.serialized.get(key);
    var validation = this.validation.child(key);
    var externalValidation = this.externalValidation.child(key);

    var attributes;
    if (value === undefined) {
      value = _defaultValue(schemaInstance);
      attributes = makeAttributes({schema, value, serialized, validation, externalValidation});
    } else {
      attributes = {schema, value, serialized, validation, externalValidation};
    }

    var ctor = _getCtor(schemaInstance);
    return (this._cache[key] = new ctor(
      this._attributes.merge(attributes),
      this._root,
      this.path.concat(key)
    ));
  }

  child(...key) {
    var value = this;
    for (var i = 0, len = key.length; i < len; i++) {
      value = value._child(key[i]);
    }
    return value;
  }

  childIn(keyPath) {
    return this.child.apply(this, keyPath);
  }

  update(newValue) {
    var trace = valueTraceByPath(this.root, this.path);
    var attributes;
    for (var i = 0, len = trace.length; i < len; i++) {
      var value = trace[i];
      if (i === 0) {
        attributes = makeAttributes({schema: value.schema, value: newValue});
      } else {
        attributes = value.onChildUpdate(prevValue.key, attributes);
      }
      var prevValue = value;
    }
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes.merge(attributes),
      this._root.merge({dirty, pendingRootRef}),
      []
    );
    var n = root.childIn(this.path);
    return n;
  }

  onChildUpdate(key, {value, validation, serialized}) {
    value = this.value.set(key, value);

    var schema = this.schema;
    var newSchema = instantiateSchema(this._attributes.schema, value);
    if (!schema.equals(newSchema)) {
      return makeAttributes({schema: newSchema, value}, {strip: true});
    }
    validation = this.validation.updateChild(key, validation);
    validation = validate(this.schema, value, validation.children).validation;
    serialized = this.serialized.set(key, serialized);
    return this._attributes.merge({value, serialized, validation});
  }

  updateChild(key, newValue) {
    return this.child(key).update(newValue).root();
  }

  updateChildIn(keyPath, newValue) {
    return this.childIn(keyPath).update(newValue).root();
  }

  updateSchema(newSchema) {
    // TODO: Should we try to keep serialized for unchanged parts of schema?
    var {_attributes: {value, externalValidation, dirty, onUpdate, rootRef}} = this.root;
    return make(newSchema, value, externalValidation, onUpdate, dirty, rootRef);
  }

  updateExternalValidation(newExternalValidation) {
    // TODO: Should we try to keep serialized for unchanged parts of schema?
    var {_attributes: {schema, value, dirty, onUpdate, rootRef}} = this.root;
    return make(schema, value, newExternalValidation, onUpdate, dirty, rootRef);
  }

  _makeDirty() {
    var dirty = this._root.get('dirty');
    return dirty.updateIn(this.path.concat(DIRTY_KEY), () => true);
  }

  markDirty() {
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes,
      this.root._root.merge({dirty, pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  markAsConsistent() {
    return new this.constructor(
      this._attributes,
      this._root.merge({pendingRootRef: null}),
      this.path
    );
  }

  notify() {
    var onUpdate = this._root.get('onUpdate', emptyFunction)
    onUpdate(this);
    return this;
  }
}

Object.defineProperty(Value.prototype, 'key', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    } else {
      return this.path[this.path.length - 1];
    }
  }
});

Object.defineProperty(Value.prototype, 'root', {
  get: function() {
    var ref = this._root.get('pendingRootRef');
    if (!ref) {
      ref = this._root.get('rootRef');
    }
    if (!ref) {
      return this;
    }
    return ref();
  }
});

Object.defineProperty(Value.prototype, 'parent', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    }
    var path = this.path.slice(0);
    path.pop();
    return this.root.childIn(path);
  }
});

Object.defineProperty(Value.prototype, 'schema', {
  get: function() {
    if (this._schema === null) {
      this._schema = instantiateSchema(this._attributes.schema, this._attributes.value);
    }
    return this._schema;
  }
});

Object.defineProperty(Value.prototype, 'value', {
  get: function() {
    return this._attributes.value;
  }
});

Object.defineProperty(Value.prototype, 'serialized', {
  get: function() {
    var serialized = this._attributes.serialized;
    if (serialized === undefined) {
      return _defaultValue(this._attributes.schema);
    }
    return serialized;
  }
});

Object.defineProperty(Value.prototype, 'validation', {
  get: function() {
    return this._attributes.validation;
  }
});

Object.defineProperty(Value.prototype, 'externalValidation', {
  get: function() {
    return this._attributes.externalValidation;
  }
});

Object.defineProperty(Value.prototype, 'isValid', {
  get: function() {
    return this.validation.isSuccess;
  }
});

Object.defineProperty(Value.prototype, 'isDirty', {
  get: function() {
    var path = this.path;
    var dirty = this._root.get('dirty');
    for (var i = 0, len = path.length; i < len; i++) {
      if (dirty) {
        if (dirty.get(DIRTY_KEY) || dirty.get(path[i])) {
          return true;
        }
      } else {
        return false;
      }
      dirty = dirty.get(path[i]);
    }
    return dirty && (dirty.get(DIRTY_KEY) || dirty.length > 0);
  }
});

function valueTraceByPath(value, path) {
  var trace = [value];
  for (var i = 0, len = path.length; i < len; i++) {
    value = value.child(path[i]);
    trace.unshift(value);
  }
  return trace;
}

class ScalarValue extends Value {

}

class MappingValue extends Value {

  map(func, context) {
    return this.schema.children
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.schema.children.forEach((_, key) => {
      return func.call(context, this.child(key), key);
    });
  }
}

class ListValue extends Value {

  map(func, context) {
    return this.value
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.value.forEach((_, key) => func.call(context, this.child(key), key));
  }

  emptyChild() {
    return _defaultValue(this.schema.children);
  }

  push(...values) {
    var newValue = this.value.push.apply(this.value, values);
    return this.update(newValue);
  }

  splice() {
    var newValue = this.value.splice.apply(this.value, toArray(arguments));
    return this.update(newValue);
  }
}

function isValue(maybeValue) {
  return maybeValue instanceof Value;
}

function isScalarValue(value) {
  return value instanceof ScalarValue;
}

function isMappingValue(value) {
  return value instanceof MappingValue;
}

function isListValue(value) {
  return value instanceof ListValue;
}

function make(schema, value, externalValidation, onUpdate, dirty, rootRef) {
  externalValidation = externalValidation || ValidationResult.success;
  dirty = dirty || Map.empty();
  var attributes = makeAttributes({schema, value, externalValidation}, {root: true});
  var ctor = _getCtor(schema);
  rootRef = rootRef || (() => value);
  var value = new ctor(attributes, Map({onUpdate, dirty, rootRef}), []);
  return value;
}

function instantiateSchema(schema, value) {
  if (typeof schema === 'function') {
    schema = schema(value);
  }
  return schema;
}

function makeAttributes(args, options) {
  var {schema, value} = args;

  invariant(
    isSchema(schema),
    'make(schema, ...) has received not a schema value as its first argument'
  );

  var schemaInstance = instantiateSchema(schema, value);
  if (isScalar(schemaInstance)) {
    return _makeScalar(args, options);
  } else if (isMapping(schemaInstance)) {
    return _makeMapping(args, options);
  } else if (isList(schemaInstance)) {
    return _makeList(args, options);
  }
}

function _makeScalar(args) {
  var {value, schema, validation, serialized} = args;
  var schemaInstance = instantiateSchema(schema, value);
  if (value === undefined) {
    value = _defaultValue(schemaInstance);
    if (value === null) {
      return undefined;
    }
  }
  if (validation === undefined) {
    var validationResult = validate(schemaInstance, value);
    value = validationResult.value;
    validation = validationResult.validation;
  }
  if (serialized === undefined) {
    serialized = schemaInstance.type.serialize(value);
  }
  return new ValueAttributes(merge(args, {value, validation, serialized}));
}

function _makeMapping(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  var schemaInstance = instantiateSchema(schema, value);
  if (value === undefined) {
    if (options.root) {
      value = _defaultValue(schemaInstance);
    } else {
      return undefined;
    }
  }
  if (!(value instanceof OrderedMap)) {
    value = OrderedMap.from(value);
  }

  var _value = {};
  var _serialized = {};
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  schemaInstance.children.forEach((schema, name) => {
    var schemaInstance = instantiateSchema(schema, value.get(name));
    var child = makeAttributes({
      schema,
      value: value.get(name)
    }, {strip: options.strip});
    if (child === undefined) {
      if (schemaInstance.props.get('required')) {
        _hasChildError = true;
        _childrenValidation[name] = ValidationResult.failure('value is required');
      }
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value[name] = childValue;
    _serialized[name] = childSerialized;
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schemaInstance, _value);
  }
  value = value.merge(_value);
  if (options.strip) {
    value.forEach((_, key) =>{
      if (!schema.children.has(key)) {
        value = value.remove(key);
      }
    });
  }
  serialized = serialized || OrderedMap.from(_serialized);
  validation = validation || _validation;
  return new ValueAttributes({schema, value, serialized, validation, externalValidation});
}

function _makeList(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  var schemaInstance = instantiateSchema(schema, value);
  if (value === undefined) {
    if (options.root) {
      value = _defaultValue(schemaInstance);
    } else {
      return undefined;
    }
  }
  if (!(value instanceof Vector)) {
    value = Vector.from(value);
  }

  var _value = [];
  var _serialized = [];
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  value.forEach((value, name) => {
    var child = makeAttributes({
      schema: schemaInstance.child(name),
      value
    }, {strip: options.strip});
    if (child === undefined) {
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value.push(childValue);
    _serialized.push(childSerialized);
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schemaInstance, _value);
  }
  return new ValueAttributes({
    schema,
    value: Vector.from(_value),
    serialized: serialized || Vector.from(_serialized),
    validation: validation || _validation,
    externalValidation
  });
}

/**
 * Get value constructor for given schema node.
 *
 * @private
 * @param {Schema} schema
 * @returns {Constructor}
 */
function _getCtor(schema) {
  var constructor;
  if (isScalar(schema)) {
    constructor = ScalarValue;
  } else if (isMapping(schema)) {
    constructor = MappingValue;
  } else if (isList(schema)) {
    constructor = ListValue;
  } else {
    invariant(false, 'invalid schema node');
  }
  return constructor;
}

function _defaultValue(schema) {
  if (schema.defaultValue !== undefined) {
    return schema.defaultValue;
  } else if (isMapping(schema)) {
    return OrderedMap.empty();
  } else if (isList(schema)) {
    return Vector.empty();
  } else {
    return null;
  }
}

module.exports = make;
mergeInto(module.exports, {
  isValue, isScalarValue, isMappingValue, isListValue
});
<commit_msg>Value: fix schema update<commit_after>/**
 * @jsx React.DOM
 * @preventMunge
 * @copyright Prometheus Research, LLC 2014
 */
'use strict';

var {Vector, Map, OrderedMap, Record}            = require('immutable');
var {isSchema, isList, isMapping, isScalar}      = require('./schema');
var ValidationResult                             = require('./ValidationResult');
var mergeInto                                    = require('./mergeInto');
var merge                                        = require('./merge');
var invariant                                    = require('./invariant');
var validate                                     = require('./validate');
var emptyFunction                                = require('./emptyFunction');
var toArray                                      = require('./toArray');

var DIRTY_KEY = '__react_forms_dirty__';

/**
 * Serves as a immutable container for form value attributes.
 */
var ValueAttributes = Record({
  schema: null,
  value: null,
  validation: null,
  externalValidation: null,
  serialized: null
}, 'ValueAttributes');

/**
 * Reference to the current form value.
 */
class Value {

  constructor(attributes, root, path) {
    this._attributes = attributes;
    this._root = root;
    this._cache = {};
    this._schema = null;
    this.path = path;
  }

  equals(other) {
    return (
      this.path.toString() === other.path.toString() &&
      this.schema.equals(other.schema) &&
      (
        this.value && this.value.equals ?
        this.value.equals(other.value) :
        this.value === other.value
      ) &&
      (
        this.serialized && this.serialized.equals ?
        this.serialized.equals(other.serialized) :
        this.serialized === other.serialized
      ) &&
      this.validation.equals(other.validation) &&
      this.externalValidation.equals(other.externalValidation) &&
      this.dirty === other.dirty &&
      this._root.get('onUpdate') === other._root.get('onUpdate')
    );
  }

  _child(key) {
    if (this._cache[key]) {
      return this._cache[key];
    }

    var schema = this.schema.child(key);
    var value = this.value.get(key);
    var schemaInstance = instantiateSchema(schema, value);
    var serialized = this.serialized.get(key);
    var validation = this.validation.child(key);
    var externalValidation = this.externalValidation.child(key);

    var attributes;
    if (value === undefined) {
      value = _defaultValue(schemaInstance);
      attributes = makeAttributes({schema, value, serialized, validation, externalValidation});
    } else {
      attributes = {schema, value, serialized, validation, externalValidation};
    }

    var ctor = _getCtor(schemaInstance);
    return (this._cache[key] = new ctor(
      this._attributes.merge(attributes),
      this._root,
      this.path.concat(key)
    ));
  }

  child(...key) {
    var value = this;
    for (var i = 0, len = key.length; i < len; i++) {
      value = value._child(key[i]);
    }
    return value;
  }

  childIn(keyPath) {
    return this.child.apply(this, keyPath);
  }

  update(newValue) {
    var trace = valueTraceByPath(this.root, this.path);
    var attributes;
    for (var i = 0, len = trace.length; i < len; i++) {
      var value = trace[i];
      if (i === 0) {
        attributes = makeAttributes({schema: value.schema, value: newValue});
      } else {
        attributes = value.onChildUpdate(prevValue.key, attributes);
      }
      var prevValue = value;
    }
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes.merge(attributes),
      this._root.merge({dirty, pendingRootRef}),
      []
    );
    var n = root.childIn(this.path);
    return n;
  }

  onChildUpdate(key, {value, validation, serialized}) {
    value = this.value.set(key, value);

    var schema = this.schema;
    var newSchema = instantiateSchema(this._attributes.schema, value);
    if (!schema.equals(newSchema)) {
      return makeAttributes({schema: newSchema, value}, {strip: true});
    }
    validation = this.validation.updateChild(key, validation);
    validation = validate(this.schema, value, validation.children).validation;
    serialized = this.serialized.set(key, serialized);
    return this._attributes.merge({value, serialized, validation});
  }

  updateChild(key, newValue) {
    return this.child(key).update(newValue).root();
  }

  updateChildIn(keyPath, newValue) {
    return this.childIn(keyPath).update(newValue).root();
  }

  updateSchema(newSchema) {
    // TODO: Should we try to keep serialized for unchanged parts of schema?
    var {_attributes: {value, externalValidation}} = this.root;
    return make(
      newSchema, value, externalValidation,
      this._root.get('onUpdate'),
      this._root.get('dirty'),
      this._root.get('rootRef'));
  }

  updateExternalValidation(newExternalValidation) {
    // TODO: Should we try to keep serialized for unchanged parts of schema?
    var {_attributes: {schema, value}} = this.root;
    return make(
      schema, value, newExternalValidation,
      this._root.get('onUpdate'),
      this._root.get('dirty'),
      this._root.get('rootRef'));
  }

  _makeDirty() {
    var dirty = this._root.get('dirty');
    return dirty.updateIn(this.path.concat(DIRTY_KEY), () => true);
  }

  markDirty() {
    var dirty = this._makeDirty();
    var root;
    var pendingRootRef = () => root;
    root = new this.root.constructor(
      this.root._attributes,
      this.root._root.merge({dirty, pendingRootRef}),
      []
    );
    return root.childIn(this.path);
  }

  markAsConsistent() {
    return new this.constructor(
      this._attributes,
      this._root.merge({pendingRootRef: null}),
      this.path
    );
  }

  notify() {
    var onUpdate = this._root.get('onUpdate', emptyFunction);
    onUpdate(this);
    return this;
  }
}

Object.defineProperty(Value.prototype, 'key', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    } else {
      return this.path[this.path.length - 1];
    }
  }
});

Object.defineProperty(Value.prototype, 'root', {
  get: function() {
    var ref = this._root.get('pendingRootRef');
    if (!ref) {
      ref = this._root.get('rootRef');
    }
    if (!ref) {
      return this;
    }
    return ref();
  }
});

Object.defineProperty(Value.prototype, 'parent', {
  get: function() {
    if (this.path.length === 0) {
      return null;
    }
    var path = this.path.slice(0);
    path.pop();
    return this.root.childIn(path);
  }
});

Object.defineProperty(Value.prototype, 'schema', {
  get: function() {
    if (this._schema === null) {
      this._schema = instantiateSchema(this._attributes.schema, this._attributes.value);
    }
    return this._schema;
  }
});

Object.defineProperty(Value.prototype, 'value', {
  get: function() {
    return this._attributes.value;
  }
});

Object.defineProperty(Value.prototype, 'serialized', {
  get: function() {
    var serialized = this._attributes.serialized;
    if (serialized === undefined) {
      return _defaultValue(this._attributes.schema);
    }
    return serialized;
  }
});

Object.defineProperty(Value.prototype, 'validation', {
  get: function() {
    return this._attributes.validation;
  }
});

Object.defineProperty(Value.prototype, 'externalValidation', {
  get: function() {
    return this._attributes.externalValidation;
  }
});

Object.defineProperty(Value.prototype, 'isValid', {
  get: function() {
    return this.validation.isSuccess;
  }
});

Object.defineProperty(Value.prototype, 'isDirty', {
  get: function() {
    var path = this.path;
    var dirty = this._root.get('dirty');
    for (var i = 0, len = path.length; i < len; i++) {
      if (dirty) {
        if (dirty.get(DIRTY_KEY) || dirty.get(path[i])) {
          return true;
        }
      } else {
        return false;
      }
      dirty = dirty.get(path[i]);
    }
    return dirty && (dirty.get(DIRTY_KEY) || dirty.length > 0);
  }
});

function valueTraceByPath(value, path) {
  var trace = [value];
  for (var i = 0, len = path.length; i < len; i++) {
    value = value.child(path[i]);
    trace.unshift(value);
  }
  return trace;
}

class ScalarValue extends Value {

}

class MappingValue extends Value {

  map(func, context) {
    return this.schema.children
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.schema.children.forEach((_, key) => {
      return func.call(context, this.child(key), key);
    });
  }
}

class ListValue extends Value {

  map(func, context) {
    return this.value
      .map((_, key) => func.call(context, this.child(key), key))
      .toJS();
  }

  forEach(func, context) {
    this.value.forEach((_, key) => func.call(context, this.child(key), key));
  }

  emptyChild() {
    return _defaultValue(this.schema.children);
  }

  push(...values) {
    var newValue = this.value.push.apply(this.value, values);
    return this.update(newValue);
  }

  splice() {
    var newValue = this.value.splice.apply(this.value, toArray(arguments));
    return this.update(newValue);
  }
}

function isValue(maybeValue) {
  return maybeValue instanceof Value;
}

function isScalarValue(value) {
  return value instanceof ScalarValue;
}

function isMappingValue(value) {
  return value instanceof MappingValue;
}

function isListValue(value) {
  return value instanceof ListValue;
}

function make(schema, value, externalValidation, onUpdate, dirty, rootRef) {
  externalValidation = externalValidation || ValidationResult.success;
  dirty = dirty || Map.empty();
  var attributes = makeAttributes({schema, value, externalValidation}, {root: true});
  var ctor = _getCtor(schema);
  rootRef = rootRef || (() => value);
  var value = new ctor(attributes, Map({onUpdate, dirty, rootRef}), []);
  return value;
}

function instantiateSchema(schema, value) {
  if (typeof schema === 'function') {
    schema = schema(value);
  }
  return schema;
}

function makeAttributes(args, options) {
  var {schema, value} = args;

  invariant(
    isSchema(schema),
    'make(schema, ...) has received not a schema value as its first argument'
  );

  var schemaInstance = instantiateSchema(schema, value);
  if (isScalar(schemaInstance)) {
    return _makeScalar(args, options);
  } else if (isMapping(schemaInstance)) {
    return _makeMapping(args, options);
  } else if (isList(schemaInstance)) {
    return _makeList(args, options);
  }
}

function _makeScalar(args) {
  var {value, schema, validation, serialized} = args;
  var schemaInstance = instantiateSchema(schema, value);
  if (value === undefined) {
    value = _defaultValue(schemaInstance);
    if (value === null) {
      return undefined;
    }
  }
  if (validation === undefined) {
    var validationResult = validate(schemaInstance, value);
    value = validationResult.value;
    validation = validationResult.validation;
  }
  if (serialized === undefined) {
    serialized = schemaInstance.type.serialize(value);
  }
  return new ValueAttributes(merge(args, {value, validation, serialized}));
}

function _makeMapping(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  var schemaInstance = instantiateSchema(schema, value);
  if (value === undefined) {
    if (options.root) {
      value = _defaultValue(schemaInstance);
    } else {
      return undefined;
    }
  }
  if (!(value instanceof OrderedMap)) {
    value = OrderedMap.from(value);
  }

  var _value = {};
  var _serialized = {};
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  schemaInstance.children.forEach((schema, name) => {
    var schemaInstance = instantiateSchema(schema, value.get(name));
    var child = makeAttributes({
      schema,
      value: value.get(name)
    }, {strip: options.strip});
    if (child === undefined) {
      if (schemaInstance.props.get('required')) {
        _hasChildError = true;
        _childrenValidation[name] = ValidationResult.failure('value is required');
      }
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value[name] = childValue;
    _serialized[name] = childSerialized;
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schemaInstance, _value);
  }
  value = value.merge(_value);
  if (options.strip) {
    value.forEach((_, key) =>{
      if (!schema.children.has(key)) {
        value = value.remove(key);
      }
    });
  }
  serialized = serialized || OrderedMap.from(_serialized);
  validation = validation || _validation;
  return new ValueAttributes({schema, value, serialized, validation, externalValidation});
}

function _makeList(args, options) {
  options = options || {};
  var {schema, value, externalValidation, serialized, validation} = args;
  var schemaInstance = instantiateSchema(schema, value);
  if (value === undefined) {
    if (options.root) {
      value = _defaultValue(schemaInstance);
    } else {
      return undefined;
    }
  }
  if (!(value instanceof Vector)) {
    value = Vector.from(value);
  }

  var _value = [];
  var _serialized = [];
  var _childrenValidation = {};
  var _hasChildError = false;
  var _validation;
  value.forEach((value, name) => {
    var child = makeAttributes({
      schema: schemaInstance.child(name),
      value
    }, {strip: options.strip});
    if (child === undefined) {
      return;
    }
    var {
      value: childValue,
      serialized: childSerialized,
      validation: childValidation
    } = child;
    _value.push(childValue);
    _serialized.push(childSerialized);
    if (childValidation.isFailure) {
      _hasChildError = true;
      _childrenValidation[name] = childValidation;
    }
  });
  if (_hasChildError) {
    _validation = new ValidationResult(null, OrderedMap(_childrenValidation));
  } else {
    var {value: _value, validation: _validation} = validate(schemaInstance, _value);
  }
  return new ValueAttributes({
    schema,
    value: Vector.from(_value),
    serialized: serialized || Vector.from(_serialized),
    validation: validation || _validation,
    externalValidation
  });
}

/**
 * Get value constructor for given schema node.
 *
 * @private
 * @param {Schema} schema
 * @returns {Constructor}
 */
function _getCtor(schema) {
  var constructor;
  if (isScalar(schema)) {
    constructor = ScalarValue;
  } else if (isMapping(schema)) {
    constructor = MappingValue;
  } else if (isList(schema)) {
    constructor = ListValue;
  } else {
    invariant(false, 'invalid schema node');
  }
  return constructor;
}

function _defaultValue(schema) {
  if (schema.defaultValue !== undefined) {
    return schema.defaultValue;
  } else if (isMapping(schema)) {
    return OrderedMap.empty();
  } else if (isList(schema)) {
    return Vector.empty();
  } else {
    return null;
  }
}

module.exports = make;
mergeInto(module.exports, {
  isValue, isScalarValue, isMappingValue, isListValue
});
<|endoftext|>


<commit_before>var signup = require('../controllers/signup.js');
var Polls = require('../models/polls.js');
var shortid = require('shortid');
var colors = require('../utils/colors.js');
var HIGHLIGHT_LUMINANCE = .2;
var POLLS_PER_PAGE = 20;

module.exports = function(app, passport) {

    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {
            res.redirect('/login');
        }
    }

    //From https://www.sitepoint.com/javascript-generate-lighter-darker-color/
    function ColorLuminance(hex, lum) {

        // validate hex string
        hex = String(hex).replace(/[^0-9a-f]/gi, '');
        if (hex.length < 6) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        lum = lum || 0;

        // convert to decimal and change luminosity
        var rgb = "#",
            c, i;
        for (i = 0; i < 3; i++) {
            c = parseInt(hex.substr(i * 2, 2), 16);
            c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
            rgb += ("00" + c).substr(c.length);
        }

        return rgb;
    }

    function voted(req, res, poll, next) {
        var voted = false;
        if (req.isAuthenticated()) {
            var userId = req.user._id;
            var index = poll.voterUserid.indexOf(userId);
            voted = voted || index > -1;
        } else if (req.ip) {
            voted = voted || poll.voterIP.indexOf(req.ip) > -1;
        }
        next(voted);
    }

    //TODO: Make sure output doesn't allow xxs
    function getChartData(poll, next) {
        var data = [];
        for (var i = 0; i < poll.options.length; i++) {
            data.push({
                value: poll.options[i].votes,
                color: poll.options[i].color,
                highlight: ColorLuminance(poll.options[i].color, HIGHLIGHT_LUMINANCE),
                label: poll.options[i].answer
            });
        }
        next(data);
    }

    app.route('/')
        .get(function(req, res) {
            Polls.find({}).limit(POLLS_PER_PAGE).exec(function(err, polls) {
                if (err) {
                    console.log(err);
                }
                res.render('home', {
                    isLoggedIn: req.isAuthenticated(),
                    polls: polls
                });
            })
        });

    app.route('/login')
        .get(function(req, res) {
            res.render('login', {
                isLoggedIn: req.isAuthenticated()
            });
        })
        .post(passport.authenticate('local', {
            failureRedirect: '/login' //TODO: Should tell the user there was an error.
        }), (req, res) => {
            res.redirect('/profile');
        });

    app.route('/signup')
        .get(function(req, res) {
            res.render('signup', {
                isLoggedIn: req.isAuthenticated()
            });
        })
        .post(signup,
            passport.authenticate('local', {
                failureRedirect: '/signup' //TODO: Should tell the user there was an error.
            }),
            (req, res, next) => {
                res.redirect('/profile');
            });

    app.route('/logout')
        .get(function(req, res) {
            req.logout();
            res.redirect('/login');
        });

    app.route('/profile')
        .get(isLoggedIn, function(req, res) {
            Polls.find({
                creatorUserid: req.user._id
            }, function(err, polls) {
                res.render('profile', {
                    isLoggedIn: req.isAuthenticated(),
                    id: req.user._id,
                    username: req.user.username,
                    myPolls: polls
                });
            })

        });

    app.route('/make')
        .get(isLoggedIn, function(req, res) {
            res.render('make', {
                isLoggedIn: req.isAuthenticated()
            });
        });

    app.route('/search')
        .get(function(req, res) {
            var q = req.query.q;
            Polls.find({
                $text: {
                    $search: q
                }
            }).limit(POLLS_PER_PAGE).exec(function(err, polls) {
                if (err) {
                    console.log(err);
                }
                res.render('home', {
                    isLoggedIn: req.isAuthenticated(),
                    polls: polls
                });
            })
        })

    app.route('/polls/:id')
        .get(function(req, res) { //TODO: Infinite scroll feature
            var id = req.params.id;
            if (shortid.isValid(id)) {
                Polls.findOne({
                    _id: id
                }, function(err, poll) {
                    if (err) {
                        console.log(err);
                    } else if (poll) {
                        voted(req, res, poll, function(voted) {
                            getChartData(poll, function(data) {
                                res.render('poll', {
                                    isLoggedIn: req.isAuthenticated(),
                                    question: poll.question,
                                    options: poll.options,
                                    createdDate: poll.date,
                                    pollId: poll.id,
                                    chartData: data,
                                    voted: voted
                                });
                            });
                        });
                    } else {
                        res.render('404', {
                            msg: "Poll not found."
                        });
                    }
                });
            }
        });

    //API
    app.route('/api/makePoll')
        .post(isLoggedIn, function(req, res) {
            var question = req.body.question;
            var inputOptions = req.body.options;
            var verifiedOptions = [];
            var colorSeed = Math.floor(Math.random() * colors.colors.length);
            for (var i in inputOptions) {
                if (i.match(/answer[0-9]+/)) {
                    verifiedOptions.push({
                        answer: inputOptions[i],
                        votes: 0,
                        color: colors.colors[(++colorSeed) % colors.colors.length]
                    })
                }
            }
            var poll = new Polls({
                question: question,
                options: verifiedOptions,
                creatorUserid: req.user._id
            });
            poll.save(function(err, data) {
                if (err) {
                    console.log(err);
                    res.render('make', {
                        isLoggedIn: req.isAuthenticated(),
                        msg: "Error while making poll."
                    })
                } else {
                    res.redirect('/polls/' + data._id); //TODO: redirect to new poll
                }
            });
        })

    app.route('/api/vote')
        .post(function(req, res) {
            var pollId = req.body.poll;
            var answer = req.body.answer;
            Polls.findOne({
                _id: pollId
            }, function(err, poll) {
                if (err) {
                    console.log(err);
                    res.json({
                        "error": "Poll not found. Vote not counted."
                    });
                    return;
                } else if (poll) {
                    voted(req, res, poll, function(voted) {
                        if (voted) {
                            res.json({
                                "error": "Already voted."
                            });
                            return;
                        } else {
                            var found = false;
                            var answerId;
                            for (var i = 0; i < poll.options.length; i++) {
                                if (answer == poll.options[i].answer) {
                                    poll.options[i].votes++;
                                    answerId = poll.options[i].id;
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                var randomColor = colors.colors[Math.floor(Math.random() * colors.colors.length)];
                                poll.options.push({
                                    answer: answer,
                                    votes: 1,
                                    color: randomColor
                                })
                            }
                            if (req.isAuthenticated()) {
                                var userId = req.user._id;
                                poll.voterUserid.push(userId);
                            }
                            var ip = req.headers['x-forwarded-for'] ||
                                req.connection.remoteAddress ||
                                req.socket.remoteAddress ||
                                req.connection.socket.remoteAddress;
                            if (ip) {
                                poll.voterIP.push(ip);
                            }
                            poll.save(function(err, savedPoll) {
                                if (err) {
                                    console.log(err)
                                    res.json({
                                        "error": "Poll not saved."
                                    });
                                } else {
                                    res.json({
                                        "success": "Vote counted.",
                                        "answerId": answerId
                                    });
                                }
                            });
                        }
                    })
                }
            })
        });

    app.route('/api/delete')
        .delete(isLoggedIn, function(req, res) {
            var pollId = req.body.pollId;
            var userId = req.user._id;
            Polls.findOne({
                _id: pollId
            }, function(err, poll) {
                if (err) {
                    console.log(err);
                    res.json({
                        error: "Error when trying to delete a poll"
                    });
                }
                if (poll && poll.creatorUserid == userId) {
                    poll.remove();
                    res.json({
                        success: "Poll Deleted"
                    });
                    //res.redirect('/profile');
                }
            });
        });

    //404 Not Found
    app.use((req, res, next) => {
        if (req.accepts('html')) {
            res.render('404');
        } else {
            res.status(404)
                .type('text')
                .send('Not Found');
        }
    });
};
<commit_msg>Checks x-forwarded-for for ips. More robust check.<commit_after>var signup = require('../controllers/signup.js');
var Polls = require('../models/polls.js');
var shortid = require('shortid');
var colors = require('../utils/colors.js');
var HIGHLIGHT_LUMINANCE = .2;
var POLLS_PER_PAGE = 20;

module.exports = function(app, passport) {

    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        } else {
            res.redirect('/login');
        }
    }

    //From https://www.sitepoint.com/javascript-generate-lighter-darker-color/
    function ColorLuminance(hex, lum) {

        // validate hex string
        hex = String(hex).replace(/[^0-9a-f]/gi, '');
        if (hex.length < 6) {
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
        }
        lum = lum || 0;

        // convert to decimal and change luminosity
        var rgb = "#",
            c, i;
        for (i = 0; i < 3; i++) {
            c = parseInt(hex.substr(i * 2, 2), 16);
            c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
            rgb += ("00" + c).substr(c.length);
        }

        return rgb;
    }

    function voted(req, res, poll, next) {
        var voted = false;
        var ip = req.headers['x-forwarded-for'] ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress;
        if (req.isAuthenticated()) {
            var userId = req.user._id;
            var index = poll.voterUserid.indexOf(userId);
            voted = voted || index > -1;
        } else if (ip) {
            voted = voted || poll.voterIP.indexOf(ip) > -1;
        }
        next(voted);
    }

    //TODO: Make sure output doesn't allow xxs
    function getChartData(poll, next) {
        var data = [];
        for (var i = 0; i < poll.options.length; i++) {
            data.push({
                value: poll.options[i].votes,
                color: poll.options[i].color,
                highlight: ColorLuminance(poll.options[i].color, HIGHLIGHT_LUMINANCE),
                label: poll.options[i].answer
            });
        }
        next(data);
    }

    app.route('/')
        .get(function(req, res) {
            Polls.find({}).limit(POLLS_PER_PAGE).exec(function(err, polls) {
                if (err) {
                    console.log(err);
                }
                res.render('home', {
                    isLoggedIn: req.isAuthenticated(),
                    polls: polls
                });
            })
        });

    app.route('/login')
        .get(function(req, res) {
            res.render('login', {
                isLoggedIn: req.isAuthenticated()
            });
        })
        .post(passport.authenticate('local', {
            failureRedirect: '/login' //TODO: Should tell the user there was an error.
        }), (req, res) => {
            res.redirect('/profile');
        });

    app.route('/signup')
        .get(function(req, res) {
            res.render('signup', {
                isLoggedIn: req.isAuthenticated()
            });
        })
        .post(signup,
            passport.authenticate('local', {
                failureRedirect: '/signup' //TODO: Should tell the user there was an error.
            }),
            (req, res, next) => {
                res.redirect('/profile');
            });

    app.route('/logout')
        .get(function(req, res) {
            req.logout();
            res.redirect('/login');
        });

    app.route('/profile')
        .get(isLoggedIn, function(req, res) {
            Polls.find({
                creatorUserid: req.user._id
            }, function(err, polls) {
                res.render('profile', {
                    isLoggedIn: req.isAuthenticated(),
                    id: req.user._id,
                    username: req.user.username,
                    myPolls: polls
                });
            })

        });

    app.route('/make')
        .get(isLoggedIn, function(req, res) {
            res.render('make', {
                isLoggedIn: req.isAuthenticated()
            });
        });

    app.route('/search')
        .get(function(req, res) {
            var q = req.query.q;
            Polls.find({
                $text: {
                    $search: q
                }
            }).limit(POLLS_PER_PAGE).exec(function(err, polls) {
                if (err) {
                    console.log(err);
                }
                res.render('home', {
                    isLoggedIn: req.isAuthenticated(),
                    polls: polls
                });
            })
        })

    app.route('/polls/:id')
        .get(function(req, res) { //TODO: Infinite scroll feature
            var id = req.params.id;
            if (shortid.isValid(id)) {
                Polls.findOne({
                    _id: id
                }, function(err, poll) {
                    if (err) {
                        console.log(err);
                    } else if (poll) {
                        voted(req, res, poll, function(voted) {
                            getChartData(poll, function(data) {
                                res.render('poll', {
                                    isLoggedIn: req.isAuthenticated(),
                                    question: poll.question,
                                    options: poll.options,
                                    createdDate: poll.date,
                                    pollId: poll.id,
                                    chartData: data,
                                    voted: voted
                                });
                            });
                        });
                    } else {
                        res.render('404', {
                            msg: "Poll not found."
                        });
                    }
                });
            }
        });

    //API
    app.route('/api/makePoll')
        .post(isLoggedIn, function(req, res) {
            var question = req.body.question;
            var inputOptions = req.body.options;
            var verifiedOptions = [];
            var colorSeed = Math.floor(Math.random() * colors.colors.length);
            for (var i in inputOptions) {
                if (i.match(/answer[0-9]+/)) {
                    verifiedOptions.push({
                        answer: inputOptions[i],
                        votes: 0,
                        color: colors.colors[(++colorSeed) % colors.colors.length]
                    })
                }
            }
            var poll = new Polls({
                question: question,
                options: verifiedOptions,
                creatorUserid: req.user._id
            });
            poll.save(function(err, data) {
                if (err) {
                    console.log(err);
                    res.render('make', {
                        isLoggedIn: req.isAuthenticated(),
                        msg: "Error while making poll."
                    })
                } else {
                    res.redirect('/polls/' + data._id); //TODO: redirect to new poll
                }
            });
        })

    app.route('/api/vote')
        .post(function(req, res) {
            var pollId = req.body.poll;
            var answer = req.body.answer;
            Polls.findOne({
                _id: pollId
            }, function(err, poll) {
                if (err) {
                    console.log(err);
                    res.json({
                        "error": "Poll not found. Vote not counted."
                    });
                    return;
                } else if (poll) {
                    voted(req, res, poll, function(voted) {
                        if (voted) {
                            res.json({
                                "error": "Already voted."
                            });
                            return;
                        } else {
                            var found = false;
                            var answerId;
                            for (var i = 0; i < poll.options.length; i++) {
                                if (answer == poll.options[i].answer) {
                                    poll.options[i].votes++;
                                    answerId = poll.options[i].id;
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                var randomColor = colors.colors[Math.floor(Math.random() * colors.colors.length)];
                                poll.options.push({
                                    answer: answer,
                                    votes: 1,
                                    color: randomColor
                                })
                            }
                            if (req.isAuthenticated()) {
                                var userId = req.user._id;
                                poll.voterUserid.push(userId);
                            }
                            var ip = req.headers['x-forwarded-for'] ||
                                req.connection.remoteAddress ||
                                req.socket.remoteAddress ||
                                req.connection.socket.remoteAddress;
                            if (ip) {
                                poll.voterIP.push(ip);
                            }
                            poll.save(function(err, savedPoll) {
                                if (err) {
                                    console.log(err)
                                    res.json({
                                        "error": "Poll not saved."
                                    });
                                } else {
                                    res.json({
                                        "success": "Vote counted.",
                                        "answerId": answerId
                                    });
                                }
                            });
                        }
                    })
                }
            })
        });

    app.route('/api/delete')
        .delete(isLoggedIn, function(req, res) {
            var pollId = req.body.pollId;
            var userId = req.user._id;
            Polls.findOne({
                _id: pollId
            }, function(err, poll) {
                if (err) {
                    console.log(err);
                    res.json({
                        error: "Error when trying to delete a poll"
                    });
                }
                if (poll && poll.creatorUserid == userId) {
                    poll.remove();
                    res.json({
                        success: "Poll Deleted"
                    });
                    //res.redirect('/profile');
                }
            });
        });

    //404 Not Found
    app.use((req, res, next) => {
        if (req.accepts('html')) {
            res.render('404');
        } else {
            res.status(404)
                .type('text')
                .send('Not Found');
        }
    });
};
<|endoftext|>


<commit_before>exports.conf = {
  "tasks": {
    "all_docs": function (util, doc) {
      console.log(doc);
    }
  }
};
<commit_msg>Use util.log for logging example.<commit_after>exports.conf = {
  "tasks": {
    "all_docs": function (util, doc) {
      util.log(doc);
    }
  }
};
<|endoftext|>


<commit_before>'use strict';

var extend = require('gextend');
var util = require('util');
var path = require('path');
var events = require('events');
var fs = require('fs');
var debug;

var ROOT_NAME = 'root';

var DEFAULTS = {
    autoinitialize: true,
    name: ROOT_NAME,
    paths:{},
    path:process.cwd(),
    ignore: [],
    requiredModules:['routes', 'middleware'],
    moduleIds: {
        environment:'environment',
        routes:'routes',
        middleware:'middleware',
        sockets:'sockets'
    },
    mountpath: '',
    configname:'.anden.json',
    staticDir: 'public',
    defaultMiddleware:true,
    port: process.env.PORT || 9000,
    host: 'localhost'
};

var Anden = function(options) {
	events.EventEmitter.call(this);
    options = extend({}, this.constructor.DEFAULTS, options);
    if (options.autoinitialize) this.init(options);
};

util.inherits(Anden, events.EventEmitter);

Anden.DEFAULTS = DEFAULTS;
Anden.ROOT_NAME = ROOT_NAME;

Anden.prototype.init = function(options) {
    if (this.initialized) return;
    this.initialized = true;

    extend(this, this.constructor.DEFAULTS, options);
    //loadConf depends on having the right path, that is why we
    //first set the path, and then load the config.
    extend(this, this.loadConf());

    debug = require('debug')('anden:'+this.name);
    debug('INIT module', this.name);

    //Run core modules
    this.loaded = require('./init').call(this);

    console.log('SUCCESS',this.name, this.loaded);

    this.emit('postinit.'+this.name);
};

Anden.prototype.run = function(config) {
    //TODO: What happens if we have config.path?
    //should we pick config.port & config.host?
    extend(this, config || {});

    this.logger.log('START!', this.name, Object.keys(this.subapps));

    // this.engine.run();
    var server = this.server.listen(this.port, this.host, function(){
        var address = 'http://'+server.address().address + ':' + server.address().port;
        debug('[%s] *** Anden running express server on %s ***', this.name, address);
    }.bind(this));

    this.emit('run');
};

Anden.prototype.loadConf = function(){
    var configpath = path.join(this.path, this.configname);
    if(! fs.existsSync(configpath)) return;
    var config = {};
    try {
        config = require(configpath);
    } catch(e){
        this.logger.log('ERROR loading config %s', configpath);
    }
    return config;
};

Anden.prototype.isRoot = function(){
    return this.name === this.constructor.ROOT_NAME;
}

Anden.prototype.logger = console;

Object.defineProperty(Anden.prototype, 'path', {
    get: function() { return this._path; },
    set: function(p) { this._path = path.resolve(p); },
    enumerable: true,
    configurable: true
});

Object.defineProperty(Anden.prototype, 'ignore', {
    get: function(){ return this._ignore;},
    set: function(i) {
        this._ignore = i.concat(this._ignore || []).filter(function(item, pos, self) {
            return self.indexOf(item) === pos;
        });
    },
    enumerable:true,
    configurable:true
});

module.exports = Anden;<commit_msg>LIB: Added registerSubapp method<commit_after>'use strict';

var extend = require('gextend');
var util = require('util');
var path = require('path');
var events = require('events');
var fs = require('fs');
var debug;

var ROOT_NAME = 'root';

var DEFAULTS = {
    autoinitialize: true,
    name: ROOT_NAME,
    paths:{},
    path:process.cwd(),
    ignore: [],
    subapps:{},
    requiredModules:['routes', 'middleware'],
    moduleIds: {
        environment:'environment',
        routes:'routes',
        middleware:'middleware',
        sockets:'sockets'
    },
    mountpath: '',
    configname:'.anden.json',
    staticDir: 'public',
    defaultMiddleware:true,
    port: process.env.PORT || 9000,
    host: 'localhost'
};

var Anden = function(options) {
	events.EventEmitter.call(this);
    options = extend({}, this.constructor.DEFAULTS, options);
    if (options.autoinitialize) this.init(options);
};

util.inherits(Anden, events.EventEmitter);

Anden.DEFAULTS = DEFAULTS;
Anden.ROOT_NAME = ROOT_NAME;

Anden.prototype.init = function(options) {
    if (this.initialized) return;
    this.initialized = true;

    extend(this, this.constructor.DEFAULTS, options);
    //loadConf depends on having the right path, that is why we
    //first set the path, and then load the config.
    extend(this, this.loadConf());

    debug = require('debug')('anden:'+this.name);
    debug('INIT module', this.name);

    //Run core modules
    this.loaded = require('./init').call(this);

    console.log('SUCCESS',this.name, this.loaded);

    this.emit('postinit.'+this.name);
};

Anden.prototype.run = function(config) {
    //TODO: What happens if we have config.path?
    //should we pick config.port & config.host?
    extend(this, config || {});

    this.logger.log('START!', this.name, Object.keys(this.subapps));

    // this.engine.run();
    var server = this.server.listen(this.port, this.host, function(){
        var address = 'http://'+server.address().address + ':' + server.address().port;
        debug('[%s] *** Anden running express server on %s ***', this.name, address);
    }.bind(this));

    this.emit('run');
};

Anden.prototype.loadConf = function(){
    var configpath = path.join(this.path, this.configname);
    if(! fs.existsSync(configpath)) return;
    var config = {};
    try {
        config = require(configpath);
    } catch(e){
        this.logger.log('ERROR loading config %s', configpath);
    }
    return config;
};

Anden.prototype.isRoot = function(){
    return this.name === this.constructor.ROOT_NAME;
};

Anden.prototype.registerSubapp = function(name){
    var subapp = new Anden({
        name:name,
        path: path.join(this.path, name),
        mountpath: this.mountpath + '/' + name,
        server: this.server,
        sockets: this.sockets
    });

    if (!subapp.loaded) return;
    this.app.use('/' + name, subapp.app);
    this.subapps[name] = subapp;
};

Anden.prototype.logger = console;

Object.defineProperty(Anden.prototype, 'path', {
    get: function() { return this._path; },
    set: function(p) { this._path = path.resolve(p); },
    enumerable: true,
    configurable: true
});

Object.defineProperty(Anden.prototype, 'ignore', {
    get: function(){ return this._ignore;},
    set: function(i) {
        this._ignore = i.concat(this._ignore || []).filter(function(item, pos, self) {
            return self.indexOf(item) === pos;
        });
    },
    enumerable:true,
    configurable:true
});

module.exports = Anden;<|endoftext|>