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

var express = require('express');
var MongoStore = require('connect-mongo')(express);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');
var _ = require('underscore');
var notifyService = require('./controllers/util/notificationService');
var OpenShiftApp = require('./openshift');

/**
 * Load controllers.
 */

var sitemap = require('./controllers/sitemap');
sitemap.scheduleSitemapRebuild(1000 * 60 * 60 * 24); // 1 day
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');
var createEventPage = require('./controllers/event/create-page');
var saveEvent = require('./controllers/event/save-event');
var viewEvent = require('./controllers/event/view');
var editEvent = require('./controllers/event/edit');
var cancelEvent = require('./controllers/event/cancel');
var upload = require('./controllers/upload').handleUpload;
var myEvents = require('./controllers/profile/my-events');
var rmEventImage = require('./controllers/event/rm-image');

var eventStore = require('./controllers/event/EventStore');

var renderTpl = require('./controllers/render-tpl').renderTpl;

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

var app = express();

app.set('ipaddress', '127.0.0.1'); // TODO refactor to use appConfig instead of plain strings
app.set('port', 3000);
app.set('mongodb-url', secrets.db);

secrets.db = app.get('mongodb-url');

var openShiftApp = new OpenShiftApp();
openShiftApp.initialize(app);

app.response.renderNotFound = function() {
  this.render('404', { status: 404 });
};

/**
 * Express configuration.
 */

var hour = 3600000;
var day = (hour * 24);
var month = (day * 30);

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(connectAssets({
  paths: ['public/css', 'public/js'],
  helperContext: app.locals,
  build: false
}));
app.use(express.compress());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.methodOverride());
app.use(express.session({
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: secrets.db,
    auto_reconnect: true
  })
}));
app.use(express.csrf());
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
  res.locals.user = req.user;
  res.locals._csrf = req.csrfToken();
  res.locals.secrets = secrets;
  res.cookie('XSRF-TOKEN', req.csrfToken());
  next();
});
app.use(flash());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: month }));
app.use(function(req, res, next) {
  // Keep track of previous URL
  if (req.method !== 'GET') return next();
  var path = req.path.split('/')[1];
  if (/(auth|login|logout|signup)$/i.test(path)) return next();
  var returnTo = req.path.indexOf('/assets') === 0 || req.path.indexOf('/favicon.ico') === 0 ? '/' : req.path; // ignore assets requests
  req.session.returnTo = returnTo;
  next();
});
app.use(app.router);
app.use(function(req, res) {
  res.renderNotFound();
});
app.use(express.errorHandler());

/**
 * Application routes.
 */

// nocache middleware, Use when you don't want browser to cache the request (e.g. on back button click)
function nocache(req, res, next) {
  res.set('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.set('Expires', '-1');
  res.set('Pragma', 'no-cache');
  next();
}

app.get('/', homeController.index);
app.get('/sitemap.xml', sitemap.getSitemap);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);
app.get('/api', apiController.getApi);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/steam', apiController.getSteam);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);

var feedback = require('./controllers/feedback');
app.get('/tpl/*', renderTpl);
app.get('/feedback', feedback.get_feedback);
app.get('/event/create', passportConf.isAuthenticated, createEventPage);
app.post('/event/save', passportConf.isAuthenticated, saveEvent);
app.get('/event/:id', viewEvent);
app.get('/event/:id/edit', passportConf.isAuthenticated, editEvent);
app.get('/event/:id/cancel', passportConf.isAuthenticated, cancelEvent);
app.post('/event/:id/rm-image/:imageId', passportConf.isAuthenticated, rmEventImage);
app.post('/upload/image', passportConf.isAuthenticated, upload);
app.get('/profile/my-events', passportConf.isAuthenticated, myEvents);

// MeetUA API
var meetuaEventsApi = require('./controllers/api/events');
app.get('/api/meetua/events/find', meetuaEventsApi.get_find);
app.get('/api/meetua/events/findById', meetuaEventsApi.get_findById);
app.get('/api/meetua/events/my', passportConf.isAuthenticated, meetuaEventsApi.get_my);
app.get('/api/meetua/events/myOverview', nocache);
app.get('/api/meetua/events/myOverview', passportConf.isAuthenticated, meetuaEventsApi.get_myOverview);
app.post('/api/meetua/events/participation', passportConf.isAuthenticated, meetuaEventsApi.post_participation);

/**
 * OAuth routes for sign-in.
 */

app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/vkontakte', passport.authenticate('vkontakte', { scope: ['email'] }));
app.get('/auth/vkontakte/callback', passport.authenticate('vkontakte', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * OAuth routes for API examples that require authorization.
 */

app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});

/**
 * Start Express server.
 */

app.listen(app.get('port'), app.get('ipaddress'), function() {
  console.log("✔ Express server listening on %s:%d in %s mode", app.get('ipaddress'), app.get('port'), app.get('env'));
});

/**
 * Mongoose configuration.
 */

mongoose.connect(app.get('mongodb-url'));
mongoose.connection.on('error', function() {
  console.error('✗ MongoDB Connection Error. Please make sure MongoDB is running.');
});

if (!openShiftApp.isOpenShiftEnv) {
  // DB preloading
  eventStore.dbPreload();
  userController.dbPreload();
}

notifyService.startCronJobs();

module.exports = app;
<commit_msg>Build assets on OpenShift.<commit_after>/**
 * Module dependencies.
 */

var express = require('express');
var MongoStore = require('connect-mongo')(express);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');
var _ = require('underscore');
var notifyService = require('./controllers/util/notificationService');
var OpenShiftApp = require('./openshift');

/**
 * Load controllers.
 */

var sitemap = require('./controllers/sitemap');
sitemap.scheduleSitemapRebuild(1000 * 60 * 60 * 24); // 1 day
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');
var createEventPage = require('./controllers/event/create-page');
var saveEvent = require('./controllers/event/save-event');
var viewEvent = require('./controllers/event/view');
var editEvent = require('./controllers/event/edit');
var cancelEvent = require('./controllers/event/cancel');
var upload = require('./controllers/upload').handleUpload;
var myEvents = require('./controllers/profile/my-events');
var rmEventImage = require('./controllers/event/rm-image');

var eventStore = require('./controllers/event/EventStore');

var renderTpl = require('./controllers/render-tpl').renderTpl;

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

var app = express();

app.set('ipaddress', '127.0.0.1'); // TODO refactor to use appConfig instead of plain strings
app.set('port', 3000);
app.set('mongodb-url', secrets.db);

secrets.db = app.get('mongodb-url');

var openShiftApp = new OpenShiftApp();
openShiftApp.initialize(app);

app.response.renderNotFound = function() {
  this.render('404', { status: 404 });
};

/**
 * Express configuration.
 */

var hour = 3600000;
var day = (hour * 24);
var month = (day * 30);

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(connectAssets({
  paths: ['public/css', 'public/js'],
  helperContext: app.locals,
  build: openShiftApp.isOpenShiftEnv() ? true : false
}));
app.use(express.compress());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.methodOverride());
app.use(express.session({
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: secrets.db,
    auto_reconnect: true
  })
}));
app.use(express.csrf());
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
  res.locals.user = req.user;
  res.locals._csrf = req.csrfToken();
  res.locals.secrets = secrets;
  res.cookie('XSRF-TOKEN', req.csrfToken());
  next();
});
app.use(flash());
app.use(express.static(path.join(__dirname, 'public'), { maxAge: month }));
app.use(function(req, res, next) {
  // Keep track of previous URL
  if (req.method !== 'GET') return next();
  var path = req.path.split('/')[1];
  if (/(auth|login|logout|signup)$/i.test(path)) return next();
  var returnTo = req.path.indexOf('/assets') === 0 || req.path.indexOf('/favicon.ico') === 0 ? '/' : req.path; // ignore assets requests
  req.session.returnTo = returnTo;
  next();
});
app.use(app.router);
app.use(function(req, res) {
  res.renderNotFound();
});
app.use(express.errorHandler());

/**
 * Application routes.
 */

