<commit_before>'use strict';

define(['app/welcome', 'app/gui'], function () {

    function AppCtrl($scope, session, $state, sessions, alerts, $cookies) {
        $scope.session = session;
        $scope.$state = $state;

        $scope.signOut = function () {
            sessions.delete('current').success(function () {
                $cookies.remove('session-token');
                session.terminate();
                alerts.prepareSuccess('Odhlášení proběhlo úspěšně.');
                $state.go('welcome.signIn');
            });
        };
    }

    angular.module('app.sections', ['ui.router', 'app.welcome', 'app.gui', 'ngCookies'])

        .config(function ($stateProvider, $urlRouterProvider) {
            $stateProvider
                .state('welcome', {
                    abstract: true,
                    templateUrl: 'app/sections/welcome.html'
                })
                .state('app', {
                    abstract: true,
                    url: '/app',
                    controller: AppCtrl,
                    templateUrl: 'app/sections/app.html'
                })
                .state('loading', {
                    templateUrl: 'app/sections/loading.html'
                });

            $urlRouterProvider.otherwise('/');
        })

        .run(function ($rootScope, $state, $cookies, session, $view, sessions, alerts, $http) {
            $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
                if (toState.name === 'loading') {
                    return;
                }

                var state = toState.name;
                var params = toParams;
                var section = state.split('.')[0];

                if (session.isActive()) {
                    if (section === 'welcome') {
                        $state.go('app.order.grid');
                        event.preventDefault();
                    }
                    return;
                }

                var token = $cookies.get('session-token');

                if (!token) {
                    if (section === 'app') {
                        alerts.prepareInfo('Přihlaste se, prosím.');
                        $state.go('welcome.signIn');
                        event.preventDefault();
                    }
                    return;
                }

                $state.go('loading');
                $http.defaults.headers.common['X-Session-Token'] = token;

                event.preventDefault();

                sessions.read('current').success(function (data, code) {
                    if (code === 200) { // session is active
                        session.start(data.token, data.user);
                        $state.go(section === 'welcome' ? 'app.order.grid' : state, params);
                        event.preventDefault();

                    } else { // session not found or expired
                        session.terminate();
                        $cookies.remove('session-token');

                        if (section === 'app') {
                            alerts.prepareInfo('Přihlaste se, prosím.');
                        }
                        $state.go(section === 'app' ? 'welcome.signIn' : state, params);
                        event.preventDefault();
                    }
                });
            });
        });

});
<commit_msg>fix: if the user is signed in and clicks on the set password link in an email then he is automatically signed out<commit_after>'use strict';

define(['app/welcome', 'app/gui'], function () {

    function AppCtrl($scope, session, $state, sessions, alerts, $cookies) {
        $scope.session = session;
        $scope.$state = $state;

        $scope.signOut = function () {
            sessions.delete('current').success(function () {
                $cookies.remove('session-token');
                session.terminate();
                alerts.prepareSuccess('Odhlášení proběhlo úspěšně.');
                $state.go('welcome.signIn');
            });
        };
    }

    angular.module('app.sections', ['ui.router', 'app.welcome', 'app.gui', 'ngCookies'])

        .config(function ($stateProvider, $urlRouterProvider) {
            $stateProvider
                .state('welcome', {
                    abstract: true,
                    templateUrl: 'app/sections/welcome.html'
                })
                .state('app', {
                    abstract: true,
                    url: '/app',
                    controller: AppCtrl,
                    templateUrl: 'app/sections/app.html'
                })
                .state('loading', {
                    templateUrl: 'app/sections/loading.html'
                });

            $urlRouterProvider.otherwise('/');
        })

        .run(function ($rootScope, $state, $cookies, session, $view, sessions, alerts, $http) {
            $rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
                if (toState.name === 'loading') {
                    return;
                }

                if (toState.name === 'welcome.setPassword') {
                    session.terminate();
                    $cookies.remove('session-token');
                    return;
                }

                var state = toState.name;
                var params = toParams;
                var section = state.split('.')[0];

                if (session.isActive()) {
                    if (section === 'welcome') {
                        $state.go('app.order.grid');
                        event.preventDefault();
                    }
                    return;
                }

                var token = $cookies.get('session-token');

                if (!token) {
                    if (section === 'app') {
                        alerts.prepareInfo('Přihlaste se, prosím.');
                        $state.go('welcome.signIn');
                        event.preventDefault();
                    }
                    return;
                }

                $state.go('loading');
                $http.defaults.headers.common['X-Session-Token'] = token;

                event.preventDefault();

                sessions.read('current').success(function (data, code) {
                    if (code === 200) { // session is active
                        session.start(data.token, data.user);
                        $state.go(section === 'welcome' ? 'app.order.grid' : state, params);
                        event.preventDefault();

                    } else { // session not found or expired
                        session.terminate();
                        $cookies.remove('session-token');

                        if (section === 'app') {
                            alerts.prepareInfo('Přihlaste se, prosím.');
                        }
                        $state.go(section === 'app' ? 'welcome.signIn' : state, params);
                        event.preventDefault();
                    }
                });
            });
        });

});
<|endoftext|>


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

var path = require('path');
var _ = require('underscore');
var routes = require('./src/routes');
var app = express();

console.log('Starting BeamWare Server...');

// set application paths
app.set('views', path.join(__dirname, 'src/views'));
app.set('util', path.join(__dirname, 'src/util'));

// set routes and tell express to accept JSON docs
app.use(bodyParser.json());
app.use('/', routes);

// listen on port 3000
app.listen(3000);
console.log('Started! Listening on port 3000.');

process.on('SIGINT', function() {
    console.log('Recevied SIGINT, exiting...');
    process.exit(0);
});

// export the app
module.exports = app;
<commit_msg>added proper error handlers from express-gen<commit_after>var express = require('express');
var bodyParser = require('body-parser');

var path = require('path');
var _ = require('underscore');
var routes = require('./src/routes');
var app = express();

console.log('Starting BeamWare Server...');

// set application paths
app.set('views', path.join(__dirname, 'src/views'));
app.set('util', path.join(__dirname, 'src/util'));

// set routes and tell express to accept JSON docs
app.use(bodyParser.json());
app.use('/', routes);

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

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

// listen on port 3000
app.listen(3000);
console.log('Started! Listening on port 3000.');

process.on('SIGINT', function() {
    console.log('Recevied SIGINT, exiting...');
    process.exit(0);
});

// export the app
module.exports = app;
<|endoftext|>


<commit_before>// Basic test case
var Botkit = require('botkit');

var controller = Botkit.slackbot({
  debug: true
});

// connect the bot to a stream of messages
controller.spawn({
  token: process.env.SLACK_TOKEN,
}).startRTM()

// give the bot something to listen for.
controller.on('mention',function(bot,message) {
  console.log(message);
  var namesToDrop = message.text.split(' -');
  var allNames = ["Addison", "Christian", "Chris", "Jarom", "Josh", "KC", "Keshav", "Will"];
  names = allNames.diff(namesToDrop);
  shuffle(names);
  bot.reply(message,names.join('\n'));
});

// Fisher–Yates shuffle - thanks stack overflow
// http://stackoverflow.com/a/6274398/3221576
function shuffle(array) {
  var counter = array.length;

  // While there are elements in the array
  while (counter > 0) {
    // Pick a random index
    var index = Math.floor(Math.random() * counter);

    // Decrease counter by 1
    counter--;

    // And swap the last element with it
    var temp = array[counter];
    array[counter] = array[index];
    array[index] = temp;
  }

  return array;
}

// Array diff - thanks stack overflow
// http://stackoverflow.com/a/4026828/3221576
// case insensitive indexOf - thanks stack overflow
// http://stackoverflow.com/a/40195757/3221576
Array.prototype.diff = function(a) {
    return this.filter(function(i) {
      indexOf = a.findIndex(item => i.toLowerCase() === item.toLowerCase());
      return indexOf < 0;
    });
};
<commit_msg>I wish I had a testing environment for this bot<commit_after>// Basic test case
var Botkit = require('botkit');

var controller = Botkit.slackbot({
  debug: true
});

// connect the bot to a stream of messages
controller.spawn({
  token: process.env.SLACK_TOKEN,
}).startRTM()

// give the bot something to listen for.
controller.on(['direct_message','direct_mention','mention'], function(bot, message) {
  console.log(message);
  var namesToDrop = message.text.split(' -');
  var allNames = ["Addison", "Christian", "Chris", "Jarom", "Josh", "KC", "Keshav", "Will"];
  names = allNames.diff(namesToDrop);
  shuffle(names);
  bot.reply(message,names.join('\n'));
});

// Fisher–Yates shuffle - thanks stack overflow
// http://stackoverflow.com/a/6274398/3221576
function shuffle(array) {
  var counter = array.length;

  // While there are elements in the array
  while (counter > 0) {
    // Pick a random index
    var index = Math.floor(Math.random() * counter);

    // Decrease counter by 1
    counter--;

    // And swap the last element with it
    var temp = array[counter];
    array[counter] = array[index];
    array[index] = temp;
  }

  return array;
}

