<commit_before>/*
 Copyright 2015 Aleksandar Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const express = require('express');
const chatHandler = require('./socketHandlers/chat');
const userHandler = require('./socketHandlers/user');
const dbConnector = require('../db/databaseConnector');
const dbUser = require('../db/connectors/user');
const commandHandler = require('./socketHandlers/command');
const teamHandler = require('./socketHandlers/team');
const hackingHandler = require('./socketHandlers/hacking');
const utilityHandler = require('./socketHandlers/utility');
const locationHandler = require('./socketHandlers/location');
const manager = require('../socketHelpers/manager');
const appConfig = require('../config/defaults/config').app;
const databasePopulation = require('../config/defaults/config').databasePopulation;
const logger = require('../utils/logger');
const messenger = require('../socketHelpers/messenger');
const deviceHandler = require('./socketHandlers/device');

const router = new express.Router();

/**
 * @param {Object} io - Socket.IO
 * @returns {Object} Router
 */
function handle(io) {
  router.get('/', (req, res) => {
    res.render('index', {
      title: appConfig.title,
      gMapsKey: appConfig.gMapsKey,
      socketPath: appConfig.socketPath,
      mainJs: appConfig.mode === 'dev' ? 'scripts/bundle.js' : 'scripts/bundle.min.js',
    });
  });

  io.on('connection', (socket) => {
    socket.emit('startup', {
      defaultLanguage: appConfig.defaultLanguage,
      forceFullscreen: appConfig.forceFullscreen,
      gpsTracking: appConfig.gpsTracking,
      customFlags: appConfig.customFlags,
      centerLat: appConfig.centerLat,
      centerLong: appConfig.centerLong,
      cornerOneLat: appConfig.cornerOneLat,
      cornerOneLong: appConfig.cornerOneLong,
      cornerTwoLat: appConfig.cornerTwoLat,
      cornerTwoLong: appConfig.cornerTwoLong,
      defaultZoomLevel: appConfig.defaultZoomLevel,
      radioChannels: appConfig.radioChannels,
      yearModification: appConfig.yearModification,
    });

    socket.on('disconnect', () => {
      dbUser.getUserById(socket.id, (err, user) => {
        if (err || user === null) {
          return;
        }

        dbUser.updateUserSocketId(user.userName, '', (userErr, offlineUser) => {
          if (userErr || offlineUser === null) {
            logger.sendErrorMsg({
              code: logger.ErrorCodes.general,
              text: ['Failed to reset user socket ID'],
              err: userErr,
            });
          }
        });

        dbUser.setUserLastOnline(user.userName, new Date(), (userOnlineErr, offlineUser) => {
          if (userOnlineErr || offlineUser === null) {
            logger.sendErrorMsg({
              code: logger.ErrorCodes.general,
              text: ['Failed to set last online'],
              err: userOnlineErr,
            });
          }
        });

        dbUser.updateUserOnline(user.userName, false, (onlineErr, offlineUser) => {
          if (onlineErr || offlineUser === null) {
            logger.sendErrorMsg({
              code: logger.ErrorCodes.general,
              text: ['Failed to update online'],
              err: onlineErr,
            });
          }
        });

        logger.sendInfoMsg(`${socket.id} ${user.userName} has disconnected`);
      });
    });

    // TODO This should be moved
    /**
     * Invitations command. Returns all invitations to rooms and teams for the user
     * Emits commandFail or commandSuccess with the invitations
     */
    socket.on('getInvitations', () => {
      manager.userAllowedCommand(socket.id, databasePopulation.commands.invitations.commandName, (allowErr, allowed, user) => {
        if (allowErr || !allowed) {
          socket.emit('commandFail');

          return;
        }

        dbConnector.getInvitations(user.userName, (err, list) => {
          if (err) {
            messenger.sendSelfMsg({
              socket,
              message: {
                text: ['Failed to get invitations'],
                text_se: ['Misslyckades med att hämta alla inbjudan'],
              },
            });
            socket.emit('commandFail');

            return;
          } else if (list === null) {
            messenger.sendSelfMsg({
              socket,
              message: {
                text: ['No invitations founds'],
                text_se: ['Inga inbjudan hittades'],
              },
            });

            socket.emit('commandFail');

            return;
          }

          socket.emit('commandSuccess', { newData: { invitations: list.invitations }, freezeStep: true });
        });
      });
    });

    userHandler.handle(socket, io);
    chatHandler.handle(socket, io);
    commandHandler.handle(socket);
    deviceHandler.handle(socket);
    teamHandler.handle(socket, io);
    hackingHandler.handle(socket);
    utilityHandler.handle(socket);
    locationHandler.handle(socket);
  });

  return router;
}

module.exports = handle;
<commit_msg>Custom css through query<commit_after>/*
 Copyright 2015 Aleksandar Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const express = require('express');
const chatHandler = require('./socketHandlers/chat');
const userHandler = require('./socketHandlers/user');
const dbConnector = require('../db/databaseConnector');
const dbUser = require('../db/connectors/user');
const commandHandler = require('./socketHandlers/command');
const teamHandler = require('./socketHandlers/team');
const hackingHandler = require('./socketHandlers/hacking');
const utilityHandler = require('./socketHandlers/utility');
const locationHandler = require('./socketHandlers/location');
const manager = require('../socketHelpers/manager');
const appConfig = require('../config/defaults/config').app;
const databasePopulation = require('../config/defaults/config').databasePopulation;
const logger = require('../utils/logger');
const messenger = require('../socketHelpers/messenger');
const deviceHandler = require('./socketHandlers/device');

const router = new express.Router();

/**
 * @param {Object} io - Socket.IO
 * @returns {Object} Router
 */
function handle(io) {
  router.get('/', (req, res) => {
    res.render('index', {
      title: appConfig.title,
      gMapsKey: appConfig.gMapsKey,
      socketPath: appConfig.socketPath,
      mainJs: appConfig.mode === 'dev' ? 'scripts/bundle.js' : 'scripts/bundle.min.js',
      mainCss: !isNaN(req.query.style) ? `styles/${req.query.style}.css` : 'styles/main.css',
    });
  });

  io.on('connection', (socket) => {
    socket.emit('startup', {
      defaultLanguage: appConfig.defaultLanguage,
      forceFullscreen: appConfig.forceFullscreen,
      gpsTracking: appConfig.gpsTracking,
      customFlags: appConfig.customFlags,
      centerLat: appConfig.centerLat,
      centerLong: appConfig.centerLong,
      cornerOneLat: appConfig.cornerOneLat,
      cornerOneLong: appConfig.cornerOneLong,
      cornerTwoLat: appConfig.cornerTwoLat,
      cornerTwoLong: appConfig.cornerTwoLong,
      defaultZoomLevel: appConfig.defaultZoomLevel,
      radioChannels: appConfig.radioChannels,
      yearModification: appConfig.yearModification,
    });

    socket.on('disconnect', () => {
      dbUser.getUserById(socket.id, (err, user) => {
        if (err || user === null) {
          return;
        }

        dbUser.updateUserSocketId(user.userName, '', (userErr, offlineUser) => {
          if (userErr || offlineUser === null) {
            logger.sendErrorMsg({
              code: logger.ErrorCodes.general,
              text: ['Failed to reset user socket ID'],
              err: userErr,
            });
          }
        });

        dbUser.setUserLastOnline(user.userName, new Date(), (userOnlineErr, offlineUser) => {
          if (userOnlineErr || offlineUser === null) {
            logger.sendErrorMsg({
              code: logger.ErrorCodes.general,
              text: ['Failed to set last online'],
              err: userOnlineErr,
            });
          }
        });

        dbUser.updateUserOnline(user.userName, false, (onlineErr, offlineUser) => {
          if (onlineErr || offlineUser === null) {
            logger.sendErrorMsg({
              code: logger.ErrorCodes.general,
              text: ['Failed to update online'],
              err: onlineErr,
            });
          }
        });

        logger.sendInfoMsg(`${socket.id} ${user.userName} has disconnected`);
      });
    });

    // TODO This should be moved
    /**
     * Invitations command. Returns all invitations to rooms and teams for the user
     * Emits commandFail or commandSuccess with the invitations
     */
    socket.on('getInvitations', () => {
      manager.userAllowedCommand(socket.id, databasePopulation.commands.invitations.commandName, (allowErr, allowed, user) => {
        if (allowErr || !allowed) {
          socket.emit('commandFail');

          return;
        }

        dbConnector.getInvitations(user.userName, (err, list) => {
          if (err) {
            messenger.sendSelfMsg({
              socket,
              message: {
                text: ['Failed to get invitations'],
                text_se: ['Misslyckades med att hämta alla inbjudan'],
              },
            });
            socket.emit('commandFail');

            return;
          } else if (list === null) {
            messenger.sendSelfMsg({
              socket,
              message: {
                text: ['No invitations founds'],
                text_se: ['Inga inbjudan hittades'],
              },
            });

            socket.emit('commandFail');

            return;
          }

          socket.emit('commandSuccess', { newData: { invitations: list.invitations }, freezeStep: true });
        });
      });
    });

    userHandler.handle(socket, io);
    chatHandler.handle(socket, io);
    commandHandler.handle(socket);
    deviceHandler.handle(socket);
    teamHandler.handle(socket, io);
    hackingHandler.handle(socket);
    utilityHandler.handle(socket);
    locationHandler.handle(socket);
  });

  return router;
}

module.exports = handle;
<|endoftext|>