// nocache middleware, Use when you don't want browser to cache the request (e.g. on back button click)
function nocache(req, res, next) {
  res.set('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.set('Expires', '-1');
  res.set('Pragma', 'no-cache');
  next();
}

app.get('/', homeController.index);
app.get('/sitemap.xml', sitemap.getSitemap);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);
app.get('/api', apiController.getApi);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/steam', apiController.getSteam);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/twilio', apiController.getTwilio);
app.post('/api/twilio', apiController.postTwilio);
app.get('/api/clockwork', apiController.getClockwork);
app.post('/api/clockwork', apiController.postClockwork);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.get('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getVenmo);
app.post('/api/venmo', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.postVenmo);
app.get('/api/linkedin', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getLinkedin);

var feedback = require('./controllers/feedback');
app.get('/tpl/*', renderTpl);
app.get('/feedback', feedback.get_feedback);
app.get('/event/create', passportConf.isAuthenticated, createEventPage);
app.post('/event/save', passportConf.isAuthenticated, saveEvent);
app.get('/event/:id', viewEvent);
app.get('/event/:id/edit', passportConf.isAuthenticated, editEvent);
app.get('/event/:id/cancel', passportConf.isAuthenticated, cancelEvent);
app.post('/event/:id/rm-image/:imageId', passportConf.isAuthenticated, rmEventImage);
app.post('/upload/image', passportConf.isAuthenticated, upload);
app.get('/profile/my-events', passportConf.isAuthenticated, myEvents);

// MeetUA API
var meetuaEventsApi = require('./controllers/api/events');
app.get('/api/meetua/events/find', meetuaEventsApi.get_find);
app.get('/api/meetua/events/findById', meetuaEventsApi.get_findById);
app.get('/api/meetua/events/my', passportConf.isAuthenticated, meetuaEventsApi.get_my);
app.get('/api/meetua/events/myOverview', nocache);
app.get('/api/meetua/events/myOverview', passportConf.isAuthenticated, meetuaEventsApi.get_myOverview);
app.post('/api/meetua/events/participation', passportConf.isAuthenticated, meetuaEventsApi.post_participation);

/**
 * OAuth routes for sign-in.
 */

app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/vkontakte', passport.authenticate('vkontakte', { scope: ['email'] }));
app.get('/auth/vkontakte/callback', passport.authenticate('vkontakte', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' }));
app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) {
  res.redirect(req.session.returnTo || '/');
});

/**
 * OAuth routes for API examples that require authorization.
 */

app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});
app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/venmo');
});

/**
 * Start Express server.
 */

app.listen(app.get('port'), app.get('ipaddress'), function() {
  console.log("✔ Express server listening on %s:%d in %s mode", app.get('ipaddress'), app.get('port'), app.get('env'));
});

/**
 * Mongoose configuration.
 */

mongoose.connect(app.get('mongodb-url'));
mongoose.connection.on('error', function() {
  console.error('✗ MongoDB Connection Error. Please make sure MongoDB is running.');
});

if (!openShiftApp.isOpenShiftEnv()) {
  // DB preloading
  eventStore.dbPreload();
  userController.dbPreload();
}

notifyService.startCronJobs();

module.exports = app;
<|endoftext|>


<commit_before>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var SelectComponent = (function () {
    function SelectComponent() {
        this.items = [
            {
                label: 'item 1',
                value: 1
            },
            {
                label: 'item 2',
                value: 2
            },
            {
                label: 'item 3',
                value: 3
            },
            {
                label: 'item 4',
                value: 4
            },
            {
                label: 'item 5',
                value: 5
            },
            {
                label: 'item 6', sublabel: 'sublabel of item 6',
                value: 6
            }
        ];
        this.selectSingleValue = 5;
        this.selectMultiValue = [3, 4];
        this.selectSingleValueHtml = 5;
    }
    SelectComponent.prototype.ngOnInit = function () { };
    SelectComponent.prototype.onChange = function (newValue) {
        console.log('onChange:');
        console.dir(newValue);
    };
    return SelectComponent;
}());
SelectComponent = __decorate([
    core_1.Component({
        templateUrl: 'select.component.html'
    }),
    __metadata("design:paramtypes", [])
], SelectComponent);
exports.SelectComponent = SelectComponent;
<commit_msg>REMOVE dist-file mergeconflict<commit_after><|endoftext|>


<commit_before>var async = require('async');
var express = require('express');
var swig  = require('swig');
var config = require('./config');
var gcal = require('google-calendar');
var moment = require('moment-timezone');
var bodyParser = require('body-parser');

var app = express();
var passport = require('passport');
var GoogleStategy = require('passport-google-oauth').OAuth2Strategy;

var port = Number(process.env.PORT || 3000);
app.use(bodyParser());

app.configure(function() {
	app.use(express.cookieParser());
	app.use(express.bodyParser());
	app.use(express.session({secret: 'SECRET HERE'}));
	app.use(passport.initialize());
})

// that and use Express's caching instead, if you like:
app.set('view cache', false);
// To disable Swig's cache, do the following:
swig.setDefaults({ cache: false });

var GMT = "Europe/London";

var rooms = {  // TODO: autopopulate?
    'boardroom': {
        id: 'boardroom',
        name: 'The Boardroom',
        location: '300 SJS',
        cal_id: 'tintofs.com_43522d4e59432d31342d31322d4252@resource.calendar.google.com'
    },
    'study': {
        id: 'study',
        name: 'The Study',
        location: '300 SJS',
        cal_id: 'tintofs.com_2d3838353536353633313930@resource.calendar.google.com'
    },
    'drawingroom': {
        id: 'drawingroom',
        name: 'The Drawing Room',
        location: '300 SJS',
        cal_id: 'tintofs.com_2d3938353839353535393236@resource.calendar.google.com'
    },
};

function render_template(template_path, context) {
    return swig.compileFile(template_path)(context);
}

function Event(data) {

    this.title = data.summary;
    this.confirmed = data.confirmed;
    this.start = moment.utc(data.start.dateTime).tz(GMT);
    this.end = moment.utc(data.end.dateTime).tz(GMT);
    this.minutes = this.end.diff(this.start, 'minutes');
    this.attendees = [];
    this.status = 'busy';

    for (var i=0; i<data.attendees.length; i++) {
        attendee =  data.attendees[i]
        if (attendee.resource !== true) {
            if (attendee.organizer == true) {
                this.owner = attendee.displayName;
            } else {
                this.attendees.push(attendee.displayName);
            }
        }
    }
}

Event.prototype.is_active = function() {
    var now = moment.utc();
    return this.start.isBefore(now) && this.end.isAfter(now);
}

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

app.get('/', function(req, res){
    var template = swig.compileFile('templates/index.html');
    var output = template({
        project_name: 'Rendezvous',
    });
    res.send(output);
});

// views for generating the detail view
app.get('/room/', function(req, res) {
    // Returns a list of configured meeting rooms to select which room the
    // client is representing
    res.send(render_template('templates/rooms_list.html', {rooms: rooms}));
})

app.post('/room/:id', function(req, res) {
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    var meetingLength = req.body.meetingLength;
    console.log('Meeting Length:' + meetingLength);

	//Create an instance from accessToken
	var accessToken     = req.session.access_token;

    var room            = rooms[req.params.id];
	var calendarId      = room.cal_id;

    var event = {
        'summary': 'Test03',
        'start': {
            'dateTime': moment().toISOString()
        },
        'end': {
            'dateTime': moment().add(meetingLength, 'minutes')
        },
        'attendees': [
            {
                'email': calendarId // the user from the URL
            },
            {
                'email': req.session.gmail_address  // the logged in user
            }
        ]
    };

	gcal(accessToken).events.insert(calendarId, event, function(err, result) {
        console.log(err);
        console.log(result);
        return res.send('done');
        return res.redirect('/room/' + req.params.id + '/');
    });

})

function schedule_for_room(data) {
    var current_event;
    var next_event;
    var schedule = [];

    var now = moment.utc();

    for (var i=0; i<data.items.length; i++) {
        var ev;
        try {
            ev = new Event(data.items[i]);
        } catch (e) {
            // malformed data
        }

        if (ev.confirmed !== true) {
            schedule.push(ev);

            if (ev.start.isBefore(now) && ev.end.isAfter(now)) {
                current_event = ev;
            }
            else if (!next_event && ev.start.isAfter(now)) {
                next_event = ev;
            }
        }
    }

    return {
        current_event: current_event,
        next_event: next_event,
        schedule: schedule
    }
}

function calculate_schedule(schedule, anchor) {
    var new_schedule = [];
    if (!schedule) return new_schedule;

    for (var i=0; i<schedule.length; i++) {
        var ev = schedule[i];
        ev.from_start = ev.start.diff(anchor, 'minutes');
        new_schedule.push(ev)
    }

    return new_schedule;
}

app.get('/room/:name/', function(req, res) {
    // gets the detail for the specified room
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.name];

    gcal(accessToken).events.list(room.cal_id, {
        maxResults: 100,
        timeMin: moment(1, 'days').subtract().toISOString()
    }, function(err, data) {
        if(err) return res.send(500,err);

        var now = moment.utc().tz(GMT);
        var room_data = schedule_for_room(data);
        var start_time = moment(now).minutes(0).seconds(0).millisecond(0).subtract(1, 'hours');

        var offset = moment.duration(15 - (now.minutes() % 15), 'minutes');
        var adhoc_defaults = [15, 30, 60];
        var adhoc_times = [];

        for (var i=0;i<adhoc_defaults.length;i++) {
            var len = adhoc_defaults[i];
            var meeting_finish = moment(now).add(offset, 'minutes')
                                            .add(moment.duration(len, 'minutes'))
                                            .seconds(0).millisecond(0);

            if (!room_data.next_event ||
                meeting_finish.isBefore(room_data.next_event.start) ||
                meeting_finish.isSame(room_data.next_event.start))
            {
                adhoc_times.push(meeting_finish);
            }
        }

        return res.send(render_template('templates/busyroom.html', {
            room: room,
            start_time: start_time,
            current_event: room_data.current_event,
            next_event: room_data.next_event,
            schedule: calculate_schedule(room_data.schedule, start_time),
            adhoc_times: adhoc_times
        }));
    });
});