// Array diff - thanks stack overflow
// http://stackoverflow.com/a/4026828/3221576
// case insensitive indexOf - thanks stack overflow
// http://stackoverflow.com/a/40195757/3221576
Array.prototype.diff = function(a) {
    return this.filter(function(i) {
      indexOf = a.findIndex(item => i.toLowerCase() === item.toLowerCase());
      return indexOf < 0;
    });
};
<|endoftext|>


<commit_before>
var myApp = angular.module('CordovaAppHarness', ['ngRoute']);

myApp.config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/', {
        templateUrl: 'views/list.html',
        controller: 'ListCtrl'
    });
    $routeProvider.when('/add', {
        templateUrl: 'views/add.html',
        controller: 'AddCtrl'
    });
    $routeProvider.when('/edit/:appId', {
        templateUrl: 'views/add.html',
        controller: 'AddCtrl'
    });
    $routeProvider.when('/details/:index', {
        templateUrl: 'views/details.html',
        controller: 'DetailsCtrl'
    });
}]);

// foo
document.addEventListener('deviceready', function() {
    cordova.plugins.fileextras.getDataDirectory(false, function(dirEntry) {
        var path = dirEntry.fullPath;
        myApp.value('INSTALL_DIRECTORY', path + '/apps');
        myApp.value('APPS_JSON', path + '/apps.json');

        myApp.factory('UrlCleanup', function() {
            return function(url) {
                url = url.replace(/\/$/, '').replace(new RegExp(cordova.platformId + '$'), '').replace(/\/$/, '');
                if (!/^[a-z]+:/.test(url)) {
                    url = 'http://' + url;
                }
                return url;
            };
        });

        angular.bootstrap(document, ['CordovaAppHarness']);
    });
}, false);
<commit_msg>Use updated symbol path for file-system-roots plugin<commit_after>
var myApp = angular.module('CordovaAppHarness', ['ngRoute']);

myApp.config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/', {
        templateUrl: 'views/list.html',
        controller: 'ListCtrl'
    });
    $routeProvider.when('/add', {
        templateUrl: 'views/add.html',
        controller: 'AddCtrl'
    });
    $routeProvider.when('/edit/:appId', {
        templateUrl: 'views/add.html',
        controller: 'AddCtrl'
    });
    $routeProvider.when('/details/:index', {
        templateUrl: 'views/details.html',
        controller: 'DetailsCtrl'
    });
}]);

// foo
document.addEventListener('deviceready', function() {
    cordova.filesystem.getDataDirectory(false, function(dirEntry) {
        var path = dirEntry.fullPath;
        myApp.value('INSTALL_DIRECTORY', path + '/apps');
        myApp.value('APPS_JSON', path + '/apps.json');

        myApp.factory('UrlCleanup', function() {
            return function(url) {
                url = url.replace(/\/$/, '').replace(new RegExp(cordova.platformId + '$'), '').replace(/\/$/, '');
                if (!/^[a-z]+:/.test(url)) {
                    url = 'http://' + url;
                }
                return url;
            };
        });

        angular.bootstrap(document, ['CordovaAppHarness']);
    });
}, false);
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var http = require('http');
var path = require('path');
var async = require('async');
var hbs = require('express-hbs');
// var baucis = require('baucis');
var socketIO = require('socket.io');
var mongoose = require('mongoose');
// var passport = require("passport");
// var LocalStrategy = require('passport-local').Strategy;
// var FacebookStrategy = require('passport-facebook').Strategy;

var uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/swabcast';
var theport = process.env.PORT || 9000;
// Makes connection asynchronously.  Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(uristring, function(err, res) {
    if (err) {
        console.log('ERROR connecting to: ' + uristring + '. ' + err);
    } else {
        console.log('Succeeded connected to: ' + uristring);
    }
});
var db = mongoose.connection;

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

    var app = express();
    app.configure(function() {
        app.set('port', theport);
        app.set('view engine', 'handlebars');
        app.set('views', __dirname + '../app/scripts/views');
    });
    /* userauths Model Schema */
    var LocalUserSchema = new mongoose.Schema({
        username: String,
        salt: String,
        hash: String,
        userDocument: String
    });
    /* FbUsers model Schema */
    var FacebookUserSchema = new mongoose.Schema({
        fbId: String,
        email: {
            type: String,
            lowercase: true
        },
        name: String,
        userDocument: String
    });
    /* Subscription Model Schema */
    var Keyword = new mongoose.Schema({
        keyword: String
    });
    var Episode = new mongoose.Schema({
        uid: Number,
        mediaUrl: String,
        duration: Number,
        episodeTitle: String,
        episodeSummary: String
    });
    var Subscription = new mongoose.Schema({
        feedUrl: String,
        subscriptionTitle: String,
        summary: String,
        albumArt: String,
        explicit: Boolean,
        keywords: [Keyword],
        episodes: [Episode]
    });
    /* UserDocument Model Schema */
    var NewEpisodes = new mongoose.Schema({
        newEpisodes: String
    });
    var KeywordPopulation = new mongoose.Schema({
        Keyword: String,
        Count: Number
    });
    var SubscribedEpisode = new mongoose.Schema({
        uid: Number,
        mediaUrl: String,
        episodeTitle: String,
        episodeSummary: String,
        duration: Number,
        position: Number,
        played: Boolean,
        archived: Boolean
    });
    var Subscribed = new mongoose.Schema({
        title: String,
        feedUrl: String,
        feedUid: String,
        summary: String,
        albumArt: String,
        archived: Boolean,
        newEpisodes: [NewEpisodes],
        keywords: [Keyword],
        episodes: [SubscribedEpisode]
    });
    var UserDocument = new mongoose.Schema({
        userId: String,
        keywordPopulation: [KeywordPopulation],
        subscriptions: [Subscribed]
    });
    /* @Model UsersModel */
    var Users = mongoose.model('userauths', LocalUserSchema);
    /* @Model Facebook Users Model */
    // var FbUsers = mongoose.model('fbs', FacebookUserSchema);
    /* @Model SubscriptionModel */
    var SubscriptionModel = mongoose.model('subscription', Subscription);
    /* @Model UserDocumentModel */
    var UserDocumentModel = mongoose.model('userDocument', UserDocument);
    /*
     * TODO - add checking validation for existing
     * TODO - if (!exists) {attempt parsing/retrieving based on URL}
     * Schema for custom subscription feed
     */
    // var CustomRSS = new mongoose.Schema({
    //     feedUrl: String
    // });
    // var CustomFeedModel = mongoose.model( 'CustomRSS', CustomRSS );
    // simple log
    app.use(function(req, res, next) {
        console.log('%s %s', req.method, req.url);
        next();
    });
    // mount static
    app.use(express.static(path.join(__dirname, '../app')));
    app.use(express.static(path.join(__dirname, '../.tmp')));
    // include passport authentication middleware
    // app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use( app.router );
    app.use( express.methodOverride() );
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
    // app.use(express.session({
    //     secret: 'SECRET'
    // }));
    // app.use(passport.initialize());
    // app.use(passport.session());
    //passport local strategy
    // passport.use(new LocalStrategy(function(username, password, done) {
    //     Users.findOne({
    //         username: username
    //     }, function(err, user) {
    //         if (err) {
    //             return done(err);
    //         }
    //         if (!user) {
    //             return done(null, false, {
    //                 message: 'Incorrect username.'
    //             });
    //         }
    //         hash(password, user.salt, function(err, hash) {
    //             if (err) {
    //                 return done(err);
    //             }
    //             if (hash == user.hash) return done(null, user);
    //             done(null, false, {
    //                 message: 'Incorrect password.'
    //             });
    //         });
    //     });
    // }));
    // passport.use(new FacebookStrategy({
    //     clientID: 'YOUR ID',
    //     clientSecret: 'YOUR CODE',
    //     callbackURL: 'http://localhost:3000/auth/facebook/callback'
    // }, function(accessToken, refreshToken, profile, done) {
    //     FbUsers.findOne({
    //         fbId: profile.id
    //     }, function(err, oldUser) {
    //         if (oldUser) {
    //             done(null, oldUser);
    //         } else {
    //             var newUser = new FbUsers({
    //                 fbId: profile.id,
    //                 email: profile.emails[0].value,
    //                 name: profile.displayName
    //             }).save(function(err, newUser) {
    //                 if (err) {
    //                     throw err;
    //                 }
    //                 done(null, newUser);
    //             });
    //         }
    //     });
    // }));
    // // set the user to req.user and establish a session via a cookie set in the user’s browser
    // passport.serializeUser(function(user, done) {
    //     done(null, user.id);
    // });
    // passport.deserializeUser(function(id, done) {
    //     Users.findById(id, function(err, user) {
    //         if (err) {
    //             done(err);
    //         }
    //         done(null, user);
    //     });
    // });

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

    // function userExist(req, res, next) {
    //     Users.count({
    //         username: req.body.username
    //     }, function(err, count) {
    //         if (count === 0) {
    //             next();
    //         } else {
    //             // req.session.error = "User Exist"
    //             res.redirect('/singup');
    //         }
    //     });
    // }
    /**
     **  @SECTION API
     **/
    // app.get('/auth/facebook', passport.authenticate('facebook', {
    //     scope: 'email'
    // }));
    // app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    //     failureRedirect: '/login'
    // }), function(req, res) {
    //     res.render('loggedin', {
    //         user: req.user
    //     });
    // });
    app.get('/', function(req, res) {
        res.sendfile(path.join(__dirname, '../app/index.html'));
    });
    app.get( '/api', function( request, response ) {
        response.send( 'Library API is running' );
    });
    app.get( '/api/static_collection/', function( request, response ) {
        response.sendfile(path.join(__dirname, '../app/static_feeds.json'));
    });
    app.get('/api/subscriptions', function(req, res) {
        return SubscriptionModel.find(function(err, subscriptions) {
            if (!err) {
                return res.send(subscriptions);
            } else {
                return console.log(err);
            }
        });
    });
    app.get('/api/subscriptions/:id', function(request, response) {
        return SubscriptionModel.findById(request.params.id, function(err, subscriptions) {
            if (!err) {
                return response.send(Subscription);
            } else {
                return console.log('subscription not found for id %s, error: %s', request.params.id, err);
            }
        });
    });
    app.post( '/api/subscriptions', function( request, response ) {

        var Subscription = new SubscriptionModel({
            feedUrl: request.body.feedUrl,
            subscriptionTitle: request.body.subscriptionTitle,
            summary: request.body.summary,
            albumArt: request.body.albumArt,
            explicit: request.body.explicit,
            keywords: null,
            episodes: null
        });
        Subscription.save( function( err ) {
            if( !err ) {
                return console.log( 'created' );
            } else {
                return console.log( err );
            }
        });
        return response.send( Subscription );
    });
    app.get('/api/subscribed', function(req, res) {
        return SubscriptionModel.find(function(err, subscribed) {
            if (!err) {
                return res.send(subscribed);
            } else {
                return console.log(err);
            }
        });
    });
    app.get('/api/subscribed/', function(req, res) {
        //will need to get auth_token and retrieve UserDocumentModel._id
        return UserDocumentModel.findById('5302cf4471349a081e000007', function(err, subscription) {
            if (!err) {
                return res.send(subscription);
            } else {
                return console.log('subscription not found for id %s, error: %s', req.params.id, err);
            }
        });
    });
    //TODO - validate
    app.put('/api/subscribed/:id/episode/:episode/:action/', function(req, res) {
        return SubscriptionModel.findById(req.params.id, req.params.episode, req.params.action, function(err, subscription) {
            if (!err) {
                return res.send(subscription);
            } else {
                return console.log('subscription not found for id %s, error: %s', req.params.id, err);
            }
        });
    });
    app.put('/api/subscribe/:id', function(req) {
        // get subscription from subscriptions collection
        var subscription = function() {
            return SubscriptionModel.findById(req.params.id, function(err, subscription) {
                if (!err) {
                    return subscription;
                } else {
                    return console.log('subscription not found for id %s, error: %s', req.params.id, err);
                }
            });
        };
        var s = new Subscribed(subscription);
        //copy subscription to user subscribed document
        UserDocumentModel.findById(req.authToken, function(err, userDoc) {
            if (!err) {
                userDoc.Subscribed.push(s);
                return console.log('success!');
            } else {
                return console.log('subscription not found for id %s, error: %s', req.params.id, err);
            }
        });
    });
    // TODO implement adding custom subscription
    // start server
    http.createServer(app).listen(app.get('port'), function() {
        console.log('Express App started!');
    });
});