<commit_before>module.exports = function(server) {
    var path = require('path')
    , folio = require('folio')
    , jade = require('jade')
    , po2json = require('po2json')
    , i18n = require('i18n-abide')
    , _ = require('underscore')
    , fs  = require('fs')
    , mbc = require('mbc-common')
    , conf = mbc.config.Webvfx
    , logger  = mbc.logger().addLogger('webvfx_routes')
    , imageFiles = []
    , watchr  = require('watchr')
    , url = require('url')
    , elements = []
    , events = []
    ;

    server.all('/events', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });

    server.all('/init', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });

    server.get("/events", function(req, res) {
        var event = _.findWhere(events, {consumed: false});
        if (event) {
            event.consumed = true;
            res.json(event);
            logger.debug(event);
        } else {
            res.json({"type": "none"});
            logger.debug('NONE');
        }
    });

    server.get("/init", function(req, res) {
        res.json({elements: elements});
        events = _.reject(events, function(event) {
            return event.type === 'add' || event.type === 'remove';
        });
    });

    server.post('/addImage', function(req, res){
        conf.Dirs.uploads
        var full_url = url.format( { protocol: req.protocol, host: req.get('host'), pathname: 'uploads/' + req.body.images });
        var element = {};
        element.id = req.body.id;
        element.type = 'image';
        element.src = full_url;
        element.top = req.body.top;
        element.left = req.body.left;
        element.bottom = req.body.bottom;
        element.right = req.body.right;
        element.height = req.body.height;
        element.width = req.body.width;
        var event = {};
        event.type = 'addImage';
        event.element = element;
        event.consumed = false;
        events.push(event);
        elements.push(element);
        return res.json({});
    });

    server.post('/addBanner', function(req, res){
        var element = {};
        element.id = req.body.id;
        element.type = 'banner';
        element.top = req.body.top;
        element.left = req.body.left;
        element.bottom = req.body.bottom;
        element.right = req.body.right;
        element.height = req.body.height;
        element.width = req.body.width;
        element.background_color = req.body.background_color;
        element.color = req.body.color;
        element.text = req.body.text;
        element.scroll = req.body.scroll;
        var event = {};
        event.type = 'addBanner';
        event.element = element;
        event.consumed = false;
        events.push(event);
        elements.push(element);
        return res.json({});
    });

    server.post('/remove', function(req, res){
        var element = {};
        element.id = req.body.elements;
        var event = {};
        event.type = 'remove';
        event.element = element;
        event.consumed = false;
        events.push(event);
        elements = _.reject(elements, function(item) {
            return item.id === element.id;
        });
        return res.json({});
    });

    server.post('/addEffect', function(req, res){
        var element = {};
        element.id = req.body.elements;
        var animation = {};
        animation.name = req.body.effects;
        animation.duration = req.body.duration;
        animation.iterations = req.body.iterations;
        animation.delay = req.body.delay;
        var event = {};
        event.type = 'animation';
        event.element = element;
        event.animation = animation;
        event.consumed = false;
        events.push(event);
        return res.json({});
    });

    server.post('/move', function(req, res){
        var element = {};
        element.id = req.body.elements;
        var move = {};
        move.x = req.body.x;
        move.y = req.body.y;
        move.duration = req.body.duration;
        var event = {};
        event.type = 'move';
        event.element = element;
        event.move = move;
        event.consumed = false;
        events.push(event);
        return res.json({});
    });

    server.post('/uploadImage', function(req, res){
        fs.readFile(req.files.uploadedFile.path, function (err, data) {
            if(err) {
                logger.error(err);
                return;
            }
            var newPath = path.join(conf.Dirs.uploads, req.files.uploadedFile.name);
            fs.writeFile(newPath, data, function (err) {
                return res.json({});
            });
        });
    });

    server.get('/live.webm',function(req,res){
        logger.info("Enter to ask for video tcp!");
        res.writeHead(200, {
            'Content-Type':'video/mp4',
        });
        videoSocket.pipe(res);
    });

    server.get('/po/:id', function (req, res) {
        var lang = req.params.id;
        var locale = i18n.localeFrom(lang);
        var jsondata = '';
        try {
            jsondata = po2json.parseSync('locale/' + locale + '/LC_MESSAGES/messages.po');
            res.send (jsondata);
        } catch (e) {
            logger.error(e);
        }
    });

    /**
     * Vendor Javascript Package
     */

    var lib_dir = path.join(__dirname, '..', 'vendor')

    var vendorJs = new folio.Glossary([
        require.resolve('jquery-browser/lib/jquery.js'),
        require.resolve('jqueryui-browser/ui/jquery-ui.js'),
        require.resolve('underscore/underscore.js'),
        require.resolve('backbone/backbone.js'),
        require.resolve('jed'),
        require.resolve('knockout-client/knockout.js'),
        require.resolve('knockback/knockback-core.js'),
        path.join(lib_dir, 'kinetic-v4.5.2.js'),
        path.join(lib_dir, 'backbone.modal-min.js'),
    ], {minify: false}); //XXX Hack Dont let uglify minify this: too slow

    // serve using express
    server.get('/js/vendor.js', folio.serve(vendorJs));

    /**
     * Views Javascript Package
     */
    var views = ['editor',
                 'header'
                ];

    var viewsJs = new folio.Glossary(
        views.map (function (e) {
            return path.join(__dirname, '..', 'public/js/views/', e + '.js');
        })
        ,{minify:server.get('minify')}
    );

    server.get('/js/views.js', folio.serve(viewsJs));

    /**
     * Models Javascript Package
     */

    var models = ['Default', 'Editor', 'Sketch'];

    var modelsJs = new folio.Glossary(
        models.map (function (e) {
            return require.resolve(path.join(__dirname, '../models', e));
        //    return require.resolve('mbc-common/models/' + e);
        })
    );

    server.get('/js/models.js', folio.serve(modelsJs));

    /**
     * Template Javascript Package
     *
     * We are going to use pre-compiled
     * jade on the client-side.
     */

    var templates = ['editor',
                     'header',
                     'objects',
                     'alert',
                     'confirm',
                     'prompt',
                    ];

    var getFileName = function (e) {
                return path.join(__dirname, '..', 'views/templates/', e + '.jade');
            };

    var templateJs = new folio.Glossary([
        require.resolve('jade/runtime.js'),
        path.join(__dirname, '..', 'views/templates/js/header.js')].concat(
            templates.map (getFileName)
        ),
        {
        compilers: {
            jade: function (name, source) {
                return 'template[\'' + name + '\'] = ' +
                    jade.compile(source, {
                        filename: getFileName(name),
                        client: true,
                        compileDebug: false
                    }) + ';';
            }
        }
    });

    // serve using express
    server.get('/js/templates.js', folio.serve(templateJs));

    server.get('*',  function(req, res) {
        res.render('index', { name: conf.Branding.name, description: conf.Branding.description });
    });