app.get('/room/:name/book/:end', function(req, res) {
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var calendarId      = rooms[req.params.name].cal_id;
    var now             = moment.utc().tz(GMT).seconds(0).millisecond(0).toISOString();
    var end             = req.params.end

    var event = {
        'summary': 'Ad-hoc meeting',
        'start'  : {'dateTime': now},
        'end'    : {'dateTime': end},
        'attendees': [
            {
                'email': calendarId // the user from the URL
            },
            {
                'email': req.session.gmail_address  // the logged in user
            }
        ]
    };

    gcal(accessToken).events.insert(calendarId, event, function(err, result) {
        return res.redirect('/room/' + req.params.name + '/');
    });
});

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

    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.name];
    var free_rooms      = [];

    async.map(
        Object.keys(rooms),
        function(item, callback) {
            var room = rooms[item];

            gcal(accessToken).events.list(room.cal_id, {maxResults: 50}, function(err, data) {
                if(err) return res.send(500,err);

                var room_data = schedule_for_room(data);
                var obj = {
                    'name': room.name,
                    'location': room.location
                };
                if (room_data.next_event) {
                    // if tomorrow?
                    obj['available_until'] = room_data.next_event.start.format('HH:mm');
                }
                if (!room_data.current_event) {
                    callback(null, obj);
                } else {
                    callback(null, null)
                }

            });
        },
        function(err, results) {
            var free_rooms = [];

            for (var i=0;i<results.length;i++) {
                var result = results[i];
                if (result !== null) {
                    free_rooms.push(result);
                }
            }
            return res.send(free_rooms);
        }
    )
});

function get_next_meeting_label(accessToken, cal_id, callback) {
    gcal(accessToken).events.list(cal_id, {
        maxResults: 10,
        timeMin: new Date().toISOString()
    }, function(err, data) {
        var label = 'Nothing!';
        if (data.items.length > 0) {
            label = data.items[0]['summary']
        }
        callback(label);
    });
}

app.get('/room/:id/in-use', function(req, res) {
    // gets the detail for the specified room
    console.log('Original URL' + req.originalUrl)
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.id];

    gcal(accessToken).events.list(room.cal_id, {maxResults: 50}, function(err, data) {
        if(err) return res.send(500,err);

        var current_event;
        var schedule = [];

        for (var i=0; i<data.items.length; i++) {
            var ev;
            try {
                ev = new Event(data.items[i]);
            } catch (e) {
                // malformed data
                console.log(e);
            }

            if (ev.confirmed !== true) {
                schedule.push(ev);

                if (ev.is_active()) {
                    current_event = ev;
                }
            }
        }

        get_next_meeting_label(accessToken, room.cal_id, function(next_label) {
            return res.send(render_template('templates/in-progress.html', {
                now: moment().format('dddd, Do MMM YYYY, hh:mm a'),
                room: room,
                room_name: data.summary,
                current_event: current_event,
                schedule: schedule,
                room_in_use: current_event !== undefined,
                next_meeting_label: next_label
            }));
        })
    });
});

app.post('/room/:id/in-use', function(req, res) {
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.id];

    gcal(accessToken).events.list(room.cal_id, {maxResults: 50}, function(err, data) {
        if(err) return res.send(500,err);

        var current_event;
        var g_event;
        var schedule = [];

        for (var i=0; i<data.items.length; i++) {
            var ev;
            try {
                g_event = data.items[i];
                ev = new Event(data.items[i]);
            } catch (e) {
                // malformed data
                console.log(e);
            }

            if (ev.confirmed !== true) {
                schedule.push(ev);

                if (ev.is_active()) {
                    current_event = ev;
                    break;
                }
            }
        }

        if (current_event === undefined) {
            throw new Error();
        }

        var event_id = g_event['id'];
        g_event['end']['dateTime'] = moment().toISOString();

        gcal(accessToken).events.update(room.cal_id, event_id, g_event, function(err, result) {

            get_next_meeting_label(accessToken, room.cal_id, function(next_label) {

                return res.send({
                    next_meeting_label: next_label
                });
            })
        });
    });
});

passport.use(new GoogleStategy({
	clientID: config.consumer_key,
	clientSecret: config.consumer_secret,
	callbackURL: (process.env.URL || ("http://lvh.me:" + port)) + "/auth/callback",
	scope: ['openid', 'email', 'https://www.googleapis.com/auth/calendar']
},
function (accessToken, refreshToken, profile, done) {
	profile.accessToken = accessToken;
	return done(null, profile);
}))

app.get('/auth',
	passport.authenticate('google', {session:false}));

app.get('/auth/callback',
  passport.authenticate('google', { session: false, failureRedirect: '/login' }),
  function(req, res) {
    req.session.access_token = req.user.accessToken;
    req.session.gmail_address = req.user.emails[0]['value']
    console.log('Session last URL ' + req.session.lastUrl)
    res.redirect(req.session.lastUrl || '/');
  });

app.get('/auth/success', function(request, response) {
  response.redirect(request.session.lastUrl || '/');
});

require('./cal_api')(app, gcal);

app.listen(port);
<commit_msg>Fix more<commit_after>var async = require('async');
var express = require('express');
var swig  = require('swig');
var config = require('./config');
var gcal = require('google-calendar');
var moment = require('moment-timezone');
var bodyParser = require('body-parser');

var app = express();
var passport = require('passport');
var GoogleStategy = require('passport-google-oauth').OAuth2Strategy;

var port = Number(process.env.PORT || 3000);
app.use(bodyParser());

app.configure(function() {
	app.use(express.cookieParser());
	app.use(express.bodyParser());
	app.use(express.session({secret: 'SECRET HERE'}));
	app.use(passport.initialize());
})

// that and use Express's caching instead, if you like:
app.set('view cache', false);
// To disable Swig's cache, do the following:
swig.setDefaults({ cache: false });

var GMT = "Europe/London";

var rooms = {  // TODO: autopopulate?
    'boardroom': {
        id: 'boardroom',
        name: 'The Boardroom',
        location: '300 SJS',
        cal_id: 'tintofs.com_43522d4e59432d31342d31322d4252@resource.calendar.google.com'
    },
    'study': {
        id: 'study',
        name: 'The Study',
        location: '300 SJS',
        cal_id: 'tintofs.com_2d3838353536353633313930@resource.calendar.google.com'
    },
    'drawingroom': {
        id: 'drawingroom',
        name: 'The Drawing Room',
        location: '300 SJS',
        cal_id: 'tintofs.com_2d3938353839353535393236@resource.calendar.google.com'
    },
};

function render_template(template_path, context) {
    return swig.compileFile(template_path)(context);
}

function Event(data) {

    this.title = data.summary;
    this.confirmed = data.confirmed;
    this.start = moment.utc(data.start.dateTime).tz(GMT);
    this.end = moment.utc(data.end.dateTime).tz(GMT);
    this.minutes = this.end.diff(this.start, 'minutes');
    this.attendees = [];
    this.status = 'busy';

    for (var i=0; i<data.attendees.length; i++) {
        attendee =  data.attendees[i]
        if (attendee.resource !== true) {
            if (attendee.organizer == true) {
                this.owner = attendee.displayName;
            } else {
                this.attendees.push(attendee.displayName);
            }
        }
    }
}

Event.prototype.is_active = function() {
    var now = moment.utc();
    return this.start.isBefore(now) && this.end.isAfter(now);
}

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

app.get('/', function(req, res){
    var template = swig.compileFile('templates/index.html');
    var output = template({
        project_name: 'Rendezvous',
    });
    res.send(output);
});

// views for generating the detail view
app.get('/room/', function(req, res) {
    // Returns a list of configured meeting rooms to select which room the
    // client is representing
    res.send(render_template('templates/rooms_list.html', {rooms: rooms}));
})

app.post('/room/:id', function(req, res) {
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    var meetingLength = req.body.meetingLength;
    console.log('Meeting Length:' + meetingLength);

	//Create an instance from accessToken
	var accessToken     = req.session.access_token;

    var room            = rooms[req.params.id];
	var calendarId      = room.cal_id;

    var event = {
        'summary': 'Test03',
        'start': {
            'dateTime': moment().toISOString()
        },
        'end': {
            'dateTime': moment().add(meetingLength, 'minutes')
        },
        'attendees': [
            {
                'email': calendarId // the user from the URL
            },
            {
                'email': req.session.gmail_address  // the logged in user
            }
        ]
    };

	gcal(accessToken).events.insert(calendarId, event, function(err, result) {
        console.log(err);
        console.log(result);
        return res.send('done');
        return res.redirect('/room/' + req.params.id + '/');
    });

})

function schedule_for_room(data) {
    var current_event;
    var next_event;
    var schedule = [];

    var now = moment.utc();

    for (var i=0; i<data.items.length; i++) {
        var ev;
        try {
            ev = new Event(data.items[i]);
        } catch (e) {
            // malformed data
        }

        if (ev.confirmed !== true) {
            schedule.push(ev);

            if (ev.start.isBefore(now) && ev.end.isAfter(now)) {
                current_event = ev;
            }
            else if (!next_event && ev.start.isAfter(now)) {
                next_event = ev;
            }
        }
    }

    return {
        current_event: current_event,
        next_event: next_event,
        schedule: schedule
    }
}