<commit_msg>changing to dist folder<commit_after>'use strict';

var express = require('express');
var http = require('http');
var path = require('path');
var async = require('async');
var hbs = require('express-hbs');
// var baucis = require('baucis');
var socketIO = require('socket.io');
var mongoose = require('mongoose');
// var passport = require("passport");
// var LocalStrategy = require('passport-local').Strategy;
// var FacebookStrategy = require('passport-facebook').Strategy;

var uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/swabcast';
var theport = process.env.PORT || 9000;
// Makes connection asynchronously.  Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(uristring, function(err, res) {
    if (err) {
        console.log('ERROR connecting to: ' + uristring + '. ' + err);
    } else {
        console.log('Succeeded connected to: ' + uristring);
    }
});
var db = mongoose.connection;

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

    var app = express();
    app.configure(function() {
        app.set('port', theport);
        app.set('view engine', 'handlebars');
        app.set('views', __dirname + '../dist/assets');
    });
    /* userauths Model Schema */
    var LocalUserSchema = new mongoose.Schema({
        username: String,
        salt: String,
        hash: String,
        userDocument: String
    });
    /* FbUsers model Schema */
    var FacebookUserSchema = new mongoose.Schema({
        fbId: String,
        email: {
            type: String,
            lowercase: true
        },
        name: String,
        userDocument: String
    });
    /* Subscription Model Schema */
    var Keyword = new mongoose.Schema({
        keyword: String
    });
    var Episode = new mongoose.Schema({
        uid: Number,
        mediaUrl: String,
        duration: Number,
        episodeTitle: String,
        episodeSummary: String
    });
    var Subscription = new mongoose.Schema({
        feedUrl: String,
        subscriptionTitle: String,
        summary: String,
        albumArt: String,
        explicit: Boolean,
        keywords: [Keyword],
        episodes: [Episode]
    });
    /* UserDocument Model Schema */
    var NewEpisodes = new mongoose.Schema({
        newEpisodes: String
    });
    var KeywordPopulation = new mongoose.Schema({
        Keyword: String,
        Count: Number
    });
    var SubscribedEpisode = new mongoose.Schema({
        uid: Number,
        mediaUrl: String,
        episodeTitle: String,
        episodeSummary: String,
        duration: Number,
        position: Number,
        played: Boolean,
        archived: Boolean
    });
    var Subscribed = new mongoose.Schema({
        title: String,
        feedUrl: String,
        feedUid: String,
        summary: String,
        albumArt: String,
        archived: Boolean,
        newEpisodes: [NewEpisodes],
        keywords: [Keyword],
        episodes: [SubscribedEpisode]
    });
    var UserDocument = new mongoose.Schema({
        userId: String,
        keywordPopulation: [KeywordPopulation],
        subscriptions: [Subscribed]
    });
    /* @Model UsersModel */
    var Users = mongoose.model('userauths', LocalUserSchema);
    /* @Model Facebook Users Model */
    // var FbUsers = mongoose.model('fbs', FacebookUserSchema);
    /* @Model SubscriptionModel */
    var SubscriptionModel = mongoose.model('subscription', Subscription);
    /* @Model UserDocumentModel */
    var UserDocumentModel = mongoose.model('userDocument', UserDocument);
    /*
     * TODO - add checking validation for existing
     * TODO - if (!exists) {attempt parsing/retrieving based on URL}
     * Schema for custom subscription feed
     */
    // var CustomRSS = new mongoose.Schema({
    //     feedUrl: String
    // });
    // var CustomFeedModel = mongoose.model( 'CustomRSS', CustomRSS );
    // simple log
    app.use(function(req, res, next) {
        console.log('%s %s', req.method, req.url);
        next();
    });
    // mount static
    app.use(express.static(path.join(__dirname, '../dist')));
    app.use(express.static(path.join(__dirname, '../.tmp')));
    // include passport authentication middleware
    // app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use( app.router );
    app.use( express.methodOverride() );
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
    // app.use(express.session({
    //     secret: 'SECRET'
    // }));
    // app.use(passport.initialize());
    // app.use(passport.session());
    //passport local strategy
    // passport.use(new LocalStrategy(function(username, password, done) {
    //     Users.findOne({
    //         username: username
    //     }, function(err, user) {
    //         if (err) {
    //             return done(err);
    //         }
    //         if (!user) {
    //             return done(null, false, {
    //                 message: 'Incorrect username.'
    //             });
    //         }
    //         hash(password, user.salt, function(err, hash) {
    //             if (err) {
    //                 return done(err);
    //             }
    //             if (hash == user.hash) return done(null, user);
    //             done(null, false, {
    //                 message: 'Incorrect password.'
    //             });
    //         });
    //     });
    // }));
    // passport.use(new FacebookStrategy({
    //     clientID: 'YOUR ID',
    //     clientSecret: 'YOUR CODE',
    //     callbackURL: 'http://localhost:3000/auth/facebook/callback'
    // }, function(accessToken, refreshToken, profile, done) {
    //     FbUsers.findOne({
    //         fbId: profile.id
    //     }, function(err, oldUser) {
    //         if (oldUser) {
    //             done(null, oldUser);
    //         } else {
    //             var newUser = new FbUsers({
    //                 fbId: profile.id,
    //                 email: profile.emails[0].value,
    //                 name: profile.displayName
    //             }).save(function(err, newUser) {
    //                 if (err) {
    //                     throw err;
    //                 }
    //                 done(null, newUser);
    //             });
    //         }
    //     });
    // }));
    // // set the user to req.user and establish a session via a cookie set in the user’s browser
    // passport.serializeUser(function(user, done) {
    //     done(null, user.id);
    // });
    // passport.deserializeUser(function(id, done) {
    //     Users.findById(id, function(err, user) {
    //         if (err) {
    //             done(err);
    //         }
    //         done(null, user);
    //     });
    // });

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

    // function userExist(req, res, next) {
    //     Users.count({
    //         username: req.body.username
    //     }, function(err, count) {
    //         if (count === 0) {
    //             next();
    //         } else {
    //             // req.session.error = "User Exist"
    //             res.redirect('/singup');
    //         }
    //     });
    // }
    /**
     **  @SECTION API
     **/
    // app.get('/auth/facebook', passport.authenticate('facebook', {
    //     scope: 'email'
    // }));
    // app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    //     failureRedirect: '/login'
    // }), function(req, res) {
    //     res.render('loggedin', {
    //         user: req.user
    //     });
    // });
    app.get('/', function(req, res) {
        res.sendfile(path.join(__dirname, '../dist/index.html'));
    });
    app.get( '/api', function( request, response ) {
        response.send( 'Library API is running' );
    });
    app.get( '/api/static_collection/', function( request, response ) {
        response.sendfile(path.join(__dirname, '../app/static_feeds.json'));
    });
    app.get('/api/subscriptions', function(req, res) {
        return SubscriptionModel.find(function(err, subscriptions) {
            if (!err) {
                return res.send(subscriptions);
            } else {
                return console.log(err);
            }
        });
    });
    app.get('/api/subscriptions/:id', function(request, response) {
        return SubscriptionModel.findById(request.params.id, function(err, subscriptions) {
            if (!err) {
                return response.send(Subscription);
            } else {
                return console.log('subscription not found for id %s, error: %s', request.params.id, err);
            }
        });
    });
    app.post( '/api/subscriptions', function( request, response ) {

        var Subscription = new SubscriptionModel({
            feedUrl: request.body.feedUrl,
            subscriptionTitle: request.body.subscriptionTitle,
            summary: request.body.summary,
            albumArt: request.body.albumArt,
            explicit: request.body.explicit,
            keywords: null,
            episodes: null
        });
        Subscription.save( function( err ) {
            if( !err ) {
                return console.log( 'created' );
            } else {
                return console.log( err );
            }
        });
        return response.send( Subscription );
    });
    app.get('/api/subscribed', function(req, res) {
        return SubscriptionModel.find(function(err, subscribed) {
            if (!err) {
                return res.send(subscribed);
            } else {
                return console.log(err);
            }
        });
    });
    app.get('/api/subscribed/', function(req, res) {
        //will need to get auth_token and retrieve UserDocumentModel._id
        return UserDocumentModel.findById('5302cf4471349a081e000007', function(err, subscription) {
            if (!err) {
                return res.send(subscription);
            } else {
                return console.log('subscription not found for id %s, error: %s', req.params.id, err);
            }
        });
    });
    //TODO - validate
    app.put('/api/subscribed/:id/episode/:episode/:action/', function(req, res) {
        return SubscriptionModel.findById(req.params.id, req.params.episode, req.params.action, function(err, subscription) {
            if (!err) {
                return res.send(subscription);
            } else {
                return console.log('subscription not found for id %s, error: %s', req.params.id, err);
            }
        });
    });
    app.put('/api/subscribe/:id', function(req) {
        // get subscription from subscriptions collection
        var subscription = function() {
            return SubscriptionModel.findById(req.params.id, function(err, subscription) {
                if (!err) {
                    return subscription;
                } else {
                    return console.log('subscription not found for id %s, error: %s', req.params.id, err);
                }
            });
        };
        var s = new Subscribed(subscription);
        //copy subscription to user subscribed document
        UserDocumentModel.findById(req.authToken, function(err, userDoc) {
            if (!err) {
                userDoc.Subscribed.push(s);
                return console.log('success!');
            } else {
                return console.log('subscription not found for id %s, error: %s', req.params.id, err);
            }
        });
    });
    // TODO implement adding custom subscription
    // start server
    http.createServer(app).listen(app.get('port'), function() {
        console.log('Express App started!');
    });
});