/*
    return appCollection;
*/
}
<commit_msg>Using min kinetic<commit_after>module.exports = function(server) {
    var path = require('path')
    , folio = require('folio')
    , jade = require('jade')
    , po2json = require('po2json')
    , i18n = require('i18n-abide')
    , _ = require('underscore')
    , fs  = require('fs')
    , mbc = require('mbc-common')
    , conf = mbc.config.Webvfx
    , logger  = mbc.logger().addLogger('webvfx_routes')
    , imageFiles = []
    , watchr  = require('watchr')
    , url = require('url')
    , elements = []
    , events = []
    ;

    server.all('/events', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });

    server.all('/init', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });

    server.get("/events", function(req, res) {
        var event = _.findWhere(events, {consumed: false});
        if (event) {
            event.consumed = true;
            res.json(event);
            logger.debug(event);
        } else {
            res.json({"type": "none"});
            logger.debug('NONE');
        }
    });

    server.get("/init", function(req, res) {
        res.json({elements: elements});
        events = _.reject(events, function(event) {
            return event.type === 'add' || event.type === 'remove';
        });
    });

    server.post('/addImage', function(req, res){
        conf.Dirs.uploads
        var full_url = url.format( { protocol: req.protocol, host: req.get('host'), pathname: 'uploads/' + req.body.images });
        var element = {};
        element.id = req.body.id;
        element.type = 'image';
        element.src = full_url;
        element.top = req.body.top;
        element.left = req.body.left;
        element.bottom = req.body.bottom;
        element.right = req.body.right;
        element.height = req.body.height;
        element.width = req.body.width;
        var event = {};
        event.type = 'addImage';
        event.element = element;
        event.consumed = false;
        events.push(event);
        elements.push(element);
        return res.json({});
    });

    server.post('/addBanner', function(req, res){
        var element = {};
        element.id = req.body.id;
        element.type = 'banner';
        element.top = req.body.top;
        element.left = req.body.left;
        element.bottom = req.body.bottom;
        element.right = req.body.right;
        element.height = req.body.height;
        element.width = req.body.width;
        element.background_color = req.body.background_color;
        element.color = req.body.color;
        element.text = req.body.text;
        element.scroll = req.body.scroll;
        var event = {};
        event.type = 'addBanner';
        event.element = element;
        event.consumed = false;
        events.push(event);
        elements.push(element);
        return res.json({});
    });

    server.post('/remove', function(req, res){
        var element = {};
        element.id = req.body.elements;
        var event = {};
        event.type = 'remove';
        event.element = element;
        event.consumed = false;
        events.push(event);
        elements = _.reject(elements, function(item) {
            return item.id === element.id;
        });
        return res.json({});
    });

    server.post('/addEffect', function(req, res){
        var element = {};
        element.id = req.body.elements;
        var animation = {};
        animation.name = req.body.effects;
        animation.duration = req.body.duration;
        animation.iterations = req.body.iterations;
        animation.delay = req.body.delay;
        var event = {};
        event.type = 'animation';
        event.element = element;
        event.animation = animation;
        event.consumed = false;
        events.push(event);
        return res.json({});
    });

    server.post('/move', function(req, res){
        var element = {};
        element.id = req.body.elements;
        var move = {};
        move.x = req.body.x;
        move.y = req.body.y;
        move.duration = req.body.duration;
        var event = {};
        event.type = 'move';
        event.element = element;
        event.move = move;
        event.consumed = false;
        events.push(event);
        return res.json({});
    });

    server.post('/uploadImage', function(req, res){
        fs.readFile(req.files.uploadedFile.path, function (err, data) {
            if(err) {
                logger.error(err);
                return;
            }
            var newPath = path.join(conf.Dirs.uploads, req.files.uploadedFile.name);
            fs.writeFile(newPath, data, function (err) {
                return res.json({});
            });
        });
    });

    server.get('/live.webm',function(req,res){
        logger.info("Enter to ask for video tcp!");
        res.writeHead(200, {
            'Content-Type':'video/mp4',
        });
        videoSocket.pipe(res);
    });

    server.get('/po/:id', function (req, res) {
        var lang = req.params.id;
        var locale = i18n.localeFrom(lang);
        var jsondata = '';
        try {
            jsondata = po2json.parseSync('locale/' + locale + '/LC_MESSAGES/messages.po');
            res.send (jsondata);
        } catch (e) {
            logger.error(e);
        }
    });

    /**
     * Vendor Javascript Package
     */

    var lib_dir = path.join(__dirname, '..', 'vendor')

    var vendorJs = new folio.Glossary([
        require.resolve('jquery-browser/lib/jquery.js'),
        require.resolve('jqueryui-browser/ui/jquery-ui.js'),
        require.resolve('underscore/underscore.js'),
        require.resolve('backbone/backbone.js'),
        require.resolve('jed'),
        require.resolve('knockout-client/knockout.js'),
        require.resolve('knockback/knockback-core.js'),
        path.join(lib_dir, 'kinetic-v4.5.2.min.js'),
        path.join(lib_dir, 'backbone.modal-min.js'),
    ], {minify: false}); //XXX Hack Dont let uglify minify this: too slow

    // serve using express
    server.get('/js/vendor.js', folio.serve(vendorJs));

    /**
     * Views Javascript Package
     */
    var views = ['editor',
                 'header'
                ];

    var viewsJs = new folio.Glossary(
        views.map (function (e) {
            return path.join(__dirname, '..', 'public/js/views/', e + '.js');
        })
        ,{minify:server.get('minify')}
    );

    server.get('/js/views.js', folio.serve(viewsJs));

    /**
     * Models Javascript Package
     */

    var models = ['Default', 'Editor', 'Sketch'];

    var modelsJs = new folio.Glossary(
        models.map (function (e) {
            return require.resolve(path.join(__dirname, '../models', e));
        //    return require.resolve('mbc-common/models/' + e);
        })
    );

    server.get('/js/models.js', folio.serve(modelsJs));

    /**
     * Template Javascript Package
     *
     * We are going to use pre-compiled
     * jade on the client-side.
     */

    var templates = ['editor',
                     'header',
                     'objects',
                     'alert',
                     'confirm',
                     'prompt',
                    ];

    var getFileName = function (e) {
                return path.join(__dirname, '..', 'views/templates/', e + '.jade');
            };

    var templateJs = new folio.Glossary([
        require.resolve('jade/runtime.js'),
        path.join(__dirname, '..', 'views/templates/js/header.js')].concat(
            templates.map (getFileName)
        ),
        {
        compilers: {
            jade: function (name, source) {
                return 'template[\'' + name + '\'] = ' +
                    jade.compile(source, {
                        filename: getFileName(name),
                        client: true,
                        compileDebug: false
                    }) + ';';
            }
        }
    });

    // serve using express
    server.get('/js/templates.js', folio.serve(templateJs));

    server.get('*',  function(req, res) {
        res.render('index', { name: conf.Branding.name, description: conf.Branding.description });
    });
/*
    return appCollection;
*/
}
<|endoftext|>


<commit_before><commit_msg>added locate to array literal<commit_after><|endoftext|>


<commit_before>var ipn = require('paypal-ipn');
var settings = require('../settings');
var tracking = require('../models/tracking');

/*
 * Public Pages
 */

exports.index = function(req, res){
	tracking.getUserId(function(err, uid) {
		res.locals.uid = uid;
		res.locals._csrf = req.csrfToken();
  	res.render('index', { title: settings.applicationTitle });
	});
};

exports.success = function(req, res) {
	res.render('success', { title: settings.applicationTitle });
};

exports.refresh = function(req, res) {
	res.redirect('/');
};

exports.results = function(req, res) {
	res.render('results', { title: 'Results - '+settings.applicationTitle });
};

/*
 * API
 */

exports.saveEntry = function(req, res) {
	res.send(200);
	tracking.saveEntry(req.body);
};

exports.ipn = function(req, res) {
	res.send(200);
	ipn.verify(req.body, function(err, msg) {
		tracking.saveIPN({
			status: msg,
			err: err,
			body: req.body
		});
		console.log('Paypal Message', req.body, err, msg);
	});
};
<commit_msg>fix csrf<commit_after>var ipn = require('paypal-ipn');
var settings = require('../settings');
var tracking = require('../models/tracking');

/*
 * Public Pages
 */

exports.index = function(req, res){
	tracking.getUserId(function(err, uid) {
		res.locals.uid = uid;
		res.locals._csrf = ''; //req.csrfToken();
  	res.render('index', { title: settings.applicationTitle });
	});
};

exports.success = function(req, res) {
	res.render('success', { title: settings.applicationTitle });
};

exports.refresh = function(req, res) {
	res.redirect('/');
};

exports.results = function(req, res) {
	res.render('results', { title: 'Results - '+settings.applicationTitle });
};

/*
 * API
 */

exports.saveEntry = function(req, res) {
	res.send(200);
	tracking.saveEntry(req.body);
};

exports.ipn = function(req, res) {
	res.send(200);
	ipn.verify(req.body, function(err, msg) {
		tracking.saveIPN({
			status: msg,
			err: err,
			body: req.body
		});
		console.log('Paypal Message', req.body, err, msg);
	});
};
<|endoftext|>


<commit_before><commit_msg>Added useTranslate option to toggle translate-accelerated animation on or off (defaults to true)<commit_after><|endoftext|>


<commit_before>var path = require("path");
var ytUploader = require('youtube-uploader');
var fs = require('fs');
var file = __dirname + client_secrets.json
var json

var filePath = path.join(__dirname, './public/test.MOV')

exports.index = function(req, res){
  res.render('index', { title: "Start Bootstrap"});
};

exports.ping = function(req, res){
  res.send("pong!", 200);
};

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }
  json = JSON.parse(data);
});

exports.uploadVideo = function(req, res) {
  res.write("This is the page where users can upload video", 200);

  youtubeUploader.configure({
  accessToken: ACCESS_TOKEN,  // string
  clientId: json.client_id,  // string
  clientSecret: json.client_secret,  // string
  expiresIn: '3600',  // string (default: '3600')
  idToken: ID_TOKEN,  // string
  refreshToken: REFRESH_TOKEN,  // string
  tokenType: 'Bearer'  // string (default: 'Bearer')
}, function (err) {
  if (err) { return console.error(err.message); }
  youtubeUploader.upload({
    path: filePath,  // string
    title: 'PP Test Upload',  // string
    description: 'Lorem Ipsum Description',  // string
    keywords: 'KEYWORDS',  // array of string
    category: '22',  // string (refer to https://developers.google.com/youtube/v3/docs/videoCategories/list)
    privacy: 'unlisted'  // 'public', 'private', or 'unlisted'
  }, function (err, videoId) {
    // ...
  });
});

};
<commit_msg>routes<commit_after>var path = require("path");
var ytUploader = require('youtube-uploader');
var fs = require('fs');
var file = __dirname + client_secrets.json
var json

var filePath = path.join(__dirname, './public/test.MOV')

exports.index = function(req, res){
  res.render('index', { title: "Start Bootstrap"});
};

exports.ping = function(req, res){
  res.send("pong!", 200);
};

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }
  json = JSON.parse(data);
});

exports.uploadVideo = function(req, res) {
  res.write("This is the page where users can upload video", 200);

  youtubeUploader.configure({
  accessToken: ACCESS_TOKEN,  // string
  clientId: json.client_id,  // string
  clientSecret: json.client_secret,  // string
  expiresIn: '3600',  // string (default: '3600')
  idToken: ID_TOKEN,  // string
  refreshToken: REFRESH_TOKEN,  // string
  tokenType: 'Bearer'  // string (default: 'Bearer')
}, function (err) {
  if (err) { return console.error(err.message); }
  youtubeUploader.upload({
    path: filePath,  // string
    title: 'PP Test Upload',  // string
    description: 'Lorem Ipsum Description',  // string
    keywords: 'KEYWORDS',  // array of string
    category: '22',  // string (refer to https://developers.google.com/youtube/v3/docs/videoCategories/list)
    privacy: 'unlisted'  // 'public', 'private', or 'unlisted'
  }, function (err, videoId) {
    // ...
  });
});

};
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var pgp = require('pg-promise')();
var debug = require('debug')('hitmanstat.us:app');
var axios = require('axios');
var throttleAdapterEnhancer = require('axios-extensions').throttleAdapterEnhancer;
var cloudscraper = require('cloudscraper');
var moment = require('moment');
var router = express.Router();