function calculate_schedule(schedule, anchor) {
    var new_schedule = [];
    if (!schedule) return new_schedule;

    for (var i=0; i<schedule.length; i++) {
        var ev = schedule[i];
        ev.from_start = ev.start.diff(anchor, 'minutes');
        new_schedule.push(ev)
    }

    return new_schedule;
}

app.get('/room/:name/', function(req, res) {
    // gets the detail for the specified room
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.name];

    gcal(accessToken).events.list(room.cal_id, {
        maxResults: 100,
        timeMin: moment(1, 'days').subtract().toISOString()
    }, function(err, data) {
        if(err) return res.send(500,err);

        var now = moment.utc().tz(GMT);
        var room_data = schedule_for_room(data);
        var start_time = moment(now).minutes(0).seconds(0).millisecond(0).subtract(1, 'hours');

        var offset = moment.duration(15 - (now.minutes() % 15), 'minutes');
        var adhoc_defaults = [15, 30, 60];
        var adhoc_times = [];

        for (var i=0;i<adhoc_defaults.length;i++) {
            var len = adhoc_defaults[i];
            var meeting_finish = moment(now).add(offset, 'minutes')
                                            .add(moment.duration(len, 'minutes'))
                                            .seconds(0).millisecond(0);

            if (!room_data.next_event ||
                meeting_finish.isBefore(room_data.next_event.start) ||
                meeting_finish.isSame(room_data.next_event.start))
            {
                adhoc_times.push(meeting_finish);
            }
        }

        return res.send(render_template('templates/busyroom.html', {
            room: room,
            start_time: start_time,
            current_event: room_data.current_event,
            next_event: room_data.next_event,
            schedule: calculate_schedule(room_data.schedule, start_time),
            adhoc_times: adhoc_times
        }));
    });
});

app.get('/room/:name/book/:end', function(req, res) {
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var calendarId      = rooms[req.params.name].cal_id;
    var now             = moment.utc().tz(GMT).seconds(0).millisecond(0).toISOString();
    var end             = req.params.end

    var event = {
        'summary': 'Ad-hoc meeting',
        'start'  : {'dateTime': now},
        'end'    : {'dateTime': end},
        'attendees': [
            {
                'email': calendarId // the user from the URL
            },
            {
                'email': req.session.gmail_address  // the logged in user
            }
        ]
    };

    gcal(accessToken).events.insert(calendarId, event, function(err, result) {
        return res.redirect('/room/' + req.params.name + '/');
    });
});

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

    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.name];
    var free_rooms      = [];

    async.map(
        Object.keys(rooms),
        function(item, callback) {
            var room = rooms[item];

            gcal(accessToken).events.list(room.cal_id, {
                maxResults: 100,
                timeMin: moment(1, 'days').subtract().toISOString()
            }, function(err, data) {
                if(err) return res.send(500,err);

                var room_data = schedule_for_room(data);
                var obj = {
                    'name': room.name,
                    'location': room.location
                };
                if (room_data.next_event) {
                    // if tomorrow?
                    obj['available_until'] = room_data.next_event.start.format('HH:mm');
                }
                if (!room_data.current_event) {
                    callback(null, obj);
                } else {
                    callback(null, null)
                }

            });
        },
        function(err, results) {
            var free_rooms = [];

            for (var i=0;i<results.length;i++) {
                var result = results[i];
                if (result !== null) {
                    free_rooms.push(result);
                }
            }
            return res.send(free_rooms);
        }
    )
});

function get_next_meeting_label(accessToken, cal_id, callback) {
    gcal(accessToken).events.list(cal_id, {
        maxResults: 10,
        timeMin: new Date().toISOString()
    }, function(err, data) {
        var label = 'Nothing!';
        if (data.items.length > 0) {
            label = data.items[0]['summary']
        }
        callback(label);
    });
}

app.get('/room/:id/in-use', function(req, res) {
    // gets the detail for the specified room
    console.log('Original URL' + req.originalUrl)
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.id];

    gcal(accessToken).events.list(room.cal_id, {
        maxResults: 100,
        timeMin: moment(1, 'days').subtract().toISOString()
    }, function(err, data) {
        if(err) return res.send(500,err);

        var current_event;
        var schedule = [];

        for (var i=0; i<data.items.length; i++) {
            var ev;
            try {
                ev = new Event(data.items[i]);
            } catch (e) {
                // malformed data
                console.log(e);
            }

            if (ev.confirmed !== true) {
                schedule.push(ev);

                if (ev.is_active()) {
                    current_event = ev;
                }
            }
        }

        get_next_meeting_label(accessToken, room.cal_id, function(next_label) {
            return res.send(render_template('templates/in-progress.html', {
                now: moment().format('dddd, Do MMM YYYY, hh:mm a'),
                room: room,
                room_name: data.summary,
                current_event: current_event,
                schedule: schedule,
                room_in_use: current_event !== undefined,
                next_meeting_label: next_label
            }));
        })
    });
});

app.post('/room/:id/in-use', function(req, res) {
    req.session.lastUrl = req.originalUrl;
    if(!req.session.access_token) return res.redirect('/auth');

    //Create an instance from accessToken
    var accessToken     = req.session.access_token;
    var room            = rooms[req.params.id];

    gcal(accessToken).events.list(room.cal_id, {
        maxResults: 100,
        timeMin: moment(1, 'days').subtract().toISOString()
    }, function(err, data) {
        if(err) return res.send(500,err);

        var current_event;
        var g_event;
        var schedule = [];

        for (var i=0; i<data.items.length; i++) {
            var ev;
            try {
                g_event = data.items[i];
                ev = new Event(data.items[i]);
            } catch (e) {
                // malformed data
                console.log(e);
            }

            if (ev.confirmed !== true) {
                schedule.push(ev);

                if (ev.is_active()) {
                    current_event = ev;
                    break;
                }
            }
        }

        if (current_event === undefined) {
            throw new Error();
        }

        var event_id = g_event['id'];
        g_event['end']['dateTime'] = moment().toISOString();

        gcal(accessToken).events.update(room.cal_id, event_id, g_event, function(err, result) {

            get_next_meeting_label(accessToken, room.cal_id, function(next_label) {

                return res.send({
                    next_meeting_label: next_label
                });
            })
        });
    });
});

passport.use(new GoogleStategy({
	clientID: config.consumer_key,
	clientSecret: config.consumer_secret,
	callbackURL: (process.env.URL || ("http://lvh.me:" + port)) + "/auth/callback",
	scope: ['openid', 'email', 'https://www.googleapis.com/auth/calendar']
},
function (accessToken, refreshToken, profile, done) {
	profile.accessToken = accessToken;
	return done(null, profile);
}))

app.get('/auth',
	passport.authenticate('google', {session:false}));

app.get('/auth/callback',
  passport.authenticate('google', { session: false, failureRedirect: '/login' }),
  function(req, res) {
    req.session.access_token = req.user.accessToken;
    req.session.gmail_address = req.user.emails[0]['value']
    console.log('Session last URL ' + req.session.lastUrl)
    res.redirect(req.session.lastUrl || '/');
  });

app.get('/auth/success', function(request, response) {
  response.redirect(request.session.lastUrl || '/');
});

require('./cal_api')(app, gcal);

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


<commit_before>navigate = function (hash) {
  window.location.replace(Meteor.absoluteUrl() + hash);
};

<commit_msg>Adjusted Meteor.absoluteUrl() to use the secure setting so SSL is enforced. Helps address the issue of accessing https://docs.meteor.com and being redirected to http://docs.meteor.com.<commit_after>navigate = function (hash) {
  window.location.replace(Meteor.absoluteUrl(null, { secure: true }) + hash);
};
<|endoftext|>


<commit_before>/*jslint node: true */

module.exports = function () {
    'use strict';

    var express = require('express'),
        basicAuth = require('basic-auth-connect'),
        request = require('request'),
        bodyParser = require('body-parser'),
        HTTP_BASIC_USER = process.env.HTTP_BASIC_USER,
        HTTP_BASIC_PASS = process.env.HTTP_BASIC_PASS,
        BITBUCKET_USERNAME = process.env.BITBUCKET_USERNAME,
        BITBUCKET_API_KEY = process.env.BITBUCKET_API_KEY,
        app = express();

    function postBitbucketCommitStatus(build, postStatusCallback) {
        var bitbucket_state = 'FAILED',
            bitbucket_url = 'https://' + BITBUCKET_USERNAME + ':' + BITBUCKET_API_KEY + '@api.bitbucket.org/2.0/repositories/' + build.project_name + '/commit/' + build.commit_id + '/statuses/build';

        switch (build.status) {
        case 'success':
            bitbucket_state = 'SUCCESSFUL';
            break;
        case 'testing':
            bitbucket_state = 'INPROGRESS';
            break;
        }

        request({
            url: bitbucket_url,
            method: 'POST',
            json: {
                state: bitbucket_state,
                key: 'CODESHIP-' + build.build_id,
                name: 'Codeship build #' + build.build_id,
                url: build.build_url,
                description: 'Build status: \'' + build.status + '\''
            }
        }, function (err, response, body) {
            if (err) {
                console.error('Error updating Bitbucket commit status:', err);
            }

            if (body && body.error) {
                console.error('Bitbucket returned an error: ', body.error);
            }

            if (response.statusCode !== 200 && response.statusCode !== 201) {
                console.error('Bitbucket returned a non-200/201 statuscode of', response.statusCode);
            }

            postStatusCallback(response.statusCode);
        });
    }

    app.use(bodyParser.json());
    app.enable('trust proxy');

    app.get('/', function (ignore, res) {
        res.status(404).end();
    });

    app.post('/codeship/webhook', basicAuth(function (username, password) {
        return (username === HTTP_BASIC_USER && password === HTTP_BASIC_PASS);
    }), function (req, res) {
        if (!req.body || !req.body.build) {
            console.error('Invalid request: missing \'build\'');
            res.status(400).end();
            return;
        }

        postBitbucketCommitStatus(req.body.build, function (status_code) {
            status_code = (status_code === 200 || status_code === 201) ? 200 : 500;
            res.status(status_code).end();
        });
    });

    return app;
};
<commit_msg>Prevents builds in a 'waiting' state from being marked as failed on Bitbucket.<commit_after>/*jslint node: true */