<|endoftext|>


<commit_before>// Prevent console.log from throwing errors
if(typeof(console) === 'undefined') {
    var console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

$('input[type=checkbox]').live('click', function(e) {
  var el = $(this);
  if(el.is(':checked')) {
    el.parent().css('font-weight', 'bold');
  } else {
    el.parent().css('font-weight', 'normal');
  }
  return true;
});

$('.VS-interface').live('focus', function(){
    console.log('hs');
});

// Click handlers for toggling the filter/location/parameter UI
$('li.metrics-dropdown').live("click", function(e){
  e.preventDefault();
  var el = $(this).next();
  // console.log(el.is(':visible'));
  if(el.is(':visible')) {
    el.addClass('hide');
  } else {
    el.removeClass('hide');
  }
});

$('#extramaplayers-button').live("click", function(e){
    e.preventDefault();
    $('#extramodal').modal();
});

Lizard.Utils = {};

Lizard.Utils.Favorites = {
  toggleSelected: function (model){
    uuid = model.url.split("eries/")[1].split("/")[0];
    if (favoriteCollection.where({timeserie: uuid}).length === 0){
            name = model.attributes.name;
            var favorite = favoriteCollection.create({
              data: {
                location: model.attributes.location,
                timeserie: uuid,
                name: name
            }
            });
            // favoriteCollection.add(favorite);
    }
    else {
      favorite = favoriteCollection.where({timeserie: uuid})[0];
      favorite.destroy({wait:true});
    }
  }
};

Lizard.Utils.DragDrop = {
  drag: function (e){
    sendThis = e.target.dataset.url;
    e.dataTransfer.setData("Text", sendThis);
    console.log(e.target);
  },

  allowDrop: function (e){
    e.preventDefault();
  },
  wmsdrop: function (e){
    e.preventDefault();
    var wms_layer= e.dataTransfer.getData("Text");
    var $target = $(e.target);
  },
  drop: function (e){
    e.preventDefault();
    var data_url = e.dataTransfer.getData("Text");
    var $target = $(e.target);
    $target.parent().removeClass("empty");
    // only fire for nearest .graph-drop parent (in case there is already a graph in the element)
    var $graph = $target;
    if (!$graph.hasClass('graph-drop')) {
        $graph = $target.parent('.graph-drop');
    }
    $graph.loadPlotData(data_url);
  },
};

(function (global) {

/**
 * Detect IE version, so we can make some exceptions,
 * due to this browsers crappiness.
 */
var isIE = false;
var ieVersion = 0;
(function () {
    if (navigator.appName == 'Microsoft Internet Explorer') {
        isIE = true;
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) {
            var rv = parseFloat(RegExp.$1);
            ieVersion = rv;
        }
    }
}());

/**
 * Detect Apple appliances.
 */
var isAppleMobile = false;
(function () {
    if (navigator && navigator.userAgent && navigator.userAgent != null) {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches)
            isAppleMobile = true;
    }
}());

/**
 * Things related to time/date formatting.
 */
var timeUnitSize = {
    "second": 1000,
    "minute": 60 * 1000,
    "hour": 60 * 60 * 1000,
    "day": 24 * 60 * 60 * 1000,
    "month": 30 * 24 * 60 * 60 * 1000,
    "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
    "year": 365.2425 * 24 * 60 * 60 * 1000
};
var dayNames = ['zo', 'ma', 'di', 'wo', 'do', 'vr','za'];
var monthNames = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'];
function timeTickFormatter (v, axis, tickIndex, tickLength) {
    var d = $.plot.dateGenerator(v, axis.options);

    // note: first tick is tickIndex 1, but only sometimes (???)
    var isFirstOrLast = tickIndex === 1 || tickIndex === (tickLength - 2);

    var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
    var span = axis.max - axis.min;
    var suffix = (isFirstOrLast) ? " %p" : "";
    var fmt;

    if (t < timeUnitSize.minute) {
        if (isFirstOrLast) {
            fmt = "%H:%M:%S\n%d %b";
        }
        else {
            fmt = "%H:%M:%S";
        }
    }
    else if (t < timeUnitSize.day) {
        if (span < 2 * timeUnitSize.day) {
            if (isFirstOrLast) {
                fmt = "%H:%M\n%d %b";
            }
            else {
                fmt = "%H:%M";
            }
        }
        else {
            fmt = "%H:%M\n%d %b";
        }
    }
    else if (t < timeUnitSize.month) {
        fmt = "%d\n%b";
    }
    else if (t < timeUnitSize.year) {
        if (span < timeUnitSize.year) {
            if (isFirstOrLast) {
                fmt = "%b\n%Y";
            }
            else {
                fmt = "%b";
            }
        }
        else {
            fmt = "%b\n%Y";
        }
    }
    else {
        fmt = "%Y";
    }

    var rt = $.plot.formatDate(d, fmt, monthNames, dayNames);

    return rt;
}

function loadPlotData ($graph, dataUrl, callback, force) {
    // no dataUrl or element, nothing to do
    if (!$graph || !dataUrl) {
        return;
    }

    // check if element is visible
    // flot can't draw on an invisible surface
    if ($graph.is(':hidden')) {
        return;
    }

    // ensure relative positioning, add a class name, force explicit height/width
    $graph.css({
        'position': 'relative',
        'width': '100%',
        'height': '100%'
    });
    $graph.addClass('flot-graph');
    if ($graph.height() === 0) {
        console.error('Height of the graph element seems to be 0');
    }

    // initialize the graph, if it doesn't exist already
    var plot = $graph.data('plot');
    if (!plot) {
        plot = initializePlot($graph);
        $graph.data('plot', plot);
    }

    plot.addDataUrl(dataUrl);
}

function loadPlotDataOld ($graph, dataUrl, callback, force) {
    // no dataUrl or element, nothing to do
    if (!$graph || !dataUrl) {
        return;
    }

    // check if data is already loaded
    var loadedDataUrls = $graph.data('loadedDataUrls');
    if (force !== true && loadedDataUrls) {
        $.each(loadedDataUrls, function (idx, loadedDataUrl) {
            if (loadedDataUrl === dataUrl) {
                // data from this URL is already loaded, do nothing
                return;
            }
        });
    }

    // the wonders of asynchronous programming
    // do nothing if data is still loading
    if ($graph.data('isLoading') === true) {
        return;
    }

    // check if element is visible
    // flot can't draw on an invisible surface
    if ($graph.is(':hidden')) {
        return;
    }

    // ensure relative positioning, add a class name, force explicit height/width
    $graph.css({
        'position': 'relative',
        'width': '100%',
        'height': '100%'
    });
    $graph.addClass('flot-graph');
    if ($graph.height() === 0) {
        console.error('Height of the graph element seems to be 0');
    }

    // initialize the graph, if it doesn't exist already
    var plot = $graph.data('plot');
    if (!plot) {
        plot = initializePlot($graph);
        $graph.data('plot', plot);
    }

    // add a spinner
    var $loading = $('');
    $graph.append($loading);
    $graph.data('isLoading', true);

    // remove spinner when loading has finished (either with or without an error)
    function loadingFinished () {
        $graph.data('isLoading', false);
        $loading.remove();
    }

    // swap out graph for an error icon when we failed to retrieve the data
    function showError () {
        var $broken = $('');
        $broken.click(function (event) {
            $broken.remove();
            loadPlotData($graph, dataUrl, callback, true);
        });
        $graph.append($broken);
    }

    // call callback on success
    function loadingSuccess () {
        // update loadedDataUrls
        var loadedDataUrls = $graph.data('loadedDataUrls');
        if (!loadedDataUrls) {
            loadedDataUrls = [];
        }
        loadedDataUrls.push(dataUrl);
        $graph.data('loadedDataUrls', loadedDataUrls);

        // set attribute and call callback when drawing has finished
        if (typeof callback !== 'undefined') {
            callback();
        }
    }

    // for flot graphs, grab the JSON data and call Flot
    $.get(dataUrl, {}, undefined, 'json')
    .done(function (data, textStatus, jqXHR) {
        loadingFinished();

        // target element might have been hidden in the meantime
        // so check if element is visible again:
        // we can't draw on an invisible surface
        if ($graph.is(':hidden')) {
            return;
        }

        // add the data
        $.each(data, function (idx, line) {
            addPlotLine(plot, line);
        });
        redraw(plot);
        loadingSuccess();
        // try {
        // }
        // catch (Exception) {
            // // we probably recieved some malformed data
            // showError();
        // }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        loadingFinished();
        showError();
    });
}

$.fn.loadPlotData = function (dataUrl, callback, force) {
    if (typeof dataUrl === 'undefined') {
        // get the data url from the element instead
        var dataUrl = $(this).data('data-url');
    }
    loadPlotData($(this), dataUrl, callback, force);
};

function redraw (plot) {
    plot.setupGrid();
    plot.draw();
    plot.triggerRedrawOverlay();
}

function addPlotLine (plot, line, dataUrl) {
    var currentData = plot.getData();
    var newData = $.extend(true, [], currentData);
    var parameter_pk_to_yaxis = {};
    var allocatedYAxes = 0;

    // unset old colors so Flot determines a new color from the default colormap
    $.each(newData, function (idx, line) {
        delete line['color'];
    });

    // determine yaxis per parameter
    var yAxes = plot.getYAxes();
    $.each(yAxes, function (idx, axis) {
        if ('parameter_pk' in axis) {
            parameter_pk_to_yaxis[axis.parameter_pk] = axis.n;
            allocatedYAxes++; // can't properly get the length of an associative array
        }
    });

    // add the new data
    // create a new axis only when we discover a new parameter
    var yaxis = 0;
    if (line.parameter_pk in parameter_pk_to_yaxis) {
        yaxis = parameter_pk_to_yaxis[line.parameter_pk];
    }
    else {
        // allocate a new axis
        yaxis = allocatedYAxes + 1;
        // set the axisLabel and parameter
        yAxes[yaxis].parameter_pk = line.parameter_pk;
        yAxes[yaxis].axisLabel = line.parameter_name;
    }
    line.yaxis = yaxis;
    newData.push(line);

    plot.setData(newData);
}

function initializePlot($container) {
    // define a set of options used for all graphs
    var defaultOpts = {
        series: {
            points: { show: true, hoverable: true, radius: 1 },
            shadowSize: 0,
            lines: { show: true }
        },
        yaxes: [
            // allocate at least 5 axes
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'left',
                reserveSpace: true
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: true
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: false
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: false
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: false
            }
        ],
        xaxes: [
            {
                axisLabel: 'Tijd',
                mode: 'time',
                zoomRange: [1 * timeUnitSize['minute'], 400 * timeUnitSize['year']],
                tickFormatter: timeTickFormatter,
                labelHeight: 28 // always reserve enough vertical space for time label
            }
        ],
        grid: {
            hoverable: true,
            labelMargin: 4,
            margin: 30 /* for the axis labels */,
            borderWidth: 1,
            autoHighlight: false
        },
        legend: {
            show: true
        }
    };

    if (isAppleMobile) {
        $.extend(defaultOpts, {
            // enable touch
            touch: { pan: 'xy', scale: 'x', autoWidth: false, autoHeight: false },
            // disable flot.navigate pan & zoom
            pan: { interactive: false },
            zoom: { interactive: false }
        });
    }
    else {
        $.extend(defaultOpts, {
            // disable touch, so the flot.touch plugin won't mess up the desktop browser
            touch: false,
            // enable pan & zoom
            pan: { interactive: false },
            zoom: { interactive: true },
            tooltip: {
                enabled: true,
                monthNames: monthNames,
                dayNames: dayNames
            },
            zoombuttons: {
                enabled: true
            }
        });
    }

    var finalOpts = $.extend({}, defaultOpts);
    var plot = $.plot($container, [], finalOpts);

    bindPanZoomEvents($container);

    return plot;
}