pgp.pg.defaults.ssl = true;
var db = pgp(process.env.DATABASE_URL);
var tn = new pgp.helpers.TableName(process.env.DATABASE_TABLE, 'public');
var cs = new pgp.helpers.ColumnSet(['service', 'status'], { table:tn });

// CONSTANTS
var TIMEOUT = 25000;
var HIGHLOAD_THRESHOLD = 5000;

// State preserved server-side variables
var initialTime = moment().subtract(1, 'm');
var steamLastRequestTimestamp = 0;
var hitmanLastRequestTimestamp = '';
var hitmanLastRequestContent = '';

// Down counters
var steamDownCounter = 0;
var hitmanDownCounter = 0;
var hitmanForumDownCounter = 0;

// Disable HTTP Caching (cache prevention)
var cacheHeaders = {
  'Cache-Control': 'no-cache, no-store, must-revalidate',
  'Expires': '0'
};

// Internet Explorer compatibility mode
var uaCompatible = {
  'X-UA-Compatible': 'IE=edge,chrome=1'
};

// Make requests throttled with a threshold equal to 60 seconds
// Used by '/events' and '/status/hitmanforum' routes
var httpMediumThrottle = axios.create({
	adapter: throttleAdapterEnhancer(axios.defaults.adapter, { threshold: 60 * 1000 })
});

// Make requests throttled with a threshold equal to 30 seconds
// Used by '/status/steam' and '/status/hitman' routes
var httpHighThrottle = axios.create({
	adapter: throttleAdapterEnhancer(axios.defaults.adapter, { threshold: 30 * 1000 })
});

String.prototype.startsWith = function(str) {
  return (this.indexOf(str) === 0);
};

router.get('/', function(req, res, next) {
  res.set(uaCompatible);
  res.render('index', {
    path: req.path,
    title: 'HITMAN Status'
  });
});

router.get('/events', function(req, res, next) {

  res.set(uaCompatible);

  var query = pgp.as.format("SELECT * FROM $1 WHERE date > NOW() - INTERVAL '30 days' ORDER BY id DESC LIMIT 300", tn);

  db.any(query)
  .then(function(data) {
    res.render('events', {
      path: req.path,
      title: 'HITMAN Status',
      events: data,
      moment: moment
    });
  })
  .catch(function(error) {
    res.locals.status = error.routine;
    res.locals.message = error;
    res.render('error', {
      title: 'HITMAN Status'
    });
  });

});

// Steam WebAPI and Connection Manager (CMs) status
router.get('/status/steam', function(req, res, next) {

  res.set(cacheHeaders);

  var output = '';
  var options = {
    url: 'https://crowbar.steamstat.us/Barney',
    timeout: TIMEOUT,
    headers: {
      'cache-control': 'no-cache',
    },
    validateStatus: function (status) {
      return status === 200;
    }
  };

  var service = {
    success: false,
    status: 'unknown',
    title: null
  };

  var events = [
    { service:"STEAM WEBAPI", status:"unknow" },
    { service:"STEAM CMS", status:"unknown" }
  ];

  httpHighThrottle.request(options).then(function(response) {
    if(response.headers['content-type'].indexOf('application/json') !== -1) {
      if(moment(response.data.time).isAfter(steamLastRequestTimestamp)) {
        debug('New data received from steamstat.us');
        steamLastRequestTimestamp = response.data.time;
        events[0].status = formatServiceStatus(response.data.services.webapi.status, 'steam');
        events[1].status = formatServiceStatus(response.data.services.cms.status, 'steam');
        submitEvents(events);
      }
      res.json(response.data);
    } else {
      // if cloudflare block the request, use cloudscraper to bypass cloudflare's protection
      debug('HTTP request denied by cloudflare');
      cloudscraper.request({
        method: 'GET',
        url: options.url,
        headers: options.headers
      }, function(err, response, body) {
        if (err) {
          service.title = 'request error';
          return res.json(service);
        }
        if(response.headers['content-type'].indexOf('application/json') === -1) {
          service.title = 'bad data';
          return res.json(service);
        }
        try {
          output = JSON.parse(body.toString());
        } catch (e) {
          service.title = 'JSON Parsing Error';
          return res.json(service);
        }
        if(moment(output.time).isAfter(steamLastRequestTimestamp)) {
          debug('New data received from steamstat.us');
          steamLastRequestTimestamp = output.time;
          events[0].status = formatServiceStatus(output.services.webapi.status, 'steam');
          events[1].status = formatServiceStatus(output.services.cms.status, 'steam');
          submitEvents(events);
        }
        res.json(output);
      });
    }
  }).catch(function (error) {
    if (error.response)
      service.title = 'steamstat.us error';
    else if (error.code === 'ECONNABORTED')
      service.title = 'steamstat.us timeout';
    if(!res.headersSent) res.json(service);
  });

});

// www.hitmanforum.com status (only reachable with HTTP protocol)
router.get('/status/hitmanforum', function(req, res, next) {

  res.set(cacheHeaders);

  var options = {
    url: 'http://www.hitmanforum.com',
    timeout: TIMEOUT,
    transformResponse: [
      function () {
        return null;
      }
    ]
  };

  var service = {
    service: 'hitmanforum',
    status: 'down'
  };

  var start = Date.now();

  httpMediumThrottle.request(options).then(function(response) {
    service.status = ((Date.now() - start) > HIGHLOAD_THRESHOLD) ? 'warn' : 'up';
    res.json(service);
  }).catch(function (error) {
    if (error.code === 'ECONNABORTED')
      service.title = 'timeout';
    if(!res.headersSent) res.json(service);
    submitEvents([
      { service:"HITMAN FORUM", status:service.status }
    ]);
  });

});

// Hitman status
router.get('/status/hitman', function(req, res, next) {

  res.set(cacheHeaders);

  var body = '';
  var options = {
    url: 'https://auth.hitman.io/status',
    timeout: TIMEOUT,
    headers: {
      'cache-control': 'no-cache',
    },
    validateStatus: function (status) {
      return status === 200;
    }
  };

  var service = {
    status: 'Down',
    title: null
  };

  var events = [
    { service:"HITMAN AUTHENTICATION", status:"down" },
    { service:"HITMAN PC", status:"down" },
    { service:"HITMAN XboxOne", status:"down" },
    { service:"HITMAN PS4", status:"down" }
  ];

  httpHighThrottle.request(options).then(function(response) {
    if(response.headers['content-type'].indexOf('application/json') !== -1) {
      body = response.data;
      // If hitman server sends a more recent response
      if(moment(body.timestamp).isAfter(hitmanLastRequestTimestamp) || !hitmanLastRequestTimestamp) {
        debug('New data received from auth.hitman.io');
        // store the response
        hitmanLastRequestTimestamp = body.timestamp;
        hitmanLastRequestContent = body;
        // send the new status of hitman services
        events[0].status = "up";
        events[1].status = formatServiceStatus(hitmanLastRequestContent.services['pc-service.hitman.io'].health, 'hitman');
        events[2].status = formatServiceStatus(hitmanLastRequestContent.services['xboxone-service.hitman.io'].health, 'hitman');
        events[3].status = formatServiceStatus(hitmanLastRequestContent.services['ps4-service.hitman.io'].health, 'hitman');
        submitEvents(events);
      }
      res.json(hitmanLastRequestContent);
    } else {
      service.status = 'Unknown';
      service.title = 'Bad data returned by authentication server';
      res.json(service);
      submitEvents([events[0]]);
    }
  }).catch(function (error) {
    if (error.response) {
      switch (error.response.status) {
        case 500:
          service.title = 'Internal authentication server error';
          break;
        case 502:
        case 503:
          service.status = 'Maintenance';
          service.title = 'Temporary Azure backend maintenance';
          break;
        default:
          service.title = 'Unknown error code returned by authentication server - error HTTP ' + error.response.status;
          break;
      }
    } else if (error.code === 'ECONNABORTED') {
      service.status = 'Timed out';
      service.title = 'Authentication server connection timeout';
    } else {
      service.status = 'Unknown - Error code : ' + error.code;
      service.title = 'Unknown error from authentication server';
    }
    if(!res.headersSent) res.json(service);
    submitEvents([events[0]]);
  });

});

router.get('/robots.txt', function (req, res, next) {
  res.type('text/plain');
  res.send("User-Agent: *\nAllow: /");
});

function formatServiceStatus(status, type) {
  var map = null;
  switch (type) {
    case 'hitman':
      map = { healthy:'up', slow:'high load' };
      break;
    case 'steam':
      map = { good:'up', minor:'high load', major:'down' };
      break;
  }
  var regex = new RegExp(Object.keys(map).join("|"), "gi");
  var output = status.replace(regex, function(match) {
    return map[match];
  });
  return output;
}