module.exports = function () {
    'use strict';

    var express = require('express'),
        basicAuth = require('basic-auth-connect'),
        request = require('request'),
        bodyParser = require('body-parser'),
        HTTP_BASIC_USER = process.env.HTTP_BASIC_USER,
        HTTP_BASIC_PASS = process.env.HTTP_BASIC_PASS,
        BITBUCKET_USERNAME = process.env.BITBUCKET_USERNAME,
        BITBUCKET_API_KEY = process.env.BITBUCKET_API_KEY,
        app = express();

    function postBitbucketCommitStatus(build, postStatusCallback) {
        var bitbucket_state = 'FAILED',
            bitbucket_url = 'https://' + BITBUCKET_USERNAME + ':' + BITBUCKET_API_KEY + '@api.bitbucket.org/2.0/repositories/' + build.project_name + '/commit/' + build.commit_id + '/statuses/build';

        switch (build.status) {
        case 'waiting':
            console.info('Codeship has indicated that the build is waiting to take place. Bitbucket will not be updated until the build is in progress.');
            return postStatusCallback(null);
        case 'success':
            bitbucket_state = 'SUCCESSFUL';
            break;
        case 'testing':
            bitbucket_state = 'INPROGRESS';
            break;
        }

        request({
            url: bitbucket_url,
            method: 'POST',
            json: {
                state: bitbucket_state,
                key: 'CODESHIP-' + build.build_id,
                name: 'Codeship build #' + build.build_id,
                url: build.build_url,
                description: 'Build status: \'' + build.status + '\''
            }
        }, function (err, response, body) {
            if (err) {
                console.error('Error updating Bitbucket commit status:', err);
            }

            if (body && body.error) {
                console.error('Bitbucket returned an error: ', body.error);
            }

            if (response.statusCode !== 200 && response.statusCode !== 201) {
                console.error('Bitbucket returned a non-200/201 statuscode of', response.statusCode);
            }

            postStatusCallback(response.statusCode);
        });
    }

    app.use(bodyParser.json());
    app.enable('trust proxy');

    app.get('/', function (ignore, res) {
        res.status(404).end();
    });

    app.post('/codeship/webhook', basicAuth(function (username, password) {
        return (username === HTTP_BASIC_USER && password === HTTP_BASIC_PASS);
    }), function (req, res) {
        if (!req.body || !req.body.build) {
            console.error('Invalid request: missing \'build\'');
            res.status(400).end();
            return;
        }

        postBitbucketCommitStatus(req.body.build, function (status_code) {
            status_code = (status_code === 200 || status_code === 201) ? 200 : 500;
            res.status(status_code).end();
        });
    });

    return app;
};
<|endoftext|>


<commit_before>
/*!
 * Lingo - inflection
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var Language = require('./language');

/**
 * Check if a `word` is uncountable.
 *
 * @param {String} word
 * @return {Boolean}
 * @api public
 */

Language.prototype.isUncountable = function(word){
  return !!this.rules.uncountable[word];
};

/**
 * Add an uncountable `word`.
 *
 * @param {String} word
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.uncountable = function(word){
  this.rules.uncountable[word] = word;
  return this;
};

/**
 * Add an irreglar `singular` / `plural` map.
 *
 * @param {String} singular
 * @param {String} plural
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.irregular = function(singular, plural){
  this.rules.irregular.plural[singular] = plural;
  this.rules.irregular.singular[plural] = singular;
  return this;
};

/**
 * Add a pluralization `rule` for numbers
 *
 * @param {RegExp} rule
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.pluralNumbers = function(rule){
  this.rules.pluralNumbers = rule;
  return this;
};

/**
 * Add a pluralization `rule` with the given `substitution`.
 *
 * @param {RegExp} rule
 * @param {String} substitution
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.plural = function(rule, substitution){
  this.rules.plural.unshift([rule, substitution]);
  return this;
};

/**
 * Add a singularization `rule` with the given `substitution`.
 *
 * @param {RegExp} rule
 * @param {String} substitution
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.singular = function(rule, substitution){
  this.rules.singular.unshift([rule, substitution]);
  return this;
};

/**
 * Pluralize the given `word`.
 *
 * @param {String} word
 * @return {String}
 * @api public
 */

Language.prototype.pluralize = function(word){
  return this.inflect(word, 'plural');
};

/**
 * Check if `word` is plural.
 *
 * @param {String} word
 * @return {Boolean}
 * @api public
 */

Language.prototype.isPlural = function(word){
  if (typeof word === 'number') {
      return (this.rules.pluralNumbers || /.*/).test(word);
  } else {
      return word == this.pluralize(this.singularize(word));
  }
};

/**
 * Singularize the given `word`.
 *
 * @param {String} word
 * @return {String}
 * @api public
 */

Language.prototype.singularize = function(word){
  return this.inflect(word, 'singular');
};

/**
 * Check if `word` is singular.
 *
 * @param {String} word
 * @return {Boolean}
 * @api public
 */

Language.prototype.isSingular = function(word){
  return word == this.singularize(this.pluralize(word));
};

/**
 * Perform `type` inflection rules on the given `word`.
 *
 * @param {String} word
 * @param {String} type
 * @return {String}
 * @api private
 */

Language.prototype.inflect = function(word, type) {
  if (this.isUncountable(word)) return word;

  var irregular = this.rules.irregular[type][word];
  if (irregular) return irregular;

  for (var i = 0, len = this.rules[type].length; i < len; ++i) {
    var rule = this.rules[type][i]
      , regexp = rule[0]
      , sub = rule[1];
    if (regexp.test(word)) {
      return word.replace(regexp, sub);
    }
  }

  return word;
}
<commit_msg>Added single rules for numbers<commit_after>
/*!
 * Lingo - inflection
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var Language = require('./language');

/**
 * Check if a `word` is uncountable.
 *
 * @param {String} word
 * @return {Boolean}
 * @api public
 */

Language.prototype.isUncountable = function(word){
  return !!this.rules.uncountable[word];
};

/**
 * Add an uncountable `word`.
 *
 * @param {String} word
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.uncountable = function(word){
  this.rules.uncountable[word] = word;
  return this;
};

/**
 * Add an irreglar `singular` / `plural` map.
 *
 * @param {String} singular
 * @param {String} plural
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.irregular = function(singular, plural){
  this.rules.irregular.plural[singular] = plural;
  this.rules.irregular.singular[plural] = singular;
  return this;
};

/**
 * Add a pluralization `rule` for numbers
 *
 * @param {RegExp} rule
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.pluralNumbers = function(rule){
  this.rules.pluralNumbers = rule;
  return this;
};

/**
 * Add a pluralization `rule` with the given `substitution`.
 *
 * @param {RegExp} rule
 * @param {String} substitution
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.plural = function(rule, substitution){
  this.rules.plural.unshift([rule, substitution]);
  return this;
};

/**
 * Add a singularization `rule` with the given `substitution`.
 *
 * @param {RegExp} rule
 * @param {String} substitution
 * @return {Language} for chaining
 * @api public
 */

Language.prototype.singular = function(rule, substitution){
  this.rules.singular.unshift([rule, substitution]);
  return this;
};

/**
 * Pluralize the given `word`.
 *
 * @param {String} word
 * @return {String}
 * @api public
 */

Language.prototype.pluralize = function(word){
  return this.inflect(word, 'plural');
};

/**
 * Check if `word` is plural.
 *
 * @param {String or Number} word
 * @return {Boolean}
 * @api public
 */

Language.prototype.isPlural = function (word) {
  if (typeof word === 'number') {
      return (this.rules.pluralNumbers || /.*/).test(word);
  } else {
      return word == this.pluralize(this.singularize(word));
  }
};

/**
 * Singularize the given `word`.
 *
 * @param {String} word
 * @return {String}
 * @api public
 */

Language.prototype.singularize = function (word) {
  return this.inflect(word, 'singular');
};

/**
 * Check if `word` is singular.
 *
 * @param {String or Number} word
 * @return {Boolean}
 * @api public
 */

Language.prototype.isSingular = function (word) {
  return !this.isPlural(word);
};