/**
* Bind several flot graphs together. When navigating through one graph, the other graphs
* should follow the zoom levels, and extent.
*/
function panAndZoomOtherGraphs(plot) {
    var axes = plot.getAxes();
    var xmin = axes.xaxis.min;
    var xmax = axes.xaxis.max;
    $('.flot-graph').each(function () {
        if ($(this).is(':visible')) {
            var otherPlot = $(this).data('plot');
            if (otherPlot && plot !== otherPlot) {
                var otherXAxis = otherPlot.getAxes().xaxis;
                var otherXAxisOptions = otherXAxis.options;
                otherXAxisOptions.min = xmin;
                otherXAxisOptions.max = xmax;
                otherPlot.setupGrid();
                otherPlot.draw();
                otherPlot.getPlaceholder().trigger('axisminmaxchanged', otherXAxis);
            }
        }
    });
}

function bindPanZoomEvents($graph) {
    $graph.bind('plotzoom', function (event, plot) {
        panAndZoomOtherGraphs(plot);
    });

    $graph.bind('plotpan', function (event, plot) {
        panAndZoomOtherGraphs(plot);
    });
}

/**
 * Turn mouse cursor in a spinner on Ajax requests.
 */
$(document).ajaxStart(function () {
    $('html').addClass('busy');
});