// Submit events to database
function submitEvents(events) {

  debug('A submission request to database has been initiated (%d event(s))', events.length);

  var noUpEvents = [];
  var downCounter = 0;
  var type = "";

  if(events[0].service.startsWith('STEAM')) {
    type = "STEAM";
    downCounter = steamDownCounter;
  } else if(events[0].service == 'HITMAN FORUM') {
    type = "HMF";
    downCounter = hitmanForumDownCounter;
  } else {
    type = "HITMAN";
    downCounter = hitmanDownCounter;
  }

  // Exclude up and high load status
  for (var index = 0; index < events.length; index++)
    if(events[index].status != 'up' && events[index].status != 'high load') noUpEvents.push(events[index]);

  // If one or more services are not available
  if (noUpEvents.length > 0) {
    if(downCounter === 0)
      downCounter++;
    else if(downCounter > 1)
      downCounter = downCounter * 2;
    if(!moment().isAfter(moment(initialTime.toISOString()).add(downCounter, 'm')))
      return;
    else {
      initialTime = moment();
      switch (type) {
        case "STEAM":
          steamDownCounter++;
          break;
        case "HMF":
          hitmanForumDownCounter++;
          break;
        case "HITMAN":
          hitmanDownCounter++;
          var maintenanceMode = true;
          for (index = 0; index < noUpEvents.length; index++)
            if(noUpEvents[index].status != 'maintenance')
              maintenanceMode = false;
          if(maintenanceMode)
            noUpEvents = [{ service:"HITMAN PC / Xbox One / PS4", status:"maintenance" }];
          break;
      }
    }
    debug('Sending %d event(s)', noUpEvents.length);
    var query = pgp.helpers.insert(noUpEvents, cs);
    db.none(query).catch(function(error) {
      console.error("Failed to submit data to database. Routine " + error.routine + " " + error);
    });
  } else {
    debug("No event sent. Service type '%s' seems available, only 'up' or 'high load' events have been received", type);
    switch (type) {
      case "STEAM":
        steamDownCounter = 0;
        break;
      case "HMF":
        hitmanForumDownCounter = 0;
        break;
      case "HITMAN":
        hitmanDownCounter = 0;
        break;
    }
  }

}

module.exports = router;
<commit_msg>change(): use https to reach hitmanforum.com<commit_after>'use strict';

var express = require('express');
var pgp = require('pg-promise')();
var debug = require('debug')('hitmanstat.us:app');
var axios = require('axios');
var throttleAdapterEnhancer = require('axios-extensions').throttleAdapterEnhancer;
var cloudscraper = require('cloudscraper');
var moment = require('moment');
var router = express.Router();

pgp.pg.defaults.ssl = true;
var db = pgp(process.env.DATABASE_URL);
var tn = new pgp.helpers.TableName(process.env.DATABASE_TABLE, 'public');
var cs = new pgp.helpers.ColumnSet(['service', 'status'], { table:tn });

// CONSTANTS
var TIMEOUT = 25000;
var HIGHLOAD_THRESHOLD = 5000;

// State preserved server-side variables
var initialTime = moment().subtract(1, 'm');
var steamLastRequestTimestamp = 0;
var hitmanLastRequestTimestamp = '';
var hitmanLastRequestContent = '';

// Down counters
var steamDownCounter = 0;
var hitmanDownCounter = 0;
var hitmanForumDownCounter = 0;

// Disable HTTP Caching (cache prevention)
var cacheHeaders = {
  'Cache-Control': 'no-cache, no-store, must-revalidate',
  'Expires': '0'
};

// Internet Explorer compatibility mode
var uaCompatible = {
  'X-UA-Compatible': 'IE=edge,chrome=1'
};

// Make requests throttled with a threshold equal to 60 seconds
// Used by '/events' and '/status/hitmanforum' routes
var httpMediumThrottle = axios.create({
	adapter: throttleAdapterEnhancer(axios.defaults.adapter, { threshold: 60 * 1000 })
});

// Make requests throttled with a threshold equal to 30 seconds
// Used by '/status/steam' and '/status/hitman' routes
var httpHighThrottle = axios.create({
	adapter: throttleAdapterEnhancer(axios.defaults.adapter, { threshold: 30 * 1000 })
});

String.prototype.startsWith = function(str) {
  return (this.indexOf(str) === 0);
};

router.get('/', function(req, res, next) {
  res.set(uaCompatible);
  res.render('index', {
    path: req.path,
    title: 'HITMAN Status'
  });
});

router.get('/events', function(req, res, next) {

  res.set(uaCompatible);

  var query = pgp.as.format("SELECT * FROM $1 WHERE date > NOW() - INTERVAL '30 days' ORDER BY id DESC LIMIT 300", tn);

  db.any(query)
  .then(function(data) {
    res.render('events', {
      path: req.path,
      title: 'HITMAN Status',
      events: data,
      moment: moment
    });
  })
  .catch(function(error) {
    res.locals.status = error.routine;
    res.locals.message = error;
    res.render('error', {
      title: 'HITMAN Status'
    });
  });

});

// Steam WebAPI and Connection Manager (CMs) status
router.get('/status/steam', function(req, res, next) {

  res.set(cacheHeaders);

  var output = '';
  var options = {
    url: 'https://crowbar.steamstat.us/Barney',
    timeout: TIMEOUT,
    headers: {
      'cache-control': 'no-cache',
    },
    validateStatus: function (status) {
      return status === 200;
    }
  };

  var service = {
    success: false,
    status: 'unknown',
    title: null
  };

  var events = [
    { service:"STEAM WEBAPI", status:"unknow" },
    { service:"STEAM CMS", status:"unknown" }
  ];

  httpHighThrottle.request(options).then(function(response) {
    if(response.headers['content-type'].indexOf('application/json') !== -1) {
      if(moment(response.data.time).isAfter(steamLastRequestTimestamp)) {
        debug('New data received from steamstat.us');
        steamLastRequestTimestamp = response.data.time;
        events[0].status = formatServiceStatus(response.data.services.webapi.status, 'steam');
        events[1].status = formatServiceStatus(response.data.services.cms.status, 'steam');
        submitEvents(events);
      }
      res.json(response.data);
    } else {
      // if cloudflare block the request, use cloudscraper to bypass cloudflare's protection
      debug('HTTP request denied by cloudflare');
      cloudscraper.request({
        method: 'GET',
        url: options.url,
        headers: options.headers
      }, function(err, response, body) {
        if (err) {
          service.title = 'request error';
          return res.json(service);
        }
        if(response.headers['content-type'].indexOf('application/json') === -1) {
          service.title = 'bad data';
          return res.json(service);
        }
        try {
          output = JSON.parse(body.toString());
        } catch (e) {
          service.title = 'JSON Parsing Error';
          return res.json(service);
        }
        if(moment(output.time).isAfter(steamLastRequestTimestamp)) {
          debug('New data received from steamstat.us');
          steamLastRequestTimestamp = output.time;
          events[0].status = formatServiceStatus(output.services.webapi.status, 'steam');
          events[1].status = formatServiceStatus(output.services.cms.status, 'steam');
          submitEvents(events);
        }
        res.json(output);
      });
    }
  }).catch(function (error) {
    if (error.response)
      service.title = 'steamstat.us error';
    else if (error.code === 'ECONNABORTED')
      service.title = 'steamstat.us timeout';
    if(!res.headersSent) res.json(service);
  });

});

// www.hitmanforum.com status
router.get('/status/hitmanforum', function(req, res, next) {

  res.set(cacheHeaders);

  var options = {
    url: 'https://www.hitmanforum.com',
    timeout: TIMEOUT,
    transformResponse: [
      function () {
        return null;
      }
    ]
  };

  var service = {
    service: 'hitmanforum',
    status: 'down'
  };

  var start = Date.now();

  httpMediumThrottle.request(options).then(function(response) {
    service.status = ((Date.now() - start) > HIGHLOAD_THRESHOLD) ? 'warn' : 'up';
    res.json(service);
  }).catch(function (error) {
    if (error.code === 'ECONNABORTED')
      service.title = 'timeout';
    if(!res.headersSent) res.json(service);
    submitEvents([
      { service:"HITMAN FORUM", status:service.status }
    ]);
  });

});

// Hitman status
router.get('/status/hitman', function(req, res, next) {

  res.set(cacheHeaders);

  var body = '';
  var options = {
    url: 'https://auth.hitman.io/status',
    timeout: TIMEOUT,
    headers: {
      'cache-control': 'no-cache',
    },
    validateStatus: function (status) {
      return status === 200;
    }
  };

  var service = {
    status: 'Down',
    title: null
  };

  var events = [
    { service:"HITMAN AUTHENTICATION", status:"down" },
    { service:"HITMAN PC", status:"down" },
    { service:"HITMAN XboxOne", status:"down" },
    { service:"HITMAN PS4", status:"down" }
  ];

  httpHighThrottle.request(options).then(function(response) {
    if(response.headers['content-type'].indexOf('application/json') !== -1) {
      body = response.data;
      // If hitman server sends a more recent response
      if(moment(body.timestamp).isAfter(hitmanLastRequestTimestamp) || !hitmanLastRequestTimestamp) {
        debug('New data received from auth.hitman.io');
        // store the response
        hitmanLastRequestTimestamp = body.timestamp;
        hitmanLastRequestContent = body;
        // send the new status of hitman services
        events[0].status = "up";
        events[1].status = formatServiceStatus(hitmanLastRequestContent.services['pc-service.hitman.io'].health, 'hitman');
        events[2].status = formatServiceStatus(hitmanLastRequestContent.services['xboxone-service.hitman.io'].health, 'hitman');
        events[3].status = formatServiceStatus(hitmanLastRequestContent.services['ps4-service.hitman.io'].health, 'hitman');
        submitEvents(events);
      }
      res.json(hitmanLastRequestContent);
    } else {
      service.status = 'Unknown';
      service.title = 'Bad data returned by authentication server';
      res.json(service);
      submitEvents([events[0]]);
    }
  }).catch(function (error) {
    if (error.response) {
      switch (error.response.status) {
        case 500:
          service.title = 'Internal authentication server error';
          break;
        case 502:
        case 503:
          service.status = 'Maintenance';
          service.title = 'Temporary Azure backend maintenance';
          break;
        default:
          service.title = 'Unknown error code returned by authentication server - error HTTP ' + error.response.status;
          break;
      }
    } else if (error.code === 'ECONNABORTED') {
      service.status = 'Timed out';
      service.title = 'Authentication server connection timeout';
    } else {
      service.status = 'Unknown - Error code : ' + error.code;
      service.title = 'Unknown error from authentication server';
    }
    if(!res.headersSent) res.json(service);
    submitEvents([events[0]]);
  });

});