/**
 * Perform `type` inflection rules on the given `word`.
 *
 * @param {String} word
 * @param {String} type
 * @return {String}
 * @api private
 */

Language.prototype.inflect = function(word, type) {
  if (this.isUncountable(word)) return word;

  var irregular = this.rules.irregular[type][word];
  if (irregular) return irregular;

  for (var i = 0, len = this.rules[type].length; i < len; ++i) {
    var rule = this.rules[type][i]
      , regexp = rule[0]
      , sub = rule[1];
    if (regexp.test(word)) {
      return word.replace(regexp, sub);
    }
  }

  return word;
}
<|endoftext|>


<commit_before>//User inputs their name
var userName = prompt('Welcome to the Guessing Game! What is your name?');
console.log('The user\'s name is ' + userName);

alert('Welcome, ' + userName + ' ! Please guess \'yes or no\' for the following questions!');
var understandCheck = confirm('Are you ready?');

if (understandCheck === true) {
  alert('Great! Let\'s get started');
  console.log(userName + ' is ready to play the guessing game!');
} else {
  alert('What don\'t you understand about answering yes or no?');
  console.log(userName + ' might not be the sharpest tool in the shed.');
}
//Begin guessing game
var answerOne = prompt('Did you know that I am from Chicago?');
if (answerOne.toUpperCase() === 'YES' || answerOne.toUpperCase() === 'Y') {
  alert('That\'s right, ' + userName + '! I am from Chicago!');
  console.log(userName + ' knew that I am from Chicago');
} else {
  alert('Well, ' + userName + ', now you do!');
  console.log(userName + ' did not know that I am from Chicago');
}

var answerTwo = prompt('Yes or No: I have 3 or more pets?');
if (answerTwo.toUpperCase() === 'YES' || answerTwo.toUpperCase() === 'Y') {
  alert('That\'s right ' + userName + '! I have 5 total pets!');
  console.log(userName + ' knew that I had more than 3 pets!');
} else {
  alert('That is incorrect, ' + userName + '. I actually have 5 total pets!');
  console.log(userName + ' did not know that I have more than 3 pets.');
}

var answerThree = prompt('Do I enjoy outdoor activities?');
if (answerThree.toUpperCase() === 'YES' || answerThree.toUpperCase() === 'Y') {
  alert('No, ' + userName + ' ! The only outdoor activity I enjoy is sitting in a beer garden!');
  console.log(userName + ' did not know about my disdain for the outdoors!');
} else {
  alert('That\'s right, ' + userName + '! The only outdoor activity I will partake in is sitting in a beer garden!');
  console.log(userName + ' knew that they would never find me participating in outdoor activities.');
}

var answerFour = prompt('Do you think I am engaged?');
if (answerFour.toUpperCase() === 'YES' || answerFour.toUpperCase() === 'Y') {
  alert('Yep, ' + userName + '! I am planning a wedding for next spring!');
  console.log(userName + ' knew I was engaged.');
} else {
  alert('Shockingly, ' + userName + ', someone actually agreed to marry me!');
  console.log(userName + ' did not think anyne would want to marry me!');
}

var answerFive = prompt('Do you think you can guess what type of dog I have?');
if (answerFive.toUpperCase() === 'YES' || answerFive.toUpperCase() === 'Y') {
  var bonusQuestion = prompt('Ok, hotshot! What type of dog do I have?');
  if (bonusQuestion.toUpperCase() === 'CHIHUAHUA') {
    alert('How did you know I had a Chihuahua? Technically, I have one and a half chihuahuas! \(Yeah, figure that one out!\)');
    console.log(userName + ' knew that I had a chihuahua!');
  } else {
    alert('That is WRONG, ' + userName + '! I have a chihuahua! Well, technically I have one and a half chihuahuas, but I will let you try to figure that one out.');
    console.log(userName + ' thought they knew what kind of dog I had, but they were WRONG!');
  }
} else {
  alert('That\'s ok, ' + userName + '! I will just tell you that I have a chihuahua.');
  console.log(userName + ' did not want to guess what type of dog I have.');
}

//end of guessing game

alert('Thank you, ' + userName + ', for playing my guessing game!');
<commit_msg>added question six<commit_after>//User inputs their name

var userName = prompt('Welcome to the Guessing Game! What is your name?');
console.log('The user\'s name is ' + userName);
/*
alert('Welcome, ' + userName + ' ! Please guess \'yes or no\' for the following questions!');
var understandCheck = confirm('Are you ready?');

if (understandCheck === true) {
  alert('Great! Let\'s get started');
  console.log(userName + ' is ready to play the guessing game!');
} else {
  alert('What don\'t you understand about answering yes or no?');
  console.log(userName + ' might not be the sharpest tool in the shed.');
}
//Begin guessing game
var answerOne = prompt('Did you know that I am from Chicago?');
if (answerOne.toUpperCase() === 'YES' || answerOne.toUpperCase() === 'Y') {
  alert('That\'s right, ' + userName + '! I am from Chicago!');
  console.log(userName + ' knew that I am from Chicago');
} else {
  alert('Well, ' + userName + ', now you do!');
  console.log(userName + ' did not know that I am from Chicago');
}

var answerTwo = prompt('Yes or No: I have 3 or more pets?');
if (answerTwo.toUpperCase() === 'YES' || answerTwo.toUpperCase() === 'Y') {
  alert('That\'s right ' + userName + '! I have 5 total pets!');
  console.log(userName + ' knew that I had more than 3 pets!');
} else {
  alert('That is incorrect, ' + userName + '. I actually have 5 total pets!');
  console.log(userName + ' did not know that I have more than 3 pets.');
}

var answerThree = prompt('Do I enjoy outdoor activities?');
if (answerThree.toUpperCase() === 'YES' || answerThree.toUpperCase() === 'Y') {
  alert('No, ' + userName + ' ! The only outdoor activity I enjoy is sitting in a beer garden!');
  console.log(userName + ' did not know about my disdain for the outdoors!');
} else {
  alert('That\'s right, ' + userName + '! The only outdoor activity I will partake in is sitting in a beer garden!');
  console.log(userName + ' knew that they would never find me participating in outdoor activities.');
}

var answerFour = prompt('Do you think I am engaged?');
if (answerFour.toUpperCase() === 'YES' || answerFour.toUpperCase() === 'Y') {
  alert('Yep, ' + userName + '! I am planning a wedding for next spring!');
  console.log(userName + ' knew I was engaged.');
} else {
  alert('Shockingly, ' + userName + ', someone actually agreed to marry me!');
  console.log(userName + ' did not think anyne would want to marry me!');
}

var answerFive = prompt('Do you think you can guess what type of dog I have?');
if (answerFive.toUpperCase() === 'YES' || answerFive.toUpperCase() === 'Y') {
  var bonusQuestion = prompt('Ok, hotshot! What type of dog do I have?');
  if (bonusQuestion.toUpperCase() === 'CHIHUAHUA') {
    alert('How did you know I had a Chihuahua? Technically, I have one and a half chihuahuas! \(Yeah, figure that one out!\)');
    console.log(userName + ' knew that I had a chihuahua!');
  } else {
    alert('That is WRONG, ' + userName + '! I have a chihuahua! Well, technically I have one and a half chihuahuas, but I will let you try to figure that one out.');
    console.log(userName + ' thought they knew what kind of dog I had, but they were WRONG!');
  }
} else {
  alert('That\'s ok, ' + userName + '! I will just tell you that I have a chihuahua.');
  console.log(userName + ' did not want to guess what type of dog I have.');
}
*/
//adding count down question six
var guessesLeft = 3;
var siblingsLeft = prompt('How many siblings do I have? You have four trys to get it right. Make sure you enter a number!');
var userGuess;
var wrongAnswer = 'Incorrect, ' + userName + '. Try again! You have ' + guessesLeft + ' guesses left!';

while (guessesLeft <= 4 && guessesLeft > 0) {
  if (parseInt(siblingsLeft) === 3) {
    alert('That\'s correct, ' + userName + '! I have four siblings.');
    console.log(userName + ' knew that I had four siblings.');
    break;
  } else if (parseInt(siblingsLeft) < 3) {
    var siblingsLeft = prompt('Try again, ' + userName + '! You have ' + guessesLeft + ' guesses left!');
    guessesLeft--;
  } else if (parseInt(siblingsLeft) > 3) {
    var siblingsLeft = prompt('Try again, ' + userName + '! You have ' + guessesLeft + ' guesses left!');
    guessesLeft--;
  } else {
    var siblingsLeft = prompt('Input error. Please enter a number!');
  }
  if (siblingsLeft !== 3 && guessesLeft === 0) {
    alert('Sorry, ' + userName + ', you ran out of guesses! I have 3 siblings');
  }
}

//end of guessing game

// alert('Thank you, ' + userName + ', for playing my guessing game!');
<|endoftext|>


<commit_before>var express = require('express')
, http = require('http')
, app = express()
, connect = require('express/node_modules/connect')
, fs = require('fs')
, winston = require('winston');

global.winston = winston;
global.ENV_CONFIG = require('./lib/config/config_'+app.settings.env);

require('./lib/orm').setup('./lib/models');