$(document).ajaxStop(function () {
    $('html').removeClass('busy');
});

}(this));
<commit_msg>add comments and remove obsolete code<commit_after>// Prevent console.log from throwing errors
if(typeof(console) === 'undefined') {
    var console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

$('input[type=checkbox]').live('click', function(e) {
  var el = $(this);
  if(el.is(':checked')) {
    el.parent().css('font-weight', 'bold');
  } else {
    el.parent().css('font-weight', 'normal');
  }
  return true;
});

$('.VS-interface').live('focus', function(){
    console.log('hs');
});

// Click handlers for toggling the filter/location/parameter UI
$('li.metrics-dropdown').live("click", function(e){
  e.preventDefault();
  var el = $(this).next();
  // console.log(el.is(':visible'));
  if(el.is(':visible')) {
    el.addClass('hide');
  } else {
    el.removeClass('hide');
  }
});

$('#extramaplayers-button').live("click", function(e){
    e.preventDefault();
    $('#extramodal').modal();
});

Lizard.Utils = {};

Lizard.Utils.Favorites = {
  toggleSelected: function (model){
    uuid = model.url.split("eries/")[1].split("/")[0];
    if (favoriteCollection.where({timeserie: uuid}).length === 0){
            name = model.attributes.name;
            var favorite = favoriteCollection.create({
              data: {
                location: model.attributes.location,
                timeserie: uuid,
                name: name
            }
            });
            // favoriteCollection.add(favorite);
    }
    else {
      favorite = favoriteCollection.where({timeserie: uuid})[0];
      favorite.destroy({wait:true});
    }
  }
};

Lizard.Utils.DragDrop = {
  drag: function (e){
    sendThis = e.target.dataset.url;
    e.dataTransfer.setData("Text", sendThis);
    console.log(e.target);
  },

  allowDrop: function (e){
    e.preventDefault();
  },
  wmsdrop: function (e){
    e.preventDefault();
    var wms_layer= e.dataTransfer.getData("Text");
    var $target = $(e.target);
  },
  drop: function (e){
    e.preventDefault();
    var data_url = e.dataTransfer.getData("Text");
    var $target = $(e.target);
    $target.parent().removeClass("empty");
    // only fire for nearest .graph-drop parent (in case there is already a graph in the element)
    var $graph = $target;
    if (!$graph.hasClass('graph-drop')) {
        $graph = $target.parent('.graph-drop');
    }
    $graph.loadPlotData(data_url);
  },
};

/**
 * Code related to initializing jQuery Flot.
 */
(function (global) {

/**
 * Detect IE version, so we can make some exceptions,
 * due to this browsers crappiness.
 */
var isIE = false;
var ieVersion = 0;
(function () {
    if (navigator.appName == 'Microsoft Internet Explorer') {
        isIE = true;
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) {
            var rv = parseFloat(RegExp.$1);
            ieVersion = rv;
        }
    }
}());

/**
 * Detect Apple appliances.
 */
var isAppleMobile = false;
(function () {
    if (navigator && navigator.userAgent && navigator.userAgent != null) {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches)
            isAppleMobile = true;
    }
}());

/**
 * Things related to time/date formatting.
 */
var timeUnitSize = {
    "second": 1000,
    "minute": 60 * 1000,
    "hour": 60 * 60 * 1000,
    "day": 24 * 60 * 60 * 1000,
    "month": 30 * 24 * 60 * 60 * 1000,
    "quarter": 3 * 30 * 24 * 60 * 60 * 1000,
    "year": 365.2425 * 24 * 60 * 60 * 1000
};
var dayNames = ['zo', 'ma', 'di', 'wo', 'do', 'vr','za'];
var monthNames = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'];
function timeTickFormatter (v, axis, tickIndex, tickLength) {
    var d = $.plot.dateGenerator(v, axis.options);

    // note: first tick is tickIndex 1, but only sometimes (???)
    var isFirstOrLast = tickIndex === 1 || tickIndex === (tickLength - 2);

    var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
    var span = axis.max - axis.min;
    var suffix = (isFirstOrLast) ? " %p" : "";
    var fmt;

    if (t < timeUnitSize.minute) {
        if (isFirstOrLast) {
            fmt = "%H:%M:%S\n%d %b";
        }
        else {
            fmt = "%H:%M:%S";
        }
    }
    else if (t < timeUnitSize.day) {
        if (span < 2 * timeUnitSize.day) {
            if (isFirstOrLast) {
                fmt = "%H:%M\n%d %b";
            }
            else {
                fmt = "%H:%M";
            }
        }
        else {
            fmt = "%H:%M\n%d %b";
        }
    }
    else if (t < timeUnitSize.month) {
        fmt = "%d\n%b";
    }
    else if (t < timeUnitSize.year) {
        if (span < timeUnitSize.year) {
            if (isFirstOrLast) {
                fmt = "%b\n%Y";
            }
            else {
                fmt = "%b";
            }
        }
        else {
            fmt = "%b\n%Y";
        }
    }
    else {
        fmt = "%Y";
    }

    var rt = $.plot.formatDate(d, fmt, monthNames, dayNames);

    return rt;
}

/**
 * Initializes a Flot plot on element $graph, and load point data from
 * dataUrl. If $graph already contains a plot, simple adds the data
 * from dataUrl as a second line in the plot.
 */
function loadPlotData ($graph, dataUrl, callback, force) {
    // no dataUrl or element, nothing to do
    if (!$graph || !dataUrl) {
        return;
    }

    // check if element is visible
    // flot can't draw on an invisible surface
    if ($graph.is(':hidden')) {
        return;
    }

    // ensure relative positioning, add a class name, force explicit height/width
    $graph.css({
        'position': 'relative',
        'width': '100%',
        'height': '100%'
    });
    $graph.addClass('flot-graph');
    if ($graph.height() === 0) {
        console.error('Height of the graph element seems to be 0');
    }

    // initialize the graph, if it doesn't exist already
    var plot = $graph.data('plot');
    if (!plot) {
        plot = initializePlot($graph);
        $graph.data('plot', plot);
    }

    plot.addDataUrl(dataUrl);
}

/**
 * Allow graphs to be loaded on any HTML element. This essentially
 * describes the "API" for all your plotting needs.
 */
$.fn.loadPlotData = function (dataUrl, callback, force) {
    if (typeof dataUrl === 'undefined') {
        // get the data url from the element instead
        var dataUrl = $(this).data('data-url');
    }
    loadPlotData($(this), dataUrl, callback, force);
};

/**
 * Initialize an empty jQuery Flot plot on passed element.
 */
function initializePlot($container) {
    // define a set of sane options used for all graphs
    var defaultOpts = {
        series: {
            points: { show: true, hoverable: true, radius: 1 },
            shadowSize: 0,
            lines: { show: true }
        },
        yaxes: [
            // allocate at least five axes, but don't reserve space
            // for the last three
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'left',
                reserveSpace: true
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: true
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: false
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: false
            },
            {
                axisLabel: '',
                zoomRange: [false, false],
                panRange: false,
                position: 'right',
                reserveSpace: false
            }
        ],
        xaxes: [
            {
                axisLabel: 'Tijd',
                mode: 'time',
                zoomRange: [1 * timeUnitSize['minute'], 400 * timeUnitSize['year']],
                tickFormatter: timeTickFormatter,
                labelHeight: 28 // always reserve enough vertical space for the time label
            }
        ],
        grid: {
            hoverable: true,
            labelMargin: 4,
            margin: 30 /* for the axis labels */,
            borderWidth: 1,
            autoHighlight: false
        },
        legend: {
            show: true
        }
    };

    // update the default options based on the users platform
    if (isAppleMobile) {
        $.extend(defaultOpts, {
            // enable touch
            touch: { pan: 'xy', scale: 'x', autoWidth: false, autoHeight: false },
            // disable flot.navigate pan & zoom
            pan: { interactive: false },
            zoom: { interactive: false }
        });
    }
    else {
        $.extend(defaultOpts, {
            // disable touch, so the flot.touch plugin won't mess up the desktop browser
            touch: false,
            // enable pan & zoom
            pan: { interactive: false },
            zoom: { interactive: true },
            // enable a mouse tooltip
            tooltip: {
                enabled: true,
                monthNames: monthNames,
                dayNames: dayNames
            },
            // enable buttons for zoom / pan
            zoombuttons: {
                enabled: true
            }
        });
    }

    // initialize an empty Flot plot
    var finalOpts = $.extend({}, defaultOpts);
    var plot = $.plot($container, [], finalOpts);

    // make sure all plots on the document scroll in synch with this plot
    bindPanZoomEvents($container);

    return plot;
}

/**
* Bind several flot graphs together. When navigating through one graph, the other graphs
* should follow the zoom levels, and extent.
*/
function panAndZoomOtherGraphs(plot) {
    var axes = plot.getAxes();
    var xmin = axes.xaxis.min;
    var xmax = axes.xaxis.max;
    $('.flot-graph').each(function () {
        if ($(this).is(':visible')) {
            var otherPlot = $(this).data('plot');
            if (otherPlot && plot !== otherPlot) {
                var otherXAxis = otherPlot.getAxes().xaxis;
                var otherXAxisOptions = otherXAxis.options;
                otherXAxisOptions.min = xmin;
                otherXAxisOptions.max = xmax;
                otherPlot.setupGrid();
                otherPlot.draw();
                otherPlot.getPlaceholder().trigger('axisminmaxchanged', otherXAxis);
            }
        }
    });
}

function bindPanZoomEvents($graph) {
    $graph.bind('plotzoom', function (event, plot) {
        panAndZoomOtherGraphs(plot);
    });

    $graph.bind('plotpan', function (event, plot) {
        panAndZoomOtherGraphs(plot);
    });
}

/**
 * Turn mouse cursor in a spinner on Ajax requests.
 */
$(document).ajaxStart(function () {
    $('html').addClass('busy');
});

$(document).ajaxStop(function () {
    $('html').removeClass('busy');
});

}(this));
<|endoftext|>


<commit_before>'use strict';