router.get('/robots.txt', function (req, res, next) {
  res.type('text/plain');
  res.send("User-Agent: *\nAllow: /");
});

function formatServiceStatus(status, type) {
  var map = null;
  switch (type) {
    case 'hitman':
      map = { healthy:'up', slow:'high load' };
      break;
    case 'steam':
      map = { good:'up', minor:'high load', major:'down' };
      break;
  }
  var regex = new RegExp(Object.keys(map).join("|"), "gi");
  var output = status.replace(regex, function(match) {
    return map[match];
  });
  return output;
}

// Submit events to database
function submitEvents(events) {

  debug('A submission request to database has been initiated (%d event(s))', events.length);

  var noUpEvents = [];
  var downCounter = 0;
  var type = "";

  if(events[0].service.startsWith('STEAM')) {
    type = "STEAM";
    downCounter = steamDownCounter;
  } else if(events[0].service == 'HITMAN FORUM') {
    type = "HMF";
    downCounter = hitmanForumDownCounter;
  } else {
    type = "HITMAN";
    downCounter = hitmanDownCounter;
  }

  // Exclude up and high load status
  for (var index = 0; index < events.length; index++)
    if(events[index].status != 'up' && events[index].status != 'high load') noUpEvents.push(events[index]);

  // If one or more services are not available
  if (noUpEvents.length > 0) {
    if(downCounter === 0)
      downCounter++;
    else if(downCounter > 1)
      downCounter = downCounter * 2;
    if(!moment().isAfter(moment(initialTime.toISOString()).add(downCounter, 'm')))
      return;
    else {
      initialTime = moment();
      switch (type) {
        case "STEAM":
          steamDownCounter++;
          break;
        case "HMF":
          hitmanForumDownCounter++;
          break;
        case "HITMAN":
          hitmanDownCounter++;
          var maintenanceMode = true;
          for (index = 0; index < noUpEvents.length; index++)
            if(noUpEvents[index].status != 'maintenance')
              maintenanceMode = false;
          if(maintenanceMode)
            noUpEvents = [{ service:"HITMAN PC / Xbox One / PS4", status:"maintenance" }];
          break;
      }
    }
    debug('Sending %d event(s)', noUpEvents.length);
    var query = pgp.helpers.insert(noUpEvents, cs);
    db.none(query).catch(function(error) {
      console.error("Failed to submit data to database. Routine " + error.routine + " " + error);
    });
  } else {
    debug("No event sent. Service type '%s' seems available, only 'up' or 'high load' events have been received", type);
    switch (type) {
      case "STEAM":
        steamDownCounter = 0;
        break;
      case "HMF":
        hitmanForumDownCounter = 0;
        break;
      case "HITMAN":
        hitmanDownCounter = 0;
        break;
    }
  }

}

module.exports = router;
<|endoftext|>


<commit_before>/*
 Copyright 2015 Aleksandar Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const express = require('express');
const chatHandler = require('./socketHandlers/chat');
const userHandler = require('./socketHandlers/user');
const dbUser = require('../db/connectors/user');
const teamHandler = require('./socketHandlers/team');
const hackingHandler = require('./socketHandlers/lanternHacking');
const utilityHandler = require('./socketHandlers/utility');
const locationHandler = require('./socketHandlers/position');
const appConfig = require('../config/defaults/config').app;
const databasePopulation = require('../config/defaults/config').databasePopulation;
const deviceHandler = require('./socketHandlers/device');
const walletHandler = require('./socketHandlers/wallet');
const calibrationJobHandler = require('./socketHandlers/calibrationMission');
const simpleMessageHandler = require('./socketHandlers/simpleMsg');

const router = new express.Router();

/**
 * @param {Object} io - Socket.IO
 * @returns {Object} Router
 */
function handle(io) {
  router.get('/', (req, res) => {
    res.render('index', {
      title: appConfig.title,
      gMapsKey: appConfig.gMapsKey,
      socketPath: appConfig.socketPath,
      mainJs: appConfig.mode === 'dev' ? 'scripts/bundle.js' : 'scripts/bundle.min.js',
      mainCss: !isNaN(req.query.style) ? `styles/${req.query.style}.css` : 'styles/main.css',
    });
  });

  io.on('connection', (socket) => {
    socket.join(databasePopulation.rooms.public.roomName);

    socket.emit('startup', {
      defaultLanguage: appConfig.defaultLanguage,
      forceFullscreen: appConfig.forceFullscreen,
      gpsTracking: appConfig.gpsTracking,
      customFlags: appConfig.customFlags,
      centerLat: appConfig.centerLat,
      centerLong: appConfig.centerLong,
      cornerOneLat: appConfig.cornerOneLat,
      cornerOneLong: appConfig.cornerOneLong,
      cornerTwoLat: appConfig.cornerTwoLat,
      cornerTwoLong: appConfig.cornerTwoLong,
      defaultZoomLevel: appConfig.defaultZoomLevel,
      radioChannels: appConfig.radioChannels,
      yearModification: appConfig.yearModification,
    });

    socket.on('disconnect', () => {
      dbUser.getUserById(socket.id, (err, user) => {
        if (err || user === null) {
          return;
        }

        dbUser.updateUserSocketId(user.userName, '', () => {});
        dbUser.setUserLastOnline(user.userName, new Date(), () => {});
        dbUser.updateUserOnline(user.userName, false, () => {});
        dbUser.updateUserIsTracked(user.userName, false, () => {});
      });
    });

    userHandler.handle(socket, io);
    chatHandler.handle(socket, io);
    deviceHandler.handle(socket, io);
    teamHandler.handle(socket, io);
    hackingHandler.handle(socket, io);
    utilityHandler.handle(socket, io);
    locationHandler.handle(socket, io);
    walletHandler.handle(socket, io);
    calibrationJobHandler.handle(socket, io);
    simpleMessageHandler.handle(socket, io);
  });

  return router;
}

module.exports = handle;
<commit_msg>Sends server mode to client<commit_after>/*
 Copyright 2015 Aleksandar Jankovic

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

'use strict';

const express = require('express');
const chatHandler = require('./socketHandlers/chat');
const userHandler = require('./socketHandlers/user');
const dbUser = require('../db/connectors/user');
const teamHandler = require('./socketHandlers/team');
const hackingHandler = require('./socketHandlers/lanternHacking');
const utilityHandler = require('./socketHandlers/utility');
const locationHandler = require('./socketHandlers/position');
const appConfig = require('../config/defaults/config').app;
const databasePopulation = require('../config/defaults/config').databasePopulation;
const deviceHandler = require('./socketHandlers/device');
const walletHandler = require('./socketHandlers/wallet');
const calibrationJobHandler = require('./socketHandlers/calibrationMission');
const simpleMessageHandler = require('./socketHandlers/simpleMsg');

const router = new express.Router();

/**
 * @param {Object} io - Socket.IO
 * @returns {Object} Router
 */
function handle(io) {
  router.get('/', (req, res) => {
    res.render('index', {
      title: appConfig.title,
      gMapsKey: appConfig.gMapsKey,
      socketPath: appConfig.socketPath,
      mainJs: appConfig.mode === 'dev' ? 'scripts/bundle.js' : 'scripts/bundle.min.js',
      mainCss: !isNaN(req.query.style) ? `styles/${req.query.style}.css` : 'styles/main.css',
    });
  });

  io.on('connection', (socket) => {
    socket.join(databasePopulation.rooms.public.roomName);

    socket.emit('startup', {
      defaultLanguage: appConfig.defaultLanguage,
      forceFullscreen: appConfig.forceFullscreen,
      gpsTracking: appConfig.gpsTracking,
      customFlags: appConfig.customFlags,
      centerLat: appConfig.centerLat,
      centerLong: appConfig.centerLong,
      cornerOneLat: appConfig.cornerOneLat,
      cornerOneLong: appConfig.cornerOneLong,
      cornerTwoLat: appConfig.cornerTwoLat,
      cornerTwoLong: appConfig.cornerTwoLong,
      defaultZoomLevel: appConfig.defaultZoomLevel,
      radioChannels: appConfig.radioChannels,
      yearModification: appConfig.yearModification,
      mode: appConfig.mode,
    });

    socket.on('disconnect', () => {
      dbUser.getUserById(socket.id, (err, user) => {
        if (err || user === null) {
          return;
        }

        dbUser.updateUserSocketId(user.userName, '', () => {});
        dbUser.setUserLastOnline(user.userName, new Date(), () => {});
        dbUser.updateUserOnline(user.userName, false, () => {});
        dbUser.updateUserIsTracked(user.userName, false, () => {});
      });
    });

    userHandler.handle(socket, io);
    chatHandler.handle(socket, io);
    deviceHandler.handle(socket, io);
    teamHandler.handle(socket, io);
    hackingHandler.handle(socket, io);
    utilityHandler.handle(socket, io);
    locationHandler.handle(socket, io);
    walletHandler.handle(socket, io);
    calibrationJobHandler.handle(socket, io);
    simpleMessageHandler.handle(socket, io);
  });

  return router;
}

module.exports = handle;
<|endoftext|>