app.set('port', ENV_CONFIG.App.port);

app.configure(function(){
    // view rendering
    app.engine('ejs', require('ejs-locals'));
    app.set('views', __dirname + '/views');
    app.locals({
        _layoutFile : '/layouts/site'
    });
    app.locals.open = '{{';
    app.locals.close = '}}';
    app.set('view engine', 'ejs');
    // allow req.body
    app.use(express.bodyParser());
    app.use(express.cookieParser(ENV_CONFIG.App.sessionSecret));
    // enable PUT and DELETE request methods
    app.use(express.methodOverride());
    // enable event logging to database. NOTE: only designed to log events which contain metadata
    winston.add(require('./lib/winston-sequelize').WinstonSequelize, {
        level            : 'info',
        handleExceptions : false
    });
});

app.configure('development', function(){
    app.use(express.errorHandler({
        dumpExceptions : true,
        showStack      : true
    }));
    app.use(express.session({
        store  : new connect.middleware.session.MemoryStore(),
        secret : ENV_CONFIG.App.sessionSecret
    }));
    // prioritize router before public directory
    app.use(express.static(__dirname + '/public'));
});

app.configure('test', function(){
    app.use(express.errorHandler({
        dumpExceptions : true,
        showStack      : true
    }));
    app.use(express.session({
        store  : new connect.middleware.session.MemoryStore(),
        secret : ENV_CONFIG.App.sessionSecret
    }));
    // prioritize router before public directory
    app.use(express.static(__dirname + '/public'));
});

app.configure('production', function(){
    app.use(express.errorHandler());
    /// TODO: Take out before hitting production
    /* Authentication module to prevent authorized access to factory
    var auth = require('http-auth');
    var basic = auth.basic({
        realm : "Authenticated Area.",
        file  : "./data/users.htpasswd" // manager1@magnetapi.com/test
    });
    app.use(auth.connect(basic));
    */
    // stop exit after an uncaughtException
    winston.exitOnError = false;
    // log only errors to console
    winston.remove(winston.transports.Console);
    winston.add(winston.transports.Console, {
        level            : 'error',
        handleExceptions : true
    });
    // log only errors to support email
    winston.add(require('winston-mail').Mail, {
        to               : ENV_CONFIG.Email.supportEmail,
        from             : ENV_CONFIG.Email.sender,
        host             : ENV_CONFIG.Email.host,
        port             : ENV_CONFIG.Email.port,
        username         : ENV_CONFIG.Email.user,
        password         : ENV_CONFIG.Email.password,
        level            : 'error',
        tls              : true,
        handleExceptions : true
    });
    // log everything to file
    if(!fs.existsSync(ENV_CONFIG.Logging.folder)){
        fs.mkdirSync(ENV_CONFIG.Logging.folder);
        winston.log('Logging: created logging directory.');
    }
    winston.add(winston.transports.File, {
        filename         : ENV_CONFIG.Logging.folder+'/'+ENV_CONFIG.Logging.filename,
        maxsize          : ENV_CONFIG.Logging.maxsize,
        maxFiles         : ENV_CONFIG.Logging.maxFiles,
        handleExceptions : true
    });
    // store sessions to redis
    var RedisStore = require('connect-redis')(express);
    var redisDB = require('redis').createClient(ENV_CONFIG.Redis);
    app.use(express.session({
        secret : ENV_CONFIG.App.sessionSecret,
        store  : new RedisStore({
            client : redisDB,
            secret : ENV_CONFIG.App.sessionSecret
        })
    }));
    // minify client side code and set router to build path
    require('requirejs').optimize(require('./lib/config/ClientBuild'), function(){
        winston.info('Requirejs: successfully optimized client javascript');
    });
    // prioritize router before public directory, use minified public directory
    app.use(express.static(__dirname + '/public-build'));
});

// Routes
require('./routes')(app);

// Run Webserver

var server = http.createServer(app);
server.listen(app.get('port'), function(){
    winston.info("Express: server listening on port %d in %s mode", app.get('port'), app.settings.env);
});<commit_msg>remove mysql log transport<commit_after>var express = require('express')
, http = require('http')
, app = express()
, connect = require('express/node_modules/connect')
, fs = require('fs')
, winston = require('winston');

global.winston = winston;
global.ENV_CONFIG = require('./lib/config/config_'+app.settings.env);

require('./lib/orm').setup('./lib/models');

app.set('port', ENV_CONFIG.App.port);

app.configure(function(){
    // view rendering
    app.engine('ejs', require('ejs-locals'));
    app.set('views', __dirname + '/views');
    app.locals({
        _layoutFile : '/layouts/site'
    });
    app.locals.open = '{{';
    app.locals.close = '}}';
    app.set('view engine', 'ejs');
    // allow req.body
    app.use(express.bodyParser());
    app.use(express.cookieParser(ENV_CONFIG.App.sessionSecret));
    // enable PUT and DELETE request methods
    app.use(express.methodOverride());
    // enable event logging to database. NOTE: only designed to log events which contain metadata
    /*
    winston.add(require('./lib/winston-sequelize').WinstonSequelize, {
        level            : 'info',
        handleExceptions : false
    });
    */
});

app.configure('development', function(){
    app.use(express.errorHandler({
        dumpExceptions : true,
        showStack      : true
    }));
    app.use(express.session({
        store  : new connect.middleware.session.MemoryStore(),
        secret : ENV_CONFIG.App.sessionSecret
    }));
    // prioritize router before public directory
    app.use(express.static(__dirname + '/public'));
});

app.configure('test', function(){
    app.use(express.errorHandler({
        dumpExceptions : true,
        showStack      : true
    }));
    app.use(express.session({
        store  : new connect.middleware.session.MemoryStore(),
        secret : ENV_CONFIG.App.sessionSecret
    }));
    // prioritize router before public directory
    app.use(express.static(__dirname + '/public'));
});

app.configure('production', function(){
    app.use(express.errorHandler());
    /// TODO: Take out before hitting production
    /* Authentication module to prevent authorized access to factory
    var auth = require('http-auth');
    var basic = auth.basic({
        realm : "Authenticated Area.",
        file  : "./data/users.htpasswd" // manager1@magnetapi.com/test
    });
    app.use(auth.connect(basic));
    */
    // stop exit after an uncaughtException
    winston.exitOnError = false;
    // log only errors to console
    winston.remove(winston.transports.Console);
    winston.add(winston.transports.Console, {
        level            : 'error',
        handleExceptions : true
    });
    // log only errors to support email
    winston.add(require('winston-mail').Mail, {
        to               : ENV_CONFIG.Email.supportEmail,
        from             : ENV_CONFIG.Email.sender,
        host             : ENV_CONFIG.Email.host,
        port             : ENV_CONFIG.Email.port,
        username         : ENV_CONFIG.Email.user,
        password         : ENV_CONFIG.Email.password,
        level            : 'error',
        tls              : true,
        handleExceptions : true
    });
    // log everything to file
    if(!fs.existsSync(ENV_CONFIG.Logging.folder)){
        fs.mkdirSync(ENV_CONFIG.Logging.folder);
        winston.log('Logging: created logging directory.');
    }
    winston.add(winston.transports.File, {
        filename         : ENV_CONFIG.Logging.folder+'/'+ENV_CONFIG.Logging.filename,
        maxsize          : ENV_CONFIG.Logging.maxsize,
        maxFiles         : ENV_CONFIG.Logging.maxFiles,
        handleExceptions : true
    });
    // store sessions to redis
    var RedisStore = require('connect-redis')(express);
    var redisDB = require('redis').createClient(ENV_CONFIG.Redis);
    app.use(express.session({
        secret : ENV_CONFIG.App.sessionSecret,
        store  : new RedisStore({
            client : redisDB,
            secret : ENV_CONFIG.App.sessionSecret
        })
    }));
    // minify client side code and set router to build path
    require('requirejs').optimize(require('./lib/config/ClientBuild'), function(){
        winston.info('Requirejs: successfully optimized client javascript');
    });
    // prioritize router before public directory, use minified public directory
    app.use(express.static(__dirname + '/public-build'));
});

// Routes
require('./routes')(app);

// Run Webserver

var server = http.createServer(app);
server.listen(app.get('port'), function(){
    winston.info("Express: server listening on port %d in %s mode", app.get('port'), app.settings.env);
});<|endoftext|>


<commit_before>const colors = {
  '00': ['white'],
  '01': ['black'],
  '02': ['navy'],
  '03': ['green'],
  '04': ['red'],
  '05': ['brown', 'maroon'],
  '06': ['purple', 'violet'],
  '07': ['olive'],
  '08': ['yellow'],
  '09': ['lightgreen', 'lime'],
  '10': ['teal', 'bluecyan'],
  '11': ['cyan', 'aqua'],
  '12': ['blue', 'royal'],
  '13': ['pink', 'lightpurple', 'fuchsia'],
  '14': ['gray', 'grey'],
  '15': ['lightgray', 'lightgrey', 'silver']
};

const styles = {
  normal    : '\x0F',
  underline : '\x1F',
  bold      : '\x02',
  italic    : '\x1D'
};

const styleChars = {};
Object.keys(styles).forEach((key) => {
  styleChars[styles[key]] = true;
});