define([
  'backbone',
  'cartodb',
  'views/layer',

  'text!../../queries/transports/metro.pgsql',
  'text!../../queries/transports/buses.pgsql',
  'text!../../queries/transports/trains.pgsql',
  'text!../../queries/transports/airports.pgsql',

  'text!../../queries/climatology/flood-zones.pgsql',
  'text!../../queries/climatology/pluviometry.pgsql',

  'text!../../queries/waste-management/green-points.pgsql',
  'text!../../queries/waste-management/landfills.pgsql',
  'text!../../queries/waste-management/sewage-plants.pgsql',

  'text!../../queries/contamination/nitrogen.pgsql',
  'text!../../queries/contamination/phosphorous.pgsql',
  'text!../../queries/contamination/potasium.pgsql'
], function(Backbone, cartodbLib, LayerView) {

  var queries = {
    metro: arguments[3],
    buses: arguments[4],
    trains: arguments[5],
    airports: arguments[6],
    floodZones: arguments[7],
    pluviometry: arguments[8],
    greenPoints: arguments[9],
    landFills: arguments[10],
    sewagePlants: arguments[11]
  };

  var MapView = Backbone.View.extend({

    el: '#mapView',

    options: {
      tiles: 'https://cartocdn_c.global.ssl.fastly.net/base-dark/{z}/{x}/{y}.png',
      center: [40.384212768155045, -3.6529541015625],
      zoom: 11
    },

    initialize: function() {
      var self = this;

      this.createMap();
      this.setTiles();

      this.metroLayer = new LayerView({el: this.el});
      this.busesLayer = new LayerView();
      this.trainsLayer = new LayerView();
      this.airportsLayer = new LayerView();

      this.greenPointsLayer = new LayerView();
      this.landFillsLayer = new LayerView();
      this.sewagePlantsLayer = new LayerView();

      this.floodZonesLayer = new LayerView();
      this.pluviometryLayer = new LayerView();

      Backbone.Events.on('layer:metro', this.setMetroLayer, this);
      Backbone.Events.on('layer:buses', this.setBusesLayer, this);
      Backbone.Events.on('layer:trains', this.setTrainsLayer, this);
      Backbone.Events.on('layer:airports', this.setAirportsLayer, this);

      Backbone.Events.on('layer:greenpoints', this.setGreenPointsLayer, this);
      Backbone.Events.on('layer:landfills', this.setLandfillsLayer, this);
      Backbone.Events.on('layer:sewageplants', this.setSewagePlantsLayer, this);

      Backbone.Events.on('layer:floodzones', this.setFloodZonesLayer, this);
      Backbone.Events.on('layer:pluviometry', this.setPluviometryLayer, this);

      Backbone.Events.on('location', this.setMarker, this);
    },

    createMap: function() {
      this.map = L.map(this.el).setView(this.options.center, this.options.zoom);
    },

    setTiles: function() {
      this.tiles = L.tileLayer(this.options.tiles).addTo(this.map);
    },

    setMetroLayer: function() {
      if (this.metroLayer.layer) {
        this.metroLayer.removeLayer();
      } else {
        this.metroLayer.setLayer(this.map, {
          sql: queries.metro,
          cartocss: '#metro {marker-fill: #ff0000;}',
          interactivity: 'name'
        });
      }
    },

    setBusesLayer: function() {
      if (this.busesLayer.layer) {
        this.busesLayer.removeLayer();
      } else {
        this.busesLayer.setLayer(this.map, {
          sql: queries.buses,
          cartocss: '#autobuses_urbanos {marker-fill: #ffff00;}',
          interactivity: 'name'
        });
      }
    },

    setTrainsLayer: function() {
      if (this.trainsLayer.layer) {
        this.trainsLayer.removeLayer();
      } else {
        this.trainsLayer.setLayer(this.map, {
          sql: queries.trains,
          cartocss: '#tren_cercanias {marker-fill: #00ff00;}',
          interactivity: 'name'
        });
      }
    },

    setAirportsLayer: function() {
      if (this.airportsLayer.layer) {
        this.airportsLayer.removeLayer();
      } else {
        this.airportsLayer.setLayer(this.map, {
          sql: queries.airports,
          cartocss: '#airports {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setGreenPointsLayer: function() {
      if (this.greenPointsLayer.layer) {
        this.greenPointsLayer.removeLayer();
      } else {
        this.greenPointsLayer.setLayer(this.map, {
          sql: queries.greenPoints,
          cartocss: '#green_points {marker-fill: #00ff00;}',
          interactivity: 'name'
        });
      }
    },

    setLandfillsLayer: function() {
      if (this.landFillsLayer.layer) {
        this.landFillsLayer.removeLayer();
      } else {
        this.landFillsLayer.setLayer(this.map, {
          sql: queries.landFills,
          cartocss: '#landfills {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setSewagePlantsLayer: function() {
      if (this.sewagePlantsLayer.layer) {
        this.sewagePlantsLayer.removeLayer();
      } else {
        this.sewagePlantsLayer.setLayer(this.map, {
          sql: queries.sewagePlants,
          cartocss: '#sewage_plants {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setFloodZonesLayer: function() {
      if (this.floodZonesLayer.layer) {
        this.floodZonesLayer.removeLayer();
      } else {
        this.floodZonesLayer.setLayer(this.map, {
          sql: queries.floodZones,
          cartocss: '#zonas_inundables {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setPluviometryLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.pluviometry,
          cartocss: '#pluviometry {marker-fill: #3333cc;}',
          interactivity: 'name'
        });
      }
    },

    setNitrogenLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.pluviometry,
          cartocss: '#pluviometry {marker-fill: #3333cc; poligon-fill: #330000;}',
          interactivity: 'name'
        });
      }
    },

    setPhosphorousLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.pluviometry,
          cartocss: '#pluviometry {marker-fill: #3333cc;}',
          interactivity: 'name'
        });
      }
    },

    setPotasiumLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.pluviometry,
          cartocss: '#pluviometry {marker-fill: #3333cc;}',
          interactivity: 'name'
        });
      }
    },

    setMarker: function(project) {
      var icon = L.icon({
        iconUrl: 'images/marker.png',
        iconSize: [40, 53]
      });

      var geolatlng = JSON.parse(project.get('latlng')).coordinates;

      var latlng = [geolatlng[1], geolatlng[0]];

      if (this.location) {
        this.map.removeLayer(this.location);
      }

      this.location = L.marker(latlng, {
        icon: icon
      });
      this.location.bindPopup(project.get('name_project'));
      this.location.addTo(this.map);
      this.map.setView(latlng, this.options.zoom);
    }

  });

  return MapView;

});
<commit_msg>queries<commit_after>'use strict';

define([
  'backbone',
  'cartodb',
  'views/layer',

  'text!../../queries/transports/metro.pgsql',
  'text!../../queries/transports/buses.pgsql',
  'text!../../queries/transports/trains.pgsql',
  'text!../../queries/transports/airports.pgsql',

  'text!../../queries/climatology/flood-zones.pgsql',
  'text!../../queries/climatology/pluviometry.pgsql',

  'text!../../queries/waste-management/green-points.pgsql',
  'text!../../queries/waste-management/landfills.pgsql',
  'text!../../queries/waste-management/sewage-plants.pgsql',

  'text!../../queries/contamination/nitrogen.pgsql',
  'text!../../queries/contamination/phosphorous.pgsql',
  'text!../../queries/contamination/potasium.pgsql'
], function(Backbone, cartodbLib, LayerView) {

  var queries = {
    metro: arguments[3],
    buses: arguments[4],
    trains: arguments[5],
    airports: arguments[6],
    floodZones: arguments[7],
    pluviometry: arguments[8],
    greenPoints: arguments[9],
    landFills: arguments[10],
    sewagePlants: arguments[11]
  };

  var MapView = Backbone.View.extend({

    el: '#mapView',

    options: {
      tiles: 'https://cartocdn_c.global.ssl.fastly.net/base-dark/{z}/{x}/{y}.png',
      center: [40.384212768155045, -3.6529541015625],
      zoom: 11
    },

    initialize: function() {
      var self = this;

      this.createMap();
      this.setTiles();

      this.metroLayer = new LayerView({el: this.el});
      this.busesLayer = new LayerView();
      this.trainsLayer = new LayerView();
      this.airportsLayer = new LayerView();

      this.greenPointsLayer = new LayerView();
      this.landFillsLayer = new LayerView();
      this.sewagePlantsLayer = new LayerView();

      this.floodZonesLayer = new LayerView();
      this.pluviometryLayer = new LayerView();

      Backbone.Events.on('layer:metro', this.setMetroLayer, this);
      Backbone.Events.on('layer:buses', this.setBusesLayer, this);
      Backbone.Events.on('layer:trains', this.setTrainsLayer, this);
      Backbone.Events.on('layer:airports', this.setAirportsLayer, this);

      Backbone.Events.on('layer:greenpoints', this.setGreenPointsLayer, this);
      Backbone.Events.on('layer:landfills', this.setLandfillsLayer, this);
      Backbone.Events.on('layer:sewageplants', this.setSewagePlantsLayer, this);

      Backbone.Events.on('layer:floodzones', this.setFloodZonesLayer, this);
      Backbone.Events.on('layer:pluviometry', this.setPluviometryLayer, this);

      Backbone.Events.on('location', this.setMarker, this);
    },

    createMap: function() {
      this.map = L.map(this.el).setView(this.options.center, this.options.zoom);
    },

    setTiles: function() {
      this.tiles = L.tileLayer(this.options.tiles).addTo(this.map);
    },

    setMetroLayer: function() {
      if (this.metroLayer.layer) {
        this.metroLayer.removeLayer();
      } else {
        this.metroLayer.setLayer(this.map, {
          sql: queries.metro,
          cartocss: '#metro {marker-fill: #ff0000;}',
          interactivity: 'name'
        });
      }
    },

    setBusesLayer: function() {
      if (this.busesLayer.layer) {
        this.busesLayer.removeLayer();
      } else {
        this.busesLayer.setLayer(this.map, {
          sql: queries.buses,
          cartocss: '#autobuses_urbanos {marker-fill: #ffff00;}',
          interactivity: 'name'
        });
      }
    },

    setTrainsLayer: function() {
      if (this.trainsLayer.layer) {
        this.trainsLayer.removeLayer();
      } else {
        this.trainsLayer.setLayer(this.map, {
          sql: queries.trains,
          cartocss: '#tren_cercanias {marker-fill: #00ff00;}',
          interactivity: 'name'
        });
      }
    },

    setAirportsLayer: function() {
      if (this.airportsLayer.layer) {
        this.airportsLayer.removeLayer();
      } else {
        this.airportsLayer.setLayer(this.map, {
          sql: queries.airports,
          cartocss: '#airports {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setGreenPointsLayer: function() {
      if (this.greenPointsLayer.layer) {
        this.greenPointsLayer.removeLayer();
      } else {
        this.greenPointsLayer.setLayer(this.map, {
          sql: queries.greenPoints,
          cartocss: '#green_points {marker-fill: #00ff00;}',
          interactivity: 'name'
        });
      }
    },

    setLandfillsLayer: function() {
      if (this.landFillsLayer.layer) {
        this.landFillsLayer.removeLayer();
      } else {
        this.landFillsLayer.setLayer(this.map, {
          sql: queries.landFills,
          cartocss: '#landfills {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setSewagePlantsLayer: function() {
      if (this.sewagePlantsLayer.layer) {
        this.sewagePlantsLayer.removeLayer();
      } else {
        this.sewagePlantsLayer.setLayer(this.map, {
          sql: queries.sewagePlants,
          cartocss: '#sewage_plants {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setFloodZonesLayer: function() {
      if (this.floodZonesLayer.layer) {
        this.floodZonesLayer.removeLayer();
      } else {
        this.floodZonesLayer.setLayer(this.map, {
          sql: queries.floodZones,
          cartocss: '#zonas_inundables {marker-fill: #0000ff;}',
          interactivity: 'name'
        });
      }
    },

    setPluviometryLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.pluviometry,
          cartocss: '#pluviometry {marker-fill: #3333cc;}',
          interactivity: 'name'
        });
      }
    },

    setNitrogenLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.pluviometry,
          cartocss: '#nitrogen_contamination {marker-fill: #3333cc; poligon-fill: #330000;}',
          interactivity: 'name'
        });
      }
    },

    setPhosphorousLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.phosphorous,
          cartocss: '#phosphorus_contamination {marker-fill: #3333cc;}',
          interactivity: 'name'
        });
      }
    },

    setPotasiumLayer: function() {
      if (this.pluviometryLayer.layer) {
        this.pluviometryLayer.removeLayer();
      } else {
        this.pluviometryLayer.setLayer(this.map, {
          sql: queries.potasium,
          cartocss: '#potasium_contamination {marker-fill: #3333cc;}',
          interactivity: 'name'
        });
      }
    },

    setMarker: function(project) {
      var icon = L.icon({
        iconUrl: 'images/marker.png',
        iconSize: [40, 53]
      });

      var geolatlng = JSON.parse(project.get('latlng')).coordinates;

      var latlng = [geolatlng[1], geolatlng[0]];

      if (this.location) {
        this.map.removeLayer(this.location);
      }

      this.location = L.marker(latlng, {
        icon: icon
      });
      this.location.bindPopup(project.get('name_project'));
      this.location.addTo(this.map);
      this.map.setView(latlng, this.options.zoom);
    }

  });

  return MapView;

});
<|endoftext|>