<commit_before>import {Preset, Clean, CleanDigest, Copy, CssNano, Images, Sass, RollupIife, ScssLint, EsLint, Rev, Uglify, Aggregate, parallel, series, tmpDir} from 'gulp-pipeline/src/index'

import stringify from 'stringify-object'
import gulp from 'gulp'
import findup from 'findup-sync'
const node_modules = findup('node_modules')

let preset = Preset.rails()

// When converting non-modular dependencies into usable ones using rollup-plugin-commonjs, if they don't have properly read exports add them here.
const namedExports = {}
//namedExports[`${node_modules}/corejs-typeahead/dist/bloodhound.js`] = ['Bloodhound']

const rollupConfig = {
  commonjs: {
    options: {
      namedExports: namedExports,
    }
  }
}

const js = new Aggregate(gulp, 'js',
  series(gulp,
    new EsLint(gulp, preset),
    new RollupIife(gulp, preset, {options: {dest: 'application.js'}}, rollupConfig)
  )
)

const css = new Aggregate(gulp, 'css',
  series(gulp,
    new ScssLint(gulp, preset),
    new Sass(gulp, preset)
  )
)

const defaultRecipes = new Aggregate(gulp, 'default',
  series(gulp,
    new Clean(gulp, preset),
    parallel(gulp,
      new Images(gulp, preset),
      js,
      css
    )
  )
)

// Create the production assets
const minifiedAssetsDir = tmpDir()
console.log(`Using ******* ${minifiedAssetsDir}`)

// digests need to be one task, tmpDir makes things interdependent
const digests = {debug: true, task: false, watch: false}

const digest = new Aggregate(gulp, 'digest',
  series(gulp,
    new CleanDigest(gulp, preset, digests),

    // minify application.(css|js) to a tmp directory
    parallel(gulp,
      new Uglify(gulp, preset, digests, {dest: minifiedAssetsDir, concat: {dest: 'application.js'}}),
      new CssNano(gulp, preset, digests, {dest: minifiedAssetsDir, minExtension: false})
    ),

    // rev minified css|js from tmp
    new Rev(gulp, preset, digests, {
      source: {
        options: {
          cwd: minifiedAssetsDir
        }
      }
    }),
    // rev all the rest from the debug dir
    new Rev(gulp, preset, digests, {
      source: {
        options: {
          ignore: ['application.js', 'application.js.map', 'application.css']
        }
      },
      options: {merge: true}
    })
  )
)

// default then digest
new Aggregate(gulp, 'build',
  series(gulp,
    defaultRecipes,
    digest
  )
)
<commit_msg>sample rev is almost working, but rev merge isn't working yet<commit_after>import {Preset, Clean, CleanDigest, Copy, CssNano, Images, Sass, RollupIife, ScssLint, EsLint, Rev, Uglify, Aggregate, parallel, series, tmpDir, sleep, clean} from 'gulp-pipeline/src/index'

import stringify from 'stringify-object'
import gulp from 'gulp'
import findup from 'findup-sync'
const node_modules = findup('node_modules')

let preset = Preset.rails()

// When converting non-modular dependencies into usable ones using rollup-plugin-commonjs, if they don't have properly read exports add them here.
const namedExports = {}
//namedExports[`${node_modules}/corejs-typeahead/dist/bloodhound.js`] = ['Bloodhound']

const rollupConfig = {
  commonjs: {
    options: {
      namedExports: namedExports,
    }
  }
}

const js = new Aggregate(gulp, 'js',
  series(gulp,
    new EsLint(gulp, preset),
    new RollupIife(gulp, preset, {options: {dest: 'application.js'}}, rollupConfig)
  )
)

const css = new Aggregate(gulp, 'css',
  series(gulp,
    new ScssLint(gulp, preset),
    new Sass(gulp, preset)
  )
)

const defaultRecipes = new Aggregate(gulp, 'default',
  series(gulp,
    new Clean(gulp, preset),
    parallel(gulp,
      new Images(gulp, preset),
      js,
      css
    )
  )
)

// Create the production assets
const minifiedAssetsDir = tmpDir()
console.log(`Using ******* ${minifiedAssetsDir}`)

// digests need to be one task, tmpDir makes things interdependent
const digests = {debug: true, task: false, watch: false}

const digest = new Aggregate(gulp, 'digest',
  series(gulp,
    new CleanDigest(gulp, preset, digests),

    // minify application.(css|js) to a tmp directory
    parallel(gulp,
      new Uglify(gulp, preset, digests, {dest: minifiedAssetsDir, concat: {dest: 'application.js'}}),
      new CssNano(gulp, preset, digests, {dest: minifiedAssetsDir, minExtension: false})
    ),

    // rev minified css|js from tmp
    new Rev(gulp, preset, digests, {
      source: {
        options: {
          cwd: minifiedAssetsDir
        }
      }
    }),
    //sleep(gulp, 8000),

    //FIXME: rev merging isn't working yet

    // rev all the rest from the debug dir
    new Rev(gulp, preset, digests, {
      source: {
        options: {
          ignore: ['**/application.js', '**/*.js.map', '**/application.css']
        }
      },
      options: {merge: true}
    })
  )
)

// default then digest
new Aggregate(gulp, 'build',
  series(gulp,
    defaultRecipes,
    digest
  )
)
<|endoftext|>


<commit_before><commit_msg>:lipstick: Added flex<commit_after><|endoftext|>


<commit_before>
//------------------------------
//- Modulos instalados por mi --
//------------------------------

var nodemailer = require('nodemailer'); // Nodemailer es un módulo externo de node que nos permite mandar correos.
var express = require('express');
var router = express.Router();

// Get home webpage
// I use a REGEX when / and /es will load the same spanish view.
// http://stackoverflow.com/questions/15350025/multiple-routes-single-function-call-express-js

router.get('/:var(en)?', function(req, res, next) {
	res.render('index_comingsoon_EN', {
		page: 'index',
		title: 'Jorge Ferreiro - Programmer - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Programmer. Node, javascript, HTML5, CSS3, JQuery. Backend developer and frontend developer',
		special : false
	});
});