// Coloring character.
const c = '\x03';
const zero = styles.bold + styles.bold;
const badStr = /^,\d/;
const colorCodeStr = new RegExp(`^${c}\\d\\d`);

const allColors = {
  fg: [], bg: [], styles: Object.keys(styles), custom: [], extras: [],
};

// Make color functions for both foreground and background.
Object.keys(colors).forEach((code) => {
  // Foreground.
  // If the string begins with /,\d/,
  // it can undersirably apply a background color.
  let fg = str => c + code + (badStr.test(str) ? zero : '') + str + c;

  // Background.
  let bg = (str) => {
    // If the string begins with a foreground color already applied,
    // use it to save string space.
    if (colorCodeStr.test(str)) {
      let str2 = str.substr(3);
      return str.substr(0, 3) + ',' + code +
        (str2.indexOf(zero) === 0 ? str2.substr(zero.length) : str2);
    } else {
      return c + '01,' + code + str + c;
    }
  };

  colors[code].forEach((color) => {
    allColors.fg.push(color);
    allColors.bg.push('bg' + color);
    exports[color] = fg;
    exports['bg' + color] = bg;
  });
});

// Style functions.
Object.keys(styles).forEach((style) => {
  let code = styles[style];
  exports[style] = str => code + str + code;
});

// Some custom helpers.
const custom = {
  rainbow: (str, colorArr) => {
    let rainbow = [
      'red', 'olive', 'yellow', 'green', 'blue', 'navy', 'violet'
    ];
    colorArr = colorArr || rainbow;
    let l = colorArr.length;
    let i = 0;

    return str
      .split('')
      .map(c => c !== ' ' ? exports[colorArr[i++ % l]](c) : c)
      .join('');
  },
};

Object.keys(custom).forEach((extra) => {
  allColors.custom.push(extra);
  exports[extra] = custom[extra];
});

// Extras.
const extras = {
  stripColors: str => str.replace(/\x03\d{0,2}(,\d{0,2}|\x02\x02)?/g, ''),

  stripStyle: (str) => {
    let path = [];
    for (let i = 0, len = str.length; i < len; i++) {
      let char = str[i];
      if (styleChars[char] || char === c) {
        let lastChar = path[path.length - 1];
        if (lastChar && lastChar[0] === char) {
          let p0 = lastChar[1];
          // Don't strip out styles with no characters inbetween.
          // And don't strip out color codes.
          if (i - p0 > 1 && char !== c) {
            str = str.slice(0, p0) + str.slice(p0 + 1, i) + str.slice(i + 1);
            i -= 2;
          }
          path.pop();
        } else {
          path.push([str[i], i]);
        }
      }

    }

    // Remove any unmatching style characterss.
    // Traverse list backwards to make removing less complicated.
    for (let char of path.reverse()) {
      if (char[0] !== c) {
        let pos = char[1];
        str = str.slice(0, pos) + str.slice(pos + 1);
      }
    }
    return str;
  },

  stripColorsAndStyle: str => exports.stripColors(exports.stripStyle(str)),
};

Object.keys(extras).forEach((extra) => {
  allColors.extras.push(extra);
  exports[extra] = extras[extra];
});

// Adds all functions to each other so they can be chained.
const addGetters = (fn, types) => {
  Object.keys(allColors).forEach((type) => {
    if (types.indexOf(type) > -1) { return; }
    allColors[type].forEach((color) => {
      if (fn[color] != null) { return; }
      Object.defineProperty(fn, color, {
        get: () => {
          let f = str => exports[color](fn(str));
          addGetters(f, [].concat(types, type));
          return f;
        },
      });
    });
  });
};

Object.keys(allColors).forEach((type) => {
  allColors[type].forEach((color) => {
    addGetters(exports[color], [type]);
  });
});

// Adds functions to global String object.
exports.global = () => {
  let str, irc = {};

  String.prototype.__defineGetter__('irc', function() {
    str = this;
    return irc;
  });

  for (let type in allColors) {
    allColors[type].forEach((color) => {
      let fn = () => exports[color](str);
      addGetters(fn, [type]);
      irc[color] = fn;
    });
  }
};
<commit_msg>feat: add support for inverted text (#17)<commit_after>const colors = {
  '00': ['white'],
  '01': ['black'],
  '02': ['navy'],
  '03': ['green'],
  '04': ['red'],
  '05': ['brown', 'maroon'],
  '06': ['purple', 'violet'],
  '07': ['olive'],
  '08': ['yellow'],
  '09': ['lightgreen', 'lime'],
  '10': ['teal', 'bluecyan'],
  '11': ['cyan', 'aqua'],
  '12': ['blue', 'royal'],
  '13': ['pink', 'lightpurple', 'fuchsia'],
  '14': ['gray', 'grey'],
  '15': ['lightgray', 'lightgrey', 'silver']
};

const styles = {
  normal    : '\x0F',
  underline : '\x1F',
  bold      : '\x02',
  italic    : '\x1D',
  inverse   : '\x16'
};

const styleChars = {};
Object.keys(styles).forEach((key) => {
  styleChars[styles[key]] = true;
});

// Coloring character.
const c = '\x03';
const zero = styles.bold + styles.bold;
const badStr = /^,\d/;
const colorCodeStr = new RegExp(`^${c}\\d\\d`);

const allColors = {
  fg: [], bg: [], styles: Object.keys(styles), custom: [], extras: [],
};

// Make color functions for both foreground and background.
Object.keys(colors).forEach((code) => {
  // Foreground.
  // If the string begins with /,\d/,
  // it can undersirably apply a background color.
  let fg = str => c + code + (badStr.test(str) ? zero : '') + str + c;

  // Background.
  let bg = (str) => {
    // If the string begins with a foreground color already applied,
    // use it to save string space.
    if (colorCodeStr.test(str)) {
      let str2 = str.substr(3);
      return str.substr(0, 3) + ',' + code +
        (str2.indexOf(zero) === 0 ? str2.substr(zero.length) : str2);
    } else {
      return c + '01,' + code + str + c;
    }
  };

  colors[code].forEach((color) => {
    allColors.fg.push(color);
    allColors.bg.push('bg' + color);
    exports[color] = fg;
    exports['bg' + color] = bg;
  });
});

// Style functions.
Object.keys(styles).forEach((style) => {
  let code = styles[style];
  exports[style] = str => code + str + code;
});

// Some custom helpers.
const custom = {
  rainbow: (str, colorArr) => {
    let rainbow = [
      'red', 'olive', 'yellow', 'green', 'blue', 'navy', 'violet'
    ];
    colorArr = colorArr || rainbow;
    let l = colorArr.length;
    let i = 0;

    return str
      .split('')
      .map(c => c !== ' ' ? exports[colorArr[i++ % l]](c) : c)
      .join('');
  },
};

Object.keys(custom).forEach((extra) => {
  allColors.custom.push(extra);
  exports[extra] = custom[extra];
});

// Extras.
const extras = {
  stripColors: str => str.replace(/\x03\d{0,2}(,\d{0,2}|\x02\x02)?/g, ''),

  stripStyle: (str) => {
    let path = [];
    for (let i = 0, len = str.length; i < len; i++) {
      let char = str[i];
      if (styleChars[char] || char === c) {
        let lastChar = path[path.length - 1];
        if (lastChar && lastChar[0] === char) {
          let p0 = lastChar[1];
          // Don't strip out styles with no characters inbetween.
          // And don't strip out color codes.
          if (i - p0 > 1 && char !== c) {
            str = str.slice(0, p0) + str.slice(p0 + 1, i) + str.slice(i + 1);
            i -= 2;
          }
          path.pop();
        } else {
          path.push([str[i], i]);
        }
      }

    }

    // Remove any unmatching style characterss.
    // Traverse list backwards to make removing less complicated.
    for (let char of path.reverse()) {
      if (char[0] !== c) {
        let pos = char[1];
        str = str.slice(0, pos) + str.slice(pos + 1);
      }
    }
    return str;
  },

  stripColorsAndStyle: str => exports.stripColors(exports.stripStyle(str)),
};

Object.keys(extras).forEach((extra) => {
  allColors.extras.push(extra);
  exports[extra] = extras[extra];
});

// Adds all functions to each other so they can be chained.
const addGetters = (fn, types) => {
  Object.keys(allColors).forEach((type) => {
    if (types.indexOf(type) > -1) { return; }
    allColors[type].forEach((color) => {
      if (fn[color] != null) { return; }
      Object.defineProperty(fn, color, {
        get: () => {
          let f = str => exports[color](fn(str));
          addGetters(f, [].concat(types, type));
          return f;
        },
      });
    });
  });
};

Object.keys(allColors).forEach((type) => {
  allColors[type].forEach((color) => {
    addGetters(exports[color], [type]);
  });
});

// Adds functions to global String object.
exports.global = () => {
  let str, irc = {};

  String.prototype.__defineGetter__('irc', function() {
    str = this;
    return irc;
  });

  for (let type in allColors) {
    allColors[type].forEach((color) => {
      let fn = () => exports[color](str);
      addGetters(fn, [type]);
      irc[color] = fn;
    });
  }
};
<|endoftext|>