<commit_before>import express from 'express';
import morgan from 'morgan';
import config from 'config';
import compression from 'compression';
import pkg from '../package.json';

/**
 * Express app
 */
const app = express();

/**
 * Locals for the templates
 */
app.locals.version = pkg.version;
app.locals.SHOW_GA = (process.env.NODE_ENV === 'production');

app.set('trust proxy', 1) // trust first proxy for https cookies

/**
 * Log
 */
app.use(morgan('dev'));

/**
 * Compress assets
 */
app.use(compression());

/**
 * Handlebars template engine
 */
require('./views')(app);
require('./routes')(app);

/**
 * 404 route
 */

app.use((req, res, next) => {
  // TODO this should redirect to a 404 page so that window location is changed
  return next({
    code: 404,
    message: 'We can\'t find that page.'
  });
});

/**
 * Error handling
 */

app.use((err, req, res, next) => {

  console.log('Error', err);
  console.log('Error stack', err.stack);

  if (res.headersSent) {
    return next(err);
  }

  res
  .status(err.code || 500)
  .render('pages/error', {
    layout: false,
    message: process.env.NODE_ENV === 'production' ? 'We couldn\'t find that page :(' : `Error ${err.code}: ${err.message}`,
    stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
    options: {
      showGA: config.GoogleAnalytics.active
    }
  });
});

/**
 * Port config
 */

app.set('port', process.env.WEBSITE_PORT || 3000);

/**
 * Start server
 */
console.log(`Starting OpenCollective Website Server on port ${app.get('port')} in ${app.get('env')} environment.`);
app
  .listen(app.get('port'))
  .on('error', (err) => {
    if (err.errno === 'EADDRINUSE')
      console.error('Error: Port busy');
    else
      console.log(err);
  });

module.exports = app;
<commit_msg>prefer WEBSITE_PORT over PORT but still support it<commit_after>import express from 'express';
import morgan from 'morgan';
import config from 'config';
import compression from 'compression';
import pkg from '../package.json';

/**
 * Express app
 */
const app = express();

/**
 * Locals for the templates
 */
app.locals.version = pkg.version;
app.locals.SHOW_GA = (process.env.NODE_ENV === 'production');

app.set('trust proxy', 1) // trust first proxy for https cookies

/**
 * Log
 */
app.use(morgan('dev'));

/**
 * Compress assets
 */
app.use(compression());

/**
 * Handlebars template engine
 */
require('./views')(app);
require('./routes')(app);

/**
 * 404 route
 */

app.use((req, res, next) => {
  // TODO this should redirect to a 404 page so that window location is changed
  return next({
    code: 404,
    message: 'We can\'t find that page.'
  });
});

/**
 * Error handling
 */

app.use((err, req, res, next) => {

  console.log('Error', err);
  console.log('Error stack', err.stack);

  if (res.headersSent) {
    return next(err);
  }

  res
  .status(err.code || 500)
  .render('pages/error', {
    layout: false,
    message: process.env.NODE_ENV === 'production' ? 'We couldn\'t find that page :(' : `Error ${err.code}: ${err.message}`,
    stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
    options: {
      showGA: config.GoogleAnalytics.active
    }
  });
});

/**
 * Port config
 */

app.set('port', process.env.WEBSITE_PORT || process.env.PORT || 3000);

/**
 * Start server
 */
console.log(`Starting OpenCollective Website Server on port ${app.get('port')} in ${app.get('env')} environment.`);
app
  .listen(app.get('port'))
  .on('error', (err) => {
    if (err.errno === 'EADDRINUSE')
      console.error('Error: Port busy');
    else
      console.log(err);
  });

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.likeSvc', []).service("likeSvc", ['$q', '$http', function($q, $http) {
  return {
    like: function({ user, sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'POST',
        url: `${beURL}/likes`,
        data: { sketch_id: sketch._id, liker_id: user.user_id }
      }).then(({ data }) => {
        deferred.resolve(data[0]);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    },
    dislike: function({ user, sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'DELETE',
        url: `${beURL}/likes`,
        data: { liker_id: user.user_id, sketch_id: sketch._id }
      }).then(({ data }) => {
        deferred.resolve(data[0]);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    },
    find: function({ user, sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'GET',
        url: `${beURL}/likes`,
        params: { liker_id: user.user_id, sketch_id: sketch._id }
      }).then(({ data }) => {
        deferred.resolve(data.data[0]);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    },
    sketchTotal: function({ sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'GET',
        url: `${beURL}/likes`,
        params: { sketch_id: sketch._id }
      }).then(({ data }) => {
        deferred.resolve(data.total);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    }
  };
}]);
<commit_msg>Add limit param<commit_after>'use strict';

angular.module('myApp.likeSvc', []).service("likeSvc", ['$q', '$http', function($q, $http) {
  return {
    like: function({ user, sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'POST',
        url: `${beURL}/likes`,
        data: { sketch_id: sketch._id, liker_id: user.user_id }
      }).then(({ data }) => {
        deferred.resolve(data[0]);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    },
    dislike: function({ user, sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'DELETE',
        url: `${beURL}/likes`,
        data: { liker_id: user.user_id, sketch_id: sketch._id }
      }).then(({ data }) => {
        deferred.resolve(data[0]);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    },
    find: function({ user, sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'GET',
        url: `${beURL}/likes`,
        params: { liker_id: user.user_id, sketch_id: sketch._id }
      }).then(({ data }) => {
        deferred.resolve(data.data[0]);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    },
    sketchTotal: function({ sketch }) {
      let deferred  = $q.defer();

      $http({
        method: 'GET',
        url: `${beURL}/likes`,
        params: { sketch_id: sketch._id, $limit: 0 }
      }).then(({ data }) => {
        deferred.resolve(data.total);
      }, (e) => {
        deferred.reject(e);
      });

      return deferred.promise;
    }
  };
}]);
<|endoftext|>