router.get( '/es' , function(req, res, next) {
	res.render('index_comingsoon_ES', {
		page: "index",
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get( '/university' , function(req, res, next) {
	res.render('university', {
		page: "university",
		title: 'University program - Jorge Ferreiro - Computer science student and programmer.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});
router.get( '/app-stadistics' , function(req, res, next) {
	res.render('app-stadistics', {
		page: "stadistics",
		title: 'App stadistics - Jorge Ferreiro - Computer science student and programmer.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get( '/en/contact' , function(req, res, next) {
	res.render('contact', {
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get('/adaptada', function(req, res, next) {
	res.render('index', {
		title: 'Jorge Ferreiro - Programador full stack - node, javascript, less.js, jade y más. Backend y frontend.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery',
		special : true
	});
});

router.post('/contact', function (req, res, next) {
    var form; // keep the form data in one variable
    var transporter; // mail variables.
    var msg; // Body message to send the user.

    // Creating a form object and saving the &_POST data.
    // req.body also is an object with the same data  var form = req.body.
    // We use form object to pass the form data to the view and make "JSON" responses.

    form = {
    	subject: 'Tomar algo con Jorge',
        name: req.body.name,
        email: req.body.email,
        day: req.body.day,
        month: req.body.month,
        year: req.body.year,
        time: req.body.time,
        plan: req.body.plan,
        error: false
    }

	// Create reusable transporter object using SMTP transport
	transporter = nodemailer.createTransport({
	    service: 'Gmail',
	    auth: {
	        user: 'landcreativaContactForm@gmail.com',
	        pass: 'landcreativad5Gk6VLpfvmLeGc24HYg'
	    }
	});

	// Preparing email message
	msg =  '';
	msg += '
Mensaje
';
	msg += '
';
	msg += 'Nombre: '  + form.name +'
 ';
	msg += 'Email: '   + form.email + '
';
	msg += 'Date: '    + form.day + '/' + form.month + '/' + form.year + '
';
	msg += 'Time: '    + form.time + '
';
	msg += 'Plan: '    + form.plan + '
';
	msg += '
';
	msg += '';

	// Setup e-mail data with unicode symbols
	var mailOptions = {
	    from: 'Jorge <me@jgferreiro.com>', // sender address
	    to: 'me@jgferreiro.com, ferreirostartups@gmail.com', // list of receivers
	    replyTo: form.email,
	    subject: 'Mensaje de ' + form.name + ' - ' + form.subject, // Subject line
	    html: msg // html body
	};

	// Send mail with defined transport object
	transporter.sendMail(mailOptions, function(error, info) {
		form.error = error; // True: error on the email | false: everything is ok
	});

    // Devolver JSON para cuando se haga un formulario ajax.
    res.json({
        data: form          // We pass the form object we created before
    });

});

module.exports = router;
<commit_msg>Update index.js<commit_after>
//------------------------------
//- Modulos instalados por mi --
//------------------------------

var nodemailer = require('nodemailer'); // Nodemailer es un módulo externo de node que nos permite mandar correos.
var express = require('express');
var router = express.Router();

// Get home webpage
// I use a REGEX when / and /es will load the same spanish view.
// http://stackoverflow.com/questions/15350025/multiple-routes-single-function-call-express-js

router.get('/:var(en)?', function(req, res, next) {
	res.render('index_comingsoon_EN', {
		page: 'index',
		title: 'Jorge Ferreiro - Programmer - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Programmer. Node, javascript, HTML5, CSS3, JQuery. Backend developer and frontend developer',
		special : false
	});
});

router.get( '/es' , function(req, res, next) {
	res.render('index', {
		page: "index",
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get( '/university' , function(req, res, next) {
	res.render('university', {
		page: "university",
		title: 'University program - Jorge Ferreiro - Computer science student and programmer.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});
router.get( '/app-stadistics' , function(req, res, next) {
	res.render('app-stadistics', {
		page: "stadistics",
		title: 'App stadistics - Jorge Ferreiro - Computer science student and programmer.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get( '/en/contact' , function(req, res, next) {
	res.render('contact', {
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get('/adaptada', function(req, res, next) {
	res.render('index', {
		title: 'Jorge Ferreiro - Programador full stack - node, javascript, less.js, jade y más. Backend y frontend.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery',
		special : true
	});
});

router.post('/contact', function (req, res, next) {
    var form; // keep the form data in one variable
    var transporter; // mail variables.
    var msg; // Body message to send the user.

    // Creating a form object and saving the &_POST data.
    // req.body also is an object with the same data  var form = req.body.
    // We use form object to pass the form data to the view and make "JSON" responses.

    form = {
    	subject: 'Tomar algo con Jorge',
        name: req.body.name,
        email: req.body.email,
        day: req.body.day,
        month: req.body.month,
        year: req.body.year,
        time: req.body.time,
        plan: req.body.plan,
        error: false
    }

	// Create reusable transporter object using SMTP transport
	transporter = nodemailer.createTransport({
	    service: 'Gmail',
	    auth: {
	        user: 'landcreativaContactForm@gmail.com',
	        pass: 'landcreativad5Gk6VLpfvmLeGc24HYg'
	    }
	});

	// Preparing email message
	msg =  '';
	msg += '
Mensaje
';
	msg += '
';
	msg += 'Nombre: '  + form.name +'
 ';
	msg += 'Email: '   + form.email + '
';
	msg += 'Date: '    + form.day + '/' + form.month + '/' + form.year + '
';
	msg += 'Time: '    + form.time + '
';
	msg += 'Plan: '    + form.plan + '
';
	msg += '
';
	msg += '';

	// Setup e-mail data with unicode symbols
	var mailOptions = {
	    from: 'Jorge <me@jgferreiro.com>', // sender address
	    to: 'me@jgferreiro.com, ferreirostartups@gmail.com', // list of receivers
	    replyTo: form.email,
	    subject: 'Mensaje de ' + form.name + ' - ' + form.subject, // Subject line
	    html: msg // html body
	};

	// Send mail with defined transport object
	transporter.sendMail(mailOptions, function(error, info) {
		form.error = error; // True: error on the email | false: everything is ok
	});

    // Devolver JSON para cuando se haga un formulario ajax.
    res.json({
        data: form          // We pass the form object we created before
    });

});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var aglio = require('aglio');
var github = require('octonode');
var cache = require('memory-cache');

var ensureAuthenticated = function(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else
    return res.redirect('/auth/google?next=' + req.url);
};

router.post('/', function(req, res) {
  var repo = req.body.repository.full_name;
  var ref = 'master';

  // if the push event has a ref
  if (req.body.ref) {
    // Example Procedure
    // req.body.ref === 'refs/heads/develop'
    // refsplit = ['refs', 'heads', 'develop']
    // ref = 'develop'
    var refsplit = req.body.ref.split('/');

    // and it has three components
    if (refsplit.length == 3) {
      // then we'll update our ref to that last piece
      ref = refsplit[2];
    }
  }

  // build our cache key
  var CACHE_KEY = repo + '?ref=' + ref;

  // and delete the cache element
  cache.del(CACHE_KEY);

  console.log("CACHE CLEARED " + CACHE_KEY);

  return res.status(200).end();
});

router.get('/', function(req, res) {
  // if some params are specified
  if (req.query.owner || req.query.repository || req.query.ref) {

    // then check if all are specified
    if (req.query.owner && req.query.repository && req.query.ref) {
      // if they are, then send them on to the docs
      return res.redirect('/docs/' + req.query.owner + '/' + req.query.repository + '?ref=' + req.query.ref);
    }

    var owner = process.env.DEFAULT_OWNER;

    if (req.query.owner) {
      owner = req.query.owner;
    }

    // otherwise, there's an issue
    return res.render('index', { error: true, owner: owner, repository: req.query.repository, ref: req.query.ref });

  }

  return res.render('index', { error: false, owner: process.env.DEFAULT_OWNER, repository: "", ref: "master" });
});

router.get('/docs/:owner/:repository', ensureAuthenticated, function(req, res, next) {

  var repo = req.params.owner + '/' + req.params.repository;
  var ref = 'master';

  if (req.query.ref) {
    ref = req.query.ref;
  }

  var CACHE_KEY = repo + '?ref=' + ref;

  var html = cache.get(CACHE_KEY);

  if (html) {
    console.log("CACHE GET " + CACHE_KEY);
    return res.send(html);
  } else {
    var client = github.client(process.env.GITHUB_TOKEN);

    var ghrepo = client.repo(repo);

    ghrepo.contents(process.env.DOCS_PATH, ref, function(err, data) {
      if (err) {
        if (err.statusCode === 404) {
          console.log("Not Found: " + CACHE_KEY);
          return res.status(404).send("Not found");
        }

        console.error(err);
        res.status(500).send("An error occured.");
        return;
      }

      var blueprint = new Buffer(data.content, 'base64').toString('utf8');

      var options = {};

      aglio.render(blueprint, options, function(err, html) {
          if (err) {
            console.error(err);
            return res.status(500);
          }

          // ensure all assets are https
          html = html.replace(/http\:\/\//g, 'https://');

          cache.put(CACHE_KEY, html);
          console.log("CACHE POPULATED " + CACHE_KEY);

          return res.send(html);
      });
    });
  }
});

module.exports = router;
<commit_msg>Added auth to root endpoint<commit_after>var express = require('express');
var router = express.Router();
var aglio = require('aglio');
var github = require('octonode');
var cache = require('memory-cache');

var ensureAuthenticated = function(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else
    return res.redirect('/auth/google?next=' + req.url);
};

router.post('/', function(req, res) {
  var repo = req.body.repository.full_name;
  var ref = 'master';

  // if the push event has a ref
  if (req.body.ref) {
    // Example Procedure
    // req.body.ref === 'refs/heads/develop'
    // refsplit = ['refs', 'heads', 'develop']
    // ref = 'develop'
    var refsplit = req.body.ref.split('/');

    // and it has three components
    if (refsplit.length == 3) {
      // then we'll update our ref to that last piece
      ref = refsplit[2];
    }
  }

  // build our cache key
  var CACHE_KEY = repo + '?ref=' + ref;

  // and delete the cache element
  cache.del(CACHE_KEY);

  console.log("CACHE CLEARED " + CACHE_KEY);

  return res.status(200).end();
});

router.get('/', ensureAuthenticated, function(req, res) {
  // if some params are specified
  if (req.query.owner || req.query.repository || req.query.ref) {

    // then check if all are specified
    if (req.query.owner && req.query.repository && req.query.ref) {
      // if they are, then send them on to the docs
      return res.redirect('/docs/' + req.query.owner + '/' + req.query.repository + '?ref=' + req.query.ref);
    }

    var owner = process.env.DEFAULT_OWNER;

    if (req.query.owner) {
      owner = req.query.owner;
    }

    // otherwise, there's an issue
    return res.render('index', { error: true, owner: owner, repository: req.query.repository, ref: req.query.ref });

  }

  return res.render('index', { error: false, owner: process.env.DEFAULT_OWNER, repository: "", ref: "master" });
});

router.get('/docs/:owner/:repository', ensureAuthenticated, function(req, res, next) {

  var repo = req.params.owner + '/' + req.params.repository;
  var ref = 'master';

  if (req.query.ref) {
    ref = req.query.ref;
  }

  var CACHE_KEY = repo + '?ref=' + ref;

  var html = cache.get(CACHE_KEY);

  if (html) {
    console.log("CACHE GET " + CACHE_KEY);
    return res.send(html);
  } else {
    var client = github.client(process.env.GITHUB_TOKEN);

    var ghrepo = client.repo(repo);

    ghrepo.contents(process.env.DOCS_PATH, ref, function(err, data) {
      if (err) {
        if (err.statusCode === 404) {
          console.log("Not Found: " + CACHE_KEY);
          return res.status(404).send("Not found");
        }

        console.error(err);
        res.status(500).send("An error occured.");
        return;
      }

      var blueprint = new Buffer(data.content, 'base64').toString('utf8');

      var options = {};

      aglio.render(blueprint, options, function(err, html) {
          if (err) {
            console.error(err);
            return res.status(500);
          }

          // ensure all assets are https
          html = html.replace(/http\:\/\//g, 'https://');

          cache.put(CACHE_KEY, html);
          console.log("CACHE POPULATED " + CACHE_KEY);

          return res.send(html);
      });
    });
  }
});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/search', function(req, res) {
    if (!req.query.hasOwnProperty("inp")) return res.sendStatus(400);
    res.render('searchres', { search: req.query.inp });
});

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'unicode-webapp' });
});

module.exports = router;
<commit_msg>Use error handlers for 400 page<commit_after>var express = require('express');
var router = express.Router();

router.get('/search', function(req, res, next) {
    if (!req.query.hasOwnProperty("inp")) {
        var err = new Error('Bad Request');
        err.status = 400;
        next(err);
    }
    res.render('searchres', { search: req.query.inp });
});

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'unicode-webapp' });
});

module.exports = router;
<|endoftext|>