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

var moment = require('moment');

var cars = require('../data/cars');
var cities = require('../data/cities');
var hotels = require('../data/hotelPrises');
var rooms = require('../data/rooms');

var parseData = require('../lib/parseData');

var H = require('../models/hotel');

var async = require('async');

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

    res.render('index', {
        cars    : cars,
        cities  : cities,
        hotels  : hotels,
        rooms   : rooms
    });

});

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

    res.render('test', {
        hotels: hotels,
        cities: cities,
        rooms : rooms
    });

});

router.get('/api/hotels/', function (req, res) {

    H.find({}, function (err, hotels) {
        if (err) throw  err;

        res.json(hotels);
    })

});

router.post('/test', function (req ,res) {

});

router.post('/', function (req, res) {

    console.log("Processing data..");

    var submittedData = req.body;

    var acc = {
        daysTotal: 0,
        accommodations : [
            {
                accommodationId : 0,
                city            : "",
                hotel           : "",
                moveIn          : "",
                moveout         : "",
                rooms   : [
                    {
                        roomId      : 0,
                        roomType    : "",
                        roomsAmount : 0,
                        roomPrice   : 0
                    }
                ]
            }
        ]
    };

    var accommodations = [];

    for (var i=0; i<=10; i++) {

        //accommodation

        var city = "accommodation_city_" + i;

        if (submittedData.hasOwnProperty(city)) {

            var hotel = "accommodation_hotel_" + i;
            var moveIn = "accommodation_moveIn_" + i;
            var moveOut = "accommodation_moveOut_" + i;

            var cityVal = "";
            var hotelVal = "";
            var moveInVal = "";
            var moveOutVal = "";

            var rooms = [];

            cityVal = submittedData[city];

            if (submittedData.hasOwnProperty(hotel)) {
                hotelVal = submittedData[hotel];
            }

            if (submittedData.hasOwnProperty(moveIn)) {
                moveInVal = moment(submittedData[moveIn], "DD-MM-YYYY");
            }

            if (submittedData.hasOwnProperty(moveOut)) {
                moveOutVal = moment(submittedData[moveOut], "DD-MM-YYYY");
            }

            for (var j=0; j<=50; j++) {

                var roomType    = "room_roomType_"+i+"_"+j;

                if (submittedData.hasOwnProperty(roomType)) {

                    var roomAmount  = "room_roomAmount_"+i+"_"+j;
                    var roomPrice   = "room_roomPrice_"+i+"_"+j;

                    var roomTypeVal     = "";
                    var roomAmountVal   = 0;
                    var roomPriceVal    = 0;

                    roomTypeVal     = submittedData[roomType];
                    roomAmountVal   = submittedData[roomAmount];
                    roomPriceVal    = submittedData[roomPrice];

                    //if (submittedData.hasOwnProperty[roomAmount]) {
                    //    roomAmountVal = submittedData[roomAmount];
                    //}
                    //
                    //if (submittedData.hasOwnProperty[roomPrice]) {
                    //    roomPriceVal = submittedData[roomPrice];
                    //}

                    rooms.push({
                        roomId      : j,
                        roomType    : roomTypeVal,
                        roomAmount  : roomAmountVal,
                        roomPrice   : roomPriceVal

                    });

                }

            }

            accommodations.push({
                accommodationId : i,
                city            : cityVal,
                hotel           : hotelVal,
                moveIn          : moveInVal,
                moveOut         : moveOutVal,
                rooms           : rooms
            });
        }
    }

    //calculation
    var accommodationsCount = accommodations.length;
    var fullCost            = 0;

    for (var k=0; k<accommodationsCount; k++){

        var days = accommodations[k].moveOut.diff(accommodations[k].moveIn, 'days');

        for (var l=0; l<accommodations[k].rooms.length; l++) {

            fullCost += parseInt(accommodations[k].rooms[l].roomPrice) * parseInt(accommodations[k].rooms[l].roomAmount) * days;

        }

    }

    var program = [
        {
            day  : 0,
            city : "",
            services: [
                {
                    type        : "",
                    // driver & transfer
                    carType     : "",
                    from        : "",
                    to          : "",
                    //rest
                    restaurant  : "",
                    menu        : "",
                    //excursion
                    goingPlace  : "",
                    pplAmount   : "",

                    price       : 0
                }
            ]
        }
    ];

    var programs = [];
    var services = [];

    for (var m=0; m<=10; m++) {

        var day = "day_city_" + m;

        if (submittedData.hasOwnProperty(day)) {

            for (var n=0; n<=50; n++) {

                var serviceType = "service_serviceType_"+m+"_"+n;

                if (submittedData.hasOwnProperty(serviceType)) {

                    var serviceTypeVal = submittedData[serviceType];

                    //transfer
                    var transferCarType   = "";
                    var transferCarAmount = 0;
                    var transferFrom      = "";
                    var transferTo        = "";
                    var transferPrice     = 0;

                    //driver
                    var driverCarType    = "";
                    var driverHours      = "";
                    var driverCarsAmount = 0;
                    var driverPrice      = 0;

                    //excursion
                    var goingPlace      = "";
                    var pplAmount       = "";
                    var excursionPrice  = 0;

                    //food
                    var restaurant      = "";
                    var menu            = "";
                    var foodPrice       = "";

                    switch (serviceTypeVal) {
                        case "transfer" :

                            transferCarType = submittedData["transferCarType_"+m+"_"+n];
                            transferCarAmount = submittedData["transferCarAmount_"+m+"_"+n];
                            transferFrom    = submittedData["transferFrom_"+m+"_"+n];
                            transferTo      = submittedData["transferTo_"+m+"_"+n];
                            transferPrice   = submittedData["transferPrice_"+m+"_"+n];

                            services.push({
                                type    : serviceTypeVal,
                                cars    : transferCarAmount,
                                carType : transferCarType,
                                from    : transferFrom,
                                to      : transferTo,
                                price   : transferPrice
                            });

                            break;
                        case "withDriver" :

                            driverCarType       = submittedData["driverCarType_"+m+"_"+n];
                            driverHours         = submittedData["driverHours_"+m+"_"+n];
                            driverCarsAmount    = submittedData["driverCarsAmount_"+m+"_"+n];
                            driverPrice         = submittedData["driverPrice_"+m+"_"+n];

                            services.push({
                                type    : serviceTypeVal,
                                carType : driverCarType,
                                hours   : driverHours,
                                cars    : driverCarsAmount,
                                price   : driverPrice
                            });

                            break;
                        case "excursion" :

                            goingPlace      = submittedData["goingPlace_"+m+"_"+n];
                            pplAmount       = submittedData["pplAmount_"+m+"_"+n];
                            excursionPrice  = submittedData["excusrionPrice_"+m+"_"+n];

                            services.push({
                                type        : serviceTypeVal,
                                goingPlace  : goingPlace,
                                pplAmonut   : pplAmount,
                                price       : excursionPrice
                            });

                            break;
                        case "food" :

                            restaurant      = submittedData["restaurant_"+m+"_"+n];
                            menu            = submittedData["menuTitle_"+m+"_"+n];
                            foodPrice       = submittedData["foodPrice_"+m+"_"+n];

                            services.push({
                                type        : serviceTypeVal,
                                restaurant  : restaurant,
                                memu        : menu,
                                price       : foodPrice
                            });

                            break;
                    }

                }

            }

            programs.push({
                day         : m,
                city        : submittedData[day],
                services    : services
            });

        }

    }

    // calculations

    var programsCount = programs.length;
    var secondCost = 0;

    for (var p=0; p<programsCount; p++){

        //var days = accommodations[k].moveOut.diff(accommodations[k].moveIn, 'days');

        for (var o=0; o<programs[p].services.length; o++) {

            secondCost += parseInt(programs[p].services[o].price);

        }

    }

    fullCost += secondCost;

    var trip = {
        documentFor     : req.body.documentFor,
        tripStarts      : req.body.tripStarts,
        tripEnds        : req.body.tripEnds,
        totalGuests     : req.body.guestsCount,
        accommodation   : accommodations,
        program         : programs,
        price           : fullCost
    };

    console.log(trip);

    res.render('checkout', {
        trip: trip
    });
});

module.exports = router;
<commit_msg>send json only for now<commit_after>var express = require('express');
var router = express.Router();

var moment = require('moment');

var cars = require('../data/cars');
var cities = require('../data/cities');
var hotels = require('../data/hotelPrises');
var rooms = require('../data/rooms');

var parseData = require('../lib/parseData');

var H = require('../models/hotel');

var async = require('async');

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

    res.render('index', {
        cars    : cars,
        cities  : cities,
        hotels  : hotels,
        rooms   : rooms
    });

});

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

    res.render('test', {
        hotels: hotels,
        cities: cities,
        rooms : rooms
    });

});

router.get('/api/hotels/', function (req, res) {

    H.find({}, function (err, hotels) {
        if (err) throw  err;

        res.json(hotels);
    })

});

router.post('/test', function (req ,res) {

    //console.log(req.body);

    res.json(req.body);

});

router.post('/', function (req, res) {

    console.log("Processing data..");

    var submittedData = req.body;

    var acc = {
        daysTotal: 0,
        accommodations : [
            {
                accommodationId : 0,
                city            : "",
                hotel           : "",
                moveIn          : "",
                moveout         : "",
                rooms   : [
                    {
                        roomId      : 0,
                        roomType    : "",
                        roomsAmount : 0,
                        roomPrice   : 0
                    }
                ]
            }
        ]
    };

    var accommodations = [];

    for (var i=0; i<=10; i++) {

        //accommodation

        var city = "accommodation_city_" + i;

        if (submittedData.hasOwnProperty(city)) {

            var hotel = "accommodation_hotel_" + i;
            var moveIn = "accommodation_moveIn_" + i;
            var moveOut = "accommodation_moveOut_" + i;

            var cityVal = "";
            var hotelVal = "";
            var moveInVal = "";
            var moveOutVal = "";

            var rooms = [];

            cityVal = submittedData[city];

            if (submittedData.hasOwnProperty(hotel)) {
                hotelVal = submittedData[hotel];
            }

            if (submittedData.hasOwnProperty(moveIn)) {
                moveInVal = moment(submittedData[moveIn], "DD-MM-YYYY");
            }

            if (submittedData.hasOwnProperty(moveOut)) {
                moveOutVal = moment(submittedData[moveOut], "DD-MM-YYYY");
            }

            for (var j=0; j<=50; j++) {

                var roomType    = "room_roomType_"+i+"_"+j;

                if (submittedData.hasOwnProperty(roomType)) {

                    var roomAmount  = "room_roomAmount_"+i+"_"+j;
                    var roomPrice   = "room_roomPrice_"+i+"_"+j;

                    var roomTypeVal     = "";
                    var roomAmountVal   = 0;
                    var roomPriceVal    = 0;

                    roomTypeVal     = submittedData[roomType];
                    roomAmountVal   = submittedData[roomAmount];
                    roomPriceVal    = submittedData[roomPrice];

                    //if (submittedData.hasOwnProperty[roomAmount]) {
                    //    roomAmountVal = submittedData[roomAmount];
                    //}
                    //
                    //if (submittedData.hasOwnProperty[roomPrice]) {
                    //    roomPriceVal = submittedData[roomPrice];
                    //}

                    rooms.push({
                        roomId      : j,
                        roomType    : roomTypeVal,
                        roomAmount  : roomAmountVal,
                        roomPrice   : roomPriceVal

                    });

                }

            }

            accommodations.push({
                accommodationId : i,
                city            : cityVal,
                hotel           : hotelVal,
                moveIn          : moveInVal,
                moveOut         : moveOutVal,
                rooms           : rooms
            });
        }
    }

    //calculation
    var accommodationsCount = accommodations.length;
    var fullCost            = 0;

    for (var k=0; k<accommodationsCount; k++){

        var days = accommodations[k].moveOut.diff(accommodations[k].moveIn, 'days');

        for (var l=0; l<accommodations[k].rooms.length; l++) {

            fullCost += parseInt(accommodations[k].rooms[l].roomPrice) * parseInt(accommodations[k].rooms[l].roomAmount) * days;

        }

    }

    var program = [
        {
            day  : 0,
            city : "",
            services: [
                {
                    type        : "",
                    // driver & transfer
                    carType     : "",
                    from        : "",
                    to          : "",
                    //rest
                    restaurant  : "",
                    menu        : "",
                    //excursion
                    goingPlace  : "",
                    pplAmount   : "",

                    price       : 0
                }
            ]
        }
    ];

    var programs = [];
    var services = [];

    for (var m=0; m<=10; m++) {

        var day = "day_city_" + m;

        if (submittedData.hasOwnProperty(day)) {

            for (var n=0; n<=50; n++) {

                var serviceType = "service_serviceType_"+m+"_"+n;

                if (submittedData.hasOwnProperty(serviceType)) {

                    var serviceTypeVal = submittedData[serviceType];

                    //transfer
                    var transferCarType   = "";
                    var transferCarAmount = 0;
                    var transferFrom      = "";
                    var transferTo        = "";
                    var transferPrice     = 0;

                    //driver
                    var driverCarType    = "";
                    var driverHours      = "";
                    var driverCarsAmount = 0;
                    var driverPrice      = 0;

                    //excursion
                    var goingPlace      = "";
                    var pplAmount       = "";
                    var excursionPrice  = 0;

                    //food
                    var restaurant      = "";
                    var menu            = "";
                    var foodPrice       = "";

                    switch (serviceTypeVal) {
                        case "transfer" :

                            transferCarType = submittedData["transferCarType_"+m+"_"+n];
                            transferCarAmount = submittedData["transferCarAmount_"+m+"_"+n];
                            transferFrom    = submittedData["transferFrom_"+m+"_"+n];
                            transferTo      = submittedData["transferTo_"+m+"_"+n];
                            transferPrice   = submittedData["transferPrice_"+m+"_"+n];

                            services.push({
                                type    : serviceTypeVal,
                                cars    : transferCarAmount,
                                carType : transferCarType,
                                from    : transferFrom,
                                to      : transferTo,
                                price   : transferPrice
                            });

                            break;
                        case "withDriver" :

                            driverCarType       = submittedData["driverCarType_"+m+"_"+n];
                            driverHours         = submittedData["driverHours_"+m+"_"+n];
                            driverCarsAmount    = submittedData["driverCarsAmount_"+m+"_"+n];
                            driverPrice         = submittedData["driverPrice_"+m+"_"+n];

                            services.push({
                                type    : serviceTypeVal,
                                carType : driverCarType,
                                hours   : driverHours,
                                cars    : driverCarsAmount,
                                price   : driverPrice
                            });

                            break;
                        case "excursion" :

                            goingPlace      = submittedData["goingPlace_"+m+"_"+n];
                            pplAmount       = submittedData["pplAmount_"+m+"_"+n];
                            excursionPrice  = submittedData["excusrionPrice_"+m+"_"+n];

                            services.push({
                                type        : serviceTypeVal,
                                goingPlace  : goingPlace,
                                pplAmonut   : pplAmount,
                                price       : excursionPrice
                            });

                            break;
                        case "food" :

                            restaurant      = submittedData["restaurant_"+m+"_"+n];
                            menu            = submittedData["menuTitle_"+m+"_"+n];
                            foodPrice       = submittedData["foodPrice_"+m+"_"+n];

                            services.push({
                                type        : serviceTypeVal,
                                restaurant  : restaurant,
                                memu        : menu,
                                price       : foodPrice
                            });

                            break;
                    }

                }

            }

            programs.push({
                day         : m,
                city        : submittedData[day],
                services    : services
            });

        }

    }

    // calculations

    var programsCount = programs.length;
    var secondCost = 0;

    for (var p=0; p<programsCount; p++){

        //var days = accommodations[k].moveOut.diff(accommodations[k].moveIn, 'days');

        for (var o=0; o<programs[p].services.length; o++) {

            secondCost += parseInt(programs[p].services[o].price);

        }

    }

    fullCost += secondCost;

    var trip = {
        documentFor     : req.body.documentFor,
        tripStarts      : req.body.tripStarts,
        tripEnds        : req.body.tripEnds,
        totalGuests     : req.body.guestsCount,
        accommodation   : accommodations,
        program         : programs,
        price           : fullCost
    };

    console.log(trip);

    res.render('checkout', {
        trip: trip
    });
});

module.exports = router;
<|endoftext|>


<commit_before>var http = require('http')
var fs = require('fs')
var path = require('path')
var extend = require('std/extend')
var isObject = require('std/isObject')
var getDependencyList = require('./lib/getDependencyList')
var getRequireStatements = require('./lib/getRequireStatements')
var getCode = require('./lib/getCode')
var resolve = require('./lib/resolve')

module.exports = {
	listen: listen,
	mount: mount,
	connect: connect,
	isRequireRequest: isRequireRequest,
	handleRequest: handleRequest
}

function listen(portOrOpts) {
	var _opts = (isObject(portOrOpts) ? portOrOpts : { port:portOrOpts || 1234 })
	opts.handleAllRequests = true
	mount(http.createServer(), _opts).listen(opts.port, opts.host)
}

function mount(server, _opts) {
	setOpts(_opts)
	return server.on('request', _checkRequest)
}

function connect(opts) {
	setOpts(opts)
	return _checkRequest
}

function _checkRequest(req, res, next) {
	if (isRequireRequest(req) || opts.handleAllRequests) {
		handleRequest(req, res)
	} else {
		next && next()
	}
}

function isRequireRequest(req) {
	return req.url.substr(1, opts.root.length) == opts.root
}

/* options
 *********/
var opts = {
	path: process.cwd(),
	root: 'require',
	port: null,
	host: null
}

function setOpts(_opts) {
	opts = extend(_opts, opts)
}

/* request handlers
 ******************/
function handleRequest(req, res) {
	var reqPath = _normalizeURL(req.url).substr(opts.root.length + 2)
	if (reqPath.match(/\.js$/)) {
		_handleModuleRequest(reqPath, res)
	} else {
		_handleMainModuleRequest(reqPath, req, res)
	}

	function _normalizeURL(url) {
		return url.replace(/\?.*/g, '').replace(/\/js$/, '.js')
	}
}

function _handleMainModuleRequest(reqPath, req, res) {
	var modulePath = resolve.path('./' + reqPath, opts.path)
	if (!modulePath) { return _sendError(res, 'Could not find module "'+reqPath+'" from "'+opts.path+'"') }

	try { var deps = getDependencyList(modulePath) }
	catch(err) { return _sendError(res, 'in getDependencyList: ' + err) }

	var response = ['__require__ = {}', 'require=function(){}']

	var userAgent = req.headers['user-agent']
	var isMobile = userAgent.match('iPad') || userAgent.match('iPod') || userAgent.match('iPhone') || userAgent.match('Android')
	var isPhantom = userAgent.match(/PhantomJS/)

	if (isMobile) {
		// mobile clients take too long per js file request. Inline all the JS into a single request
		each(deps, function(dependency) {
			response.push(_getModuleCode(res, dependency) + "\n")
		})
	} else {
		response.push(
			'__require__.__scripts = []',
			'__require__.__loadNext = function() {',
			'	var src = __require__.__scripts.shift()',
			'	var url = location.protocol+"//"+location.host + src',
			'	if (!src) { return }',
			isPhantom ? '	setTimeout(function() {' : '',
			'		document.getElementsByTagName("head")[0].appendChild(document.createElement("script")).src = url',
			isPhantom ? '	}, 20)' : '',
		'}')

		each(deps, function(dependency) {
			var src = _getBase() + '/' + dependency
			response.push('__require__.__scripts.push("'+src+'")')
		})

		response.push('__require__.__loadNext()')
	}

	var buf = new Buffer(response.join('\n'), encoding='utf8')
	res.writeHead(200, { 'Cache-Control':'no-cache', 'Expires':'Fri, 31 Dec 1998 12:00:00 GMT', 'Content-Length':buf.length, 'Content-Type':'text/javascript' })
	res.end(buf)
}

function _handleModuleRequest(reqPath, res) {
	try { var code = _getModuleCode(res, reqPath) }
	catch(err) { return _sendError(res, err.stack || err) }

	code += '\n__require__.__loadNext()'

	var buf = new Buffer(code, encoding='utf8')
	res.writeHead(200, { 'Cache-Control':'no-cache', 'Expires':'Fri, 31 Dec 1998 12:00:00 GMT', 'Content-Length':buf.length, 'Content-Type':'text/javascript' })
	res.end(buf)
}

function _getModuleCode(res, reqPath) {
	var _closureStart = ';(function() {'
	var _moduleDef = 'var module = {exports:{}}; var exports = module.exports;'
	var _closureEnd = '})()'

	var code = getCode(reqPath)
	var requireStatements = getRequireStatements(code)

	try {
		each(requireStatements, function(requireStmnt) {
			var depPath = resolve.requireStatement(requireStmnt, reqPath)
			if (!depPath) { throw 'Could not resolve module' }
			code = code.replace(requireStmnt, '__require__["'+depPath+'"]')
		})
	} catch(e) {
		_sendError(res, e.message || e)
	}

	return _closureStart
		+ _moduleDef
		+ code // all on the first line
		+ '\n__require__["'+reqPath+'"]=module.exports '+ _closureEnd
}

/* util
 ******/
function _sendError(res, msg) {
	if (msg) { msg = msg.replace(/\n/g, '\\n').replace(/"/g, '\\"') }
	res.writeHead(200)
	res.end('alert("error: ' + msg + '")')
}

function _getBase() {
	var host = opts.host
	var port = (!opts.usePagePort && opts.port)

	if (host && port) {
		return '//' + host + ':' + port + '/' + opts.root
	} else {
		return '/' + opts.root
	}
}
<commit_msg>don't leak global variable 'encoding'<commit_after>var http = require('http')
var fs = require('fs')
var path = require('path')
var extend = require('std/extend')
var isObject = require('std/isObject')
var getDependencyList = require('./lib/getDependencyList')
var getRequireStatements = require('./lib/getRequireStatements')
var getCode = require('./lib/getCode')
var resolve = require('./lib/resolve')

module.exports = {
	listen: listen,
	mount: mount,
	connect: connect,
	isRequireRequest: isRequireRequest,
	handleRequest: handleRequest
}

function listen(portOrOpts) {
	var _opts = (isObject(portOrOpts) ? portOrOpts : { port:portOrOpts || 1234 })
	opts.handleAllRequests = true
	mount(http.createServer(), _opts).listen(opts.port, opts.host)
}

function mount(server, _opts) {
	setOpts(_opts)
	return server.on('request', _checkRequest)
}

function connect(opts) {
	setOpts(opts)
	return _checkRequest
}

function _checkRequest(req, res, next) {
	if (isRequireRequest(req) || opts.handleAllRequests) {
		handleRequest(req, res)
	} else {
		next && next()
	}
}

function isRequireRequest(req) {
	return req.url.substr(1, opts.root.length) == opts.root
}

/* options
 *********/
var opts = {
	path: process.cwd(),
	root: 'require',
	port: null,
	host: null
}

function setOpts(_opts) {
	opts = extend(_opts, opts)
}

/* request handlers
 ******************/
function handleRequest(req, res) {
	var reqPath = _normalizeURL(req.url).substr(opts.root.length + 2)
	if (reqPath.match(/\.js$/)) {
		_handleModuleRequest(reqPath, res)
	} else {
		_handleMainModuleRequest(reqPath, req, res)
	}

	function _normalizeURL(url) {
		return url.replace(/\?.*/g, '').replace(/\/js$/, '.js')
	}
}

function _handleMainModuleRequest(reqPath, req, res) {
	var modulePath = resolve.path('./' + reqPath, opts.path)
	if (!modulePath) { return _sendError(res, 'Could not find module "'+reqPath+'" from "'+opts.path+'"') }

	try { var deps = getDependencyList(modulePath) }
	catch(err) { return _sendError(res, 'in getDependencyList: ' + err) }

	var response = ['__require__ = {}', 'require=function(){}']

	var userAgent = req.headers['user-agent']
	var isMobile = userAgent.match('iPad') || userAgent.match('iPod') || userAgent.match('iPhone') || userAgent.match('Android')
	var isPhantom = userAgent.match(/PhantomJS/)

	if (isMobile) {
		// mobile clients take too long per js file request. Inline all the JS into a single request
		each(deps, function(dependency) {
			response.push(_getModuleCode(res, dependency) + "\n")
		})
	} else {
		response.push(
			'__require__.__scripts = []',
			'__require__.__loadNext = function() {',
			'	var src = __require__.__scripts.shift()',
			'	var url = location.protocol+"//"+location.host + src',
			'	if (!src) { return }',
			isPhantom ? '	setTimeout(function() {' : '',
			'		document.getElementsByTagName("head")[0].appendChild(document.createElement("script")).src = url',
			isPhantom ? '	}, 20)' : '',
		'}')

		each(deps, function(dependency) {
			var src = _getBase() + '/' + dependency
			response.push('__require__.__scripts.push("'+src+'")')
		})

		response.push('__require__.__loadNext()')
	}

	var buf = new Buffer(response.join('\n'))
	res.writeHead(200, { 'Cache-Control':'no-cache', 'Expires':'Fri, 31 Dec 1998 12:00:00 GMT', 'Content-Length':buf.length, 'Content-Type':'text/javascript' })
	res.end(buf)
}

function _handleModuleRequest(reqPath, res) {
	try { var code = _getModuleCode(res, reqPath) }
	catch(err) { return _sendError(res, err.stack || err) }

	code += '\n__require__.__loadNext()'

	var buf = new Buffer(code)
	res.writeHead(200, { 'Cache-Control':'no-cache', 'Expires':'Fri, 31 Dec 1998 12:00:00 GMT', 'Content-Length':buf.length, 'Content-Type':'text/javascript' })
	res.end(buf)
}

function _getModuleCode(res, reqPath) {
	var _closureStart = ';(function() {'
	var _moduleDef = 'var module = {exports:{}}; var exports = module.exports;'
	var _closureEnd = '})()'

	var code = getCode(reqPath)
	var requireStatements = getRequireStatements(code)

	try {
		each(requireStatements, function(requireStmnt) {
			var depPath = resolve.requireStatement(requireStmnt, reqPath)
			if (!depPath) { throw 'Could not resolve module' }
			code = code.replace(requireStmnt, '__require__["'+depPath+'"]')
		})
	} catch(e) {
		_sendError(res, e.message || e)
	}

	return _closureStart
		+ _moduleDef
		+ code // all on the first line
		+ '\n__require__["'+reqPath+'"]=module.exports '+ _closureEnd
}

/* util
 ******/
function _sendError(res, msg) {
	if (msg) { msg = msg.replace(/\n/g, '\\n').replace(/"/g, '\\"') }
	res.writeHead(200)
	res.end('alert("error: ' + msg + '")')
}

function _getBase() {
	var host = opts.host
	var port = (!opts.usePagePort && opts.port)

	if (host && port) {
		return '//' + host + ':' + port + '/' + opts.root
	} else {
		return '/' + opts.root
	}
}
<|endoftext|>


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

var Config = require('../config');
var nodegit = require('nodegit');

/**
 * Gets the status of a repository
 */
router.get('/status/:repoName', function(req, res, next) {
    var repo = Config.reposByName[req.params.repoName];
    var repoPath = repo.path;

    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            return repo.getStatus().then(function(statuses) {
                function statusToText(status) {
                    var words = [];
                    if (status.isNew()) { words.push("NEW"); }
                    if (status.isModified()) { words.push("MODIFIED"); }
                    if (status.isTypechange()) { words.push("TYPECHANGE"); }
                    if (status.isRenamed()) { words.push("RENAMED"); }
                    if (status.isIgnored()) { words.push("IGNORED"); }
                    if (status.isConflicted()) { words.push("CONFLICT"); }

                    return words.join(" ");
                }

                var files = [];
                statuses.forEach(function(file) {
                    files.push(file.path() + " " + statusToText(file));
                });

                res.status(200).json({files: files});
            });
        }).catch(function (error) {
            res.status(500).json({error: error});
            throw error;
        });
});

/**
 * GET a list of all repositories
 */
router.get('/', function(req, res, next) {
    res.json(Config.repos.map(function(repo) {
        return {name: repo.name};
    }));
});

/**
 * Performs a repository pull for the given repo
 */
router.post('/pull/:repoName', function(req, res, next) {
    var repoConfig = Config.reposByName[req.params.repoName];
    var repoPath = repoConfig.path;

    // Open a repository that needs to be fetched and fast-forwarded
    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            repository = repo;

            return repository.fetchAll({
                callbacks: {
                    credentials: function(url) {
                        return nodegit.Cred.userpassPlaintextNew(repoConfig.username, repoConfig.password);
                    },
                    certificateCheck: function() {
                        return 1;
                    }
                }
            });

        })

        // Now that we're finished fetching, go ahead and merge our local branch
        // with the new one
        .then(function() {
            return repository.mergeBranches("master", "origin/master");
        })

        .done(function(oid) {
            var status = {oid: oid};
            res.status(200).json(status);
        }, function (error) {
            var status = {message: error.message};
            res.status(500).json(status);
            throw error;
        });
});

/**
 * Performs a repository commit and push for the given repo
 */
router.post('/commit/:repoName', function(req, res, next) {
    var repoConfig = Config.reposByName[req.params.repoName];
    var repoPath = repoConfig.path;

    var sig = nodegit.Signature.now(repoConfig.fullname, repoConfig.email);
    var index;
    var oid;
    var files = [];

    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            return repo.openIndex()
                .then(function (idx) {
                    index = idx;
                    return repo.getStatus();
                })
                .then(function (statuses) {
                    statuses.forEach(function(file) {
                        files.push(file.path());
                    });

                    return index.addAll(files);
                })
                .then(function () {
                    return index.write();
                })
                .then(function () {
                    return index.writeTree();
                })
                .then(function(oidResult) {
                    oid = oidResult;
                    return nodegit.Reference.nameToId(repo, "HEAD");
                })
                .then(function(head) {
                    return repo.getCommit(head);
                })
                .then(function(parent) {
                    return repo.createCommit("HEAD", sig, sig, "automated commit", oid, [parent]);
                })
                .then(function() {
                    return repo.getRemote("origin");
                })
                .then(function(remote) {
                    return remote.push(["refs/heads/master:refs/heads/master"],
                    {
                        callbacks: {
                            credentials: function(url) {
                                return nodegit.Cred.userpassPlaintextNew(repoConfig.username, repoConfig.password);
                            },

                            certificateCheck: function() {
                                return 1;
                            }
                        }
                    });
                })

        })
        .done(function () {
            res.status(200).json({status: "ok"});
        }, function (error) {
            res.status(500).json({message: error.message});
            throw error;
        })
});

/**
 * Reverts all local uncommitted changes
 */
router.post('/revert/:repoName', function(req, res, next) {
    var repo = Config.reposByName[req.params.repoName];
    var repoPath = repo.path;

    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            var checkoutOpts = {
                checkoutStrategy: nodegit.Checkout.STRATEGY.FORCE
            };

            return repo.checkoutBranch("master", checkoutOpts);
        })
        .done(function () {
            res.status(200).json({status: "ok"});
        }, function (error) {
            res.status(500).json({message: error.message});
            throw error;
        })
});

module.exports = router;
<commit_msg>openIndex() becomes index()<commit_after>var express = require('express');
var router = express.Router();

var Config = require('../config');
var nodegit = require('nodegit');

/**
 * Gets the status of a repository
 */
router.get('/status/:repoName', function(req, res, next) {
    var repo = Config.reposByName[req.params.repoName];
    var repoPath = repo.path;

    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            return repo.getStatus().then(function(statuses) {
                function statusToText(status) {
                    var words = [];
                    if (status.isNew()) { words.push("NEW"); }
                    if (status.isModified()) { words.push("MODIFIED"); }
                    if (status.isTypechange()) { words.push("TYPECHANGE"); }
                    if (status.isRenamed()) { words.push("RENAMED"); }
                    if (status.isIgnored()) { words.push("IGNORED"); }
                    if (status.isConflicted()) { words.push("CONFLICT"); }

                    return words.join(" ");
                }

                var files = [];
                statuses.forEach(function(file) {
                    files.push(file.path() + " " + statusToText(file));
                });

                res.status(200).json({files: files});
            });
        }).catch(function (error) {
            res.status(500).json({error: error});
            throw error;
        });
});

/**
 * GET a list of all repositories
 */
router.get('/', function(req, res, next) {
    res.json(Config.repos.map(function(repo) {
        return {name: repo.name};
    }));
});

/**
 * Performs a repository pull for the given repo
 */
router.post('/pull/:repoName', function(req, res, next) {
    var repoConfig = Config.reposByName[req.params.repoName];
    var repoPath = repoConfig.path;

    // Open a repository that needs to be fetched and fast-forwarded
    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            repository = repo;

            return repository.fetchAll({
                callbacks: {
                    credentials: function(url) {
                        return nodegit.Cred.userpassPlaintextNew(repoConfig.username, repoConfig.password);
                    },
                    certificateCheck: function() {
                        return 1;
                    }
                }
            });

        })

        // Now that we're finished fetching, go ahead and merge our local branch
        // with the new one
        .then(function() {
            return repository.mergeBranches("master", "origin/master");
        })

        .done(function(oid) {
            var status = {oid: oid};
            res.status(200).json(status);
        }, function (error) {
            var status = {message: error.message};
            res.status(500).json(status);
            throw error;
        });
});

/**
 * Performs a repository commit and push for the given repo
 */
router.post('/commit/:repoName', function(req, res, next) {
    var repoConfig = Config.reposByName[req.params.repoName];
    var repoPath = repoConfig.path;

    var sig = nodegit.Signature.now(repoConfig.fullname, repoConfig.email);
    var index;
    var oid;
    var files = [];

    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            return repo.index()
                .then(function (idx) {
                    index = idx;
                    return repo.getStatus();
                })
                .then(function (statuses) {
                    statuses.forEach(function(file) {
                        files.push(file.path());
                    });

                    return index.addAll(files);
                })
                .then(function () {
                    return index.write();
                })
                .then(function () {
                    return index.writeTree();
                })
                .then(function(oidResult) {
                    oid = oidResult;
                    return nodegit.Reference.nameToId(repo, "HEAD");
                })
                .then(function(head) {
                    return repo.getCommit(head);
                })
                .then(function(parent) {
                    return repo.createCommit("HEAD", sig, sig, "automated commit", oid, [parent]);
                })
                .then(function() {
                    return repo.getRemote("origin");
                })
                .then(function(remote) {
                    return remote.push(["refs/heads/master:refs/heads/master"],
                    {
                        callbacks: {
                            credentials: function(url) {
                                return nodegit.Cred.userpassPlaintextNew(repoConfig.username, repoConfig.password);
                            },

                            certificateCheck: function() {
                                return 1;
                            }
                        }
                    });
                })

        })
        .done(function () {
            res.status(200).json({status: "ok"});
        }, function (error) {
            res.status(500).json({message: error.message});
            throw error;
        })
});

/**
 * Reverts all local uncommitted changes
 */
router.post('/revert/:repoName', function(req, res, next) {
    var repo = Config.reposByName[req.params.repoName];
    var repoPath = repo.path;

    nodegit.Repository.open(repoPath)
        .then(function(repo) {
            var checkoutOpts = {
                checkoutStrategy: nodegit.Checkout.STRATEGY.FORCE
            };

            return repo.checkoutBranch("master", checkoutOpts);
        })
        .done(function () {
            res.status(200).json({status: "ok"});
        }, function (error) {
            res.status(500).json({message: error.message});
            throw error;
        })
});

module.exports = router;
<|endoftext|>


<commit_before>/*
Deprecated. Any remaining usage of these functions needs to be replaced
with calls to the new API endpoints.
*/

var _ = require('lodash');
var async = require('async');

module.exports = function (req, res) {

	var keystone = req.keystone;

	var sendResponse = function (status) {
		res.json(status);
	};

	var sendError = function (key, err, msg) {
		msg = msg || 'API Error';
		key = key || 'unknown error';
		msg += ' (' + key + ')';
		console.log(msg + (err ? ':' : ''));
		if (err) {
			console.log(err);
		}
		res.status(500);
		sendResponse({ error: key || 'error', detail: err ? err.message : '' });
	};

	switch (req.params.action) {

		case 'autocomplete':
			var limit = req.query.limit || 50;
			var page = req.query.page || 1;
			var skip = limit * (page - 1);
			var filters = req.list.getSearchFilters(req.query.q);
			var count = req.list.model.count(filters);
			var query = req.list.model.find(filters)
				.limit(limit)
				.skip(skip)
				.sort(req.list.defaultSort);
			if (req.query.context === 'relationship') {
				var srcList = keystone.list(req.query.list);
				if (!srcList) return sendError('invalid list provided');

				var field = srcList.fields[req.query.field];
				if (!field) return sendError('invalid field provided');

				_.forEach(req.query.filters, function (value, key) {
					query.where(key).equals(value ? value : null);
					count.where(key).equals(value ? value : null);
				});
			}
			count.exec(function (err, total) {
				if (err) return sendError('database error', err);
				query.exec(function (err, items) {
					if (err) return sendError('database error', err);
					sendResponse({
						total: total,
						items: items.map(function (i) {
							return {
								name: req.list.getDocumentName(i, false) || '(' + i.id + ')',
								id: i.id,
							};
						}),
					});
				});
			});
			break;

		case 'order':
			if (!keystone.security.csrf.validate(req)) {
				return sendError('invalid csrf');
			}
			var order = req.query.order || req.body.order;
			var queue = [];
			if (typeof order === 'string') {
				order = order.split(',');
			}
			_.forEach(order, function (id, i) {
				queue.push(function (done) {
					req.list.model.update({ _id: id }, { $set: { sortOrder: i } }, done);
				});
			});
			async.parallel(queue, function (err) {
				if (err) return sendError('database error', err);
				return sendResponse({
					success: true,
				});
			});
			break;

	}

};
<commit_msg>Removing unused api/list route<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {

	//snapping
$('body').panelSnap();

$(".carousel-caption").animate({
        marginLeft: "+=9999px",
    }, 1000 );

	//scroling menu
var sections = $('section')
  , nav = $('nav')
  , nav_height = 100;
 //nav.outerHeight()

$(window).on('scroll', function () {
  var cur_pos = $(this).scrollTop();
  sections.each(function() {

    var top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();
    if (cur_pos >= top && cur_pos <= bottom) {

      sections.removeClass('active');
      $(this).addClass('active');

	  nav.find('a').parent().removeClass('active');
      nav.find('a[href="#'+$(this).attr('id')+'"]').parent().addClass('active');

	  scolor = rgb2hex($(this).css("background-color"));
	  iscolor = getContrast50(scolor);
	  console.log(scolor);
	  console.log(iscolor);
	  nav.find('a').css("color":iscolor);
    }
  });
});
			//menu_click_scroling
	nav.find('a').on("click", function(){
		event.preventDefault();
		id = $(this).attr("href");
		scrollToID(id, 800);
	});

});

function scrollToID(id, speed){
	var targetOffset = $(id).offset().top;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	//return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function invertColor(hexTripletColor) {
    var color = hexTripletColor;
    color = color.substring(1);           // remove #
    color = parseInt(color, 16);          // convert to integer
    color = 0xFFFFFF ^ color;             // invert three bytes
    color = color.toString(16);           // convert to hex
    color = ("000000" + color).slice(-6); // pad with leading zeros
    color = "#" + color;                  // prepend #
    return color;
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}<commit_msg>iscolor<commit_after>$(document).ready(function() {

	//snapping
$('body').panelSnap();

$(".carousel-caption").animate({
        marginLeft: "+=9999px",
    }, 1000 );

	//scroling menu
var sections = $('section')
  , nav = $('nav')
  , nav_height = 100;
 //nav.outerHeight()

$(window).on('scroll', function () {
  var cur_pos = $(this).scrollTop();
  sections.each(function() {

    var top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();
    if (cur_pos >= top && cur_pos <= bottom) {

      sections.removeClass('active');
      $(this).addClass('active');

	  nav.find('a').parent().removeClass('active');
      nav.find('a[href="#'+$(this).attr('id')+'"]').parent().addClass('active');

	  scolor = rgb2hex($(this).css("background-color"));
	  iscolor = getContrast50(scolor);
	  console.log(scolor);
	  console.log(iscolor);
	  nav.find('a').css("color",iscolor);
    }
  });
});
			//menu_click_scroling
	nav.find('a').on("click", function(){
		event.preventDefault();
		id = $(this).attr("href");
		scrollToID(id, 800);
	});

});

function scrollToID(id, speed){
	var targetOffset = $(id).offset().top;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
	//return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function invertColor(hexTripletColor) {
    var color = hexTripletColor;
    color = color.substring(1);           // remove #
    color = parseInt(color, 16);          // convert to integer
    color = 0xFFFFFF ^ color;             // invert three bytes
    color = color.toString(16);           // convert to hex
    color = ("000000" + color).slice(-6); // pad with leading zeros
    color = "#" + color;                  // prepend #
    return color;
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}<|endoftext|>


<commit_before>'use strict';

var ms = require('ms');
var mongojs = require('mongojs');
var raven = require('raven');
var readPipermail = require('./lib/read-pipermail.js');
var bot = require('./index.js');

if (!process.env.PIPERMAIL_SOURCE) {
  throw new Error('You must specify the "PIPERMAIL_SOURCE" environment variable');
}
if (!process.env.PIPERMAIL_DATABASE) {
  throw new Error('You must specify the "PIPERMAIL_DATABASE" environment variable');
}

var src = process.env.PIPERMAIL_SOURCE;
var db = mongojs(process.env.PIPERMAIL_DATABASE, ['log', 'headers', 'contents', 'topics']);

var settings = 'last-reboot:  ' + (new Date()).toISOString() + '\n' +
               'source:       ' + src + '\n' +
               'database:     ' + process.env.PIPERMAIL_DATABASE.replace(/^.*@/,'')
var lastRun = 'no old runs to display'
var lastStart = 'never started'
var lastEnd = 'never finished'

var ravenClient = process.env.PIPERMAIL_RAVEN ?
    new raven.Client(process.env.PIPERMAIL_RAVEN) :
    null;
if (ravenClient) {
  ravenClient.patchGlobal(function (logged, err) {
    console.error(err.stack || err);
    process.exit(1);
  });
}
function onError(err) {
  console.error(err.stack || err.message || err);
  if (ravenClient) {
    if (typeof err === 'string') {
      ravenClient.captureMessage(err);
    } else {
      ravenClient.captureError(err);
    }
  }
}

function run() {
  lastStart = (new Date()).toISOString();
  var defaultMonths = process.env.PIPERMAIL_MONTHS || ((new Date()).getDate() < 5 ? 2 : 1);
  var parallel = process.env.PIPERMAIL_PARALLEL || 1
  return bot({
    source: src,
    db: db,
    months: +defaultMonths,
    parallel: +parallel,
    onError: onError
  }).then(function () {
    lastEnd = (new Date()).toISOString()
    if (db) {
      db.log.insert({
        type: 'bot-run',
        start: new Date(lastStart),
        end: new Date(lastEnd)
      }, {safe: true}, function (err) {
        if (err) {
          onError(err)
        }
      })
    }
  });
}
maintain()
function maintain() {
  run().done(function () {
    if (lastEnd != 'never finished') {
      lastRun = ms(new Date(lastEnd).getTime() - new Date(lastStart).getTime());
    }
    setTimeout(maintain, ms('60s'));
  }, function (err) {
    onError(err);
    setTimeout(maintain, ms('60s'));
  })
}

var http = require('http')

http.createServer(function (req, res) {
  var status = 200;
  if (lastEnd === 'never finished') {
    status = 503
  } else if (Date.now() - (new Date(lastEnd)).getTime() > ms('20 minutes')) {
    status = 503
    onError('Timeout triggering restart');
    setTimeout(function () {
      // allow time for the error to be logged
      process.exit(1);
    }, 500);
  }
  res.writeHead(status, {'Content-Type': 'text/plain'})
  var warning = status === 503 ? 'WARNING: server behind on processing\n\n' : ''
  var currentRun = lastStart > lastEnd ? ms(Date.now() - new Date(lastStart).getTime()) : '-'
  res.end(warning + settings + '\n\n' +
          'last-start:   ' + lastStart + '\n' +
          'last-end:     ' + lastEnd + '\n' +
          'pervious-run: ' + lastRun + '\n' +
          'current-run:  ' + currentRun + '\n' +
          'status:       ' + readPipermail.getStatus() + '\n\n' +
          'current-time: ' + (new Date()).toISOString());
}).listen(process.env.PORT || 3000);

console.log('Server running at http://localhost:' + (process.env.PORT || 3000));
<commit_msg>Track runsPerDay<commit_after>'use strict';

var ms = require('ms');
var mongojs = require('mongojs');
var raven = require('raven');
var readPipermail = require('./lib/read-pipermail.js');
var bot = require('./index.js');

if (!process.env.PIPERMAIL_SOURCE) {
  throw new Error('You must specify the "PIPERMAIL_SOURCE" environment variable');
}
if (!process.env.PIPERMAIL_DATABASE) {
  throw new Error('You must specify the "PIPERMAIL_DATABASE" environment variable');
}

var src = process.env.PIPERMAIL_SOURCE;
var db = mongojs(process.env.PIPERMAIL_DATABASE, ['log', 'headers', 'contents', 'topics', 'runsPerDay']);

var settings = 'last-reboot:  ' + (new Date()).toISOString() + '\n' +
               'source:       ' + src + '\n' +
               'database:     ' + process.env.PIPERMAIL_DATABASE.replace(/^.*@/,'')
var lastRun = 'no old runs to display'
var lastStart = 'never started'
var lastEnd = 'never finished'

var ravenClient = process.env.PIPERMAIL_RAVEN ?
    new raven.Client(process.env.PIPERMAIL_RAVEN) :
    null;
if (ravenClient) {
  ravenClient.patchGlobal(function (logged, err) {
    console.error(err.stack || err);
    process.exit(1);
  });
}
function onError(err) {
  console.error(err.stack || err.message || err);
  if (ravenClient) {
    if (typeof err === 'string') {
      ravenClient.captureMessage(err);
    } else {
      ravenClient.captureError(err);
    }
  }
}

function run() {
  lastStart = (new Date()).toISOString();
  var defaultMonths = process.env.PIPERMAIL_MONTHS || ((new Date()).getDate() < 5 ? 2 : 1);
  var parallel = process.env.PIPERMAIL_PARALLEL || 1
  return bot({
    source: src,
    db: db,
    months: +defaultMonths,
    parallel: +parallel,
    onError: onError
  }).then(function () {
    lastEnd = (new Date()).toISOString()
    if (db) {
      db.log.insert({
        type: 'bot-run',
        start: new Date(lastStart),
        end: new Date(lastEnd)
      }, {safe: true}, function (err) {
        if (err) {
          onError(err)
        }
      })
      var now = new Date();
      var day = now.toISOString().split('T')[0];
      db.runsPerDay.update(
        {_id: day},
        {$inc: { runs: 1, totalDuration: (new Date(lastEnd) - new Date(lastStart)) }},
        {upsert: true},
        function (err) {
          if (err) {
            onError(err)
          }
        }
      )
    }
  });
}
maintain()
function maintain() {
  run().done(function () {
    if (lastEnd != 'never finished') {
      lastRun = ms(new Date(lastEnd).getTime() - new Date(lastStart).getTime());
    }
    setTimeout(maintain, ms('60s'));
  }, function (err) {
    onError(err);
    setTimeout(maintain, ms('60s'));
  })
}

var http = require('http')

http.createServer(function (req, res) {
  var status = 200;
  if (lastEnd === 'never finished') {
    status = 503
  } else if (Date.now() - (new Date(lastEnd)).getTime() > ms('20 minutes')) {
    status = 503
    onError('Timeout triggering restart');
    setTimeout(function () {
      // allow time for the error to be logged
      process.exit(1);
    }, 500);
  }
  res.writeHead(status, {'Content-Type': 'text/plain'})
  var warning = status === 503 ? 'WARNING: server behind on processing\n\n' : ''
  var currentRun = lastStart > lastEnd ? ms(Date.now() - new Date(lastStart).getTime()) : '-'
  res.end(warning + settings + '\n\n' +
          'last-start:   ' + lastStart + '\n' +
          'last-end:     ' + lastEnd + '\n' +
          'pervious-run: ' + lastRun + '\n' +
          'current-run:  ' + currentRun + '\n' +
          'status:       ' + readPipermail.getStatus() + '\n\n' +
          'current-time: ' + (new Date()).toISOString());
}).listen(process.env.PORT || 3000);

console.log('Server running at http://localhost:' + (process.env.PORT || 3000));
<|endoftext|>


<commit_before>'use strict';

var archiver   = require('archiver'),
    mediaQuery = require('css-mediaquery'),
    rework     = require('rework'),
    grids      = require('rework-pure-grids'),
    path       = require('path');

var config     = require('../config'),
    hbs        = require('../lib/hbs'),
    utils      = require('../lib/utils'),
    middleware = require('../middleware');

exports.index = [
    normalizeOptions,
    middleware.exposeTemplates('start'),
    generateCSS,
    showStart
];

exports.download = [
    normalizeOptions,
    generateHTML,
    generateCSS,
    downloadStart
];

// -----------------------------------------------------------------------------

var LIMITS = {
    cols        : {min: 2, max: 100},
    prefix      : {min: 0, max: 80},
    mediaQueries: {min: 0, max: 10}
};

var SELECTED_GRIDS_UNITS = {
    med: new GridUnits(config.pure.grid.med),
    lrg: new GridUnits(config.pure.grid.lrg)
};

function GridUnits(mq) {
    utils.extend(this, {mq: mq}, mediaQuery.parse(mq)[0]);
}

GridUnits.prototype.toString = function () {
    return this.mq;
};

function normalizeOptions(req, res, next) {
    var mediaQueries = [],
        cols, prefix;

    function badRequest(label, message) {
        res.locals.message = message;
        throw utils.error(400, 'Bad Request: ' + label);
    }

    Object.keys(req.query).forEach(function (param) {
        var val = req.query[param];

        if (Array.isArray(val)) {
            badRequest('Duplicate param',
                '"' + param + '" must only have a single value.');
        }

        switch (param.toLowerCase()) {
            case 'cols':
                val = parseInt(val, 10);

                if (val < LIMITS.cols.min || val > LIMITS.cols.max) {
                    badRequest('Column range',
                        '"cols" must be between 2—100, inclusively.');
                }

                cols = val;
                break;

            case 'prefix':
                if (val.length > LIMITS.prefix.max) {
                    badRequest('Prefix length',
                        '"prefix" must be between 0—80 characters.');
                }

                prefix = val;
                break;

            // Assume it's a media query.
            default:
                try {
                    val = normalizeMediaQuery(val);
                } catch (e) {
                    badRequest('Media Query',
                        'Invalid CSS Media Query: "' + val + '".');
                }

                mediaQueries.push({
                    id: param,
                    mq: val
                });

                break;
        }
    });

    if (mediaQueries.length > LIMITS.mediaQueries.max) {
        badRequest('Media Query',
            'More than 10 CSS Media Queries were provided.');
    }

    req.startOptions = {
        cols        : cols,
        prefix      : prefix,
        mediaQueries: mediaQueries
    };
    next();
}

function normalizeMediaQuery(mq, options) {
    mq = mq.trim();
    var expand = options && options.expand;

    if (expand) {
        mq = 'screen and (min-width: ' + mq + ')';
    }

    try {
        mediaQuery.parse(mq);
        return mq;
    } catch (e) {
        // When we've already expanded the short-hand MQ syntax, or when the
        // short-hand form doesn't look like a length value, re-throw the error.
        if (expand || !/^(\d|\.)/.test(mq)) {
            throw e;
        }
    }

    // Try again, this time expanding the `mq` assuming it's in the short-hand.
    return normalizeMediaQuery(mq, {expand: true});
}

function generateHTML(req, res, next) {
    var template = path.join(config.dirs.shared, 'start', 'html' + hbs.extname);

    hbs.render(template, {
        cache: req.app.enabled('view cache'),
        pure : config.pure
    }, function (err, html) {
        if (err) { return next(err); }
        res.html = html;
        next();
    });
}

function generateCSS(req, res, next) {
    var options = req.startOptions;

    res.css = rework('').use(grids.units(options.cols, {
        mediaQueries: options.mediaQueries.reduce(function (map, mq) {
            map[mq.id] = mq.mq;
            return map;
        }, {})
    })).toString({indent: '    '});

    next();
}

function showStart(req, res, next) {
    var options = req.startOptions;

    res.locals.selectedUnits = SELECTED_GRIDS_UNITS;
    res.locals.css           = res.css;
    res.locals(options);

    res.expose(LIMITS, 'start.limits');
    res.expose(options, 'start.options');
    res.render('start');
}

function downloadStart(req, res, next) {
    var archive = archiver('zip');

    archive.append(res.html,         {name: 'index.html'});
    archive.append(res.css || '\n',  {name: 'grid.css'});

    res.set('Content-Disposition', 'attachment; filename="pure-start.zip"');
    archive.finalize().pipe(res);
}
<commit_msg>Update start.js route handler<commit_after>'use strict';

var archiver   = require('archiver'),
    mediaQuery = require('css-mediaquery'),
    rework     = require('rework'),
    grids      = require('rework-pure-grids'),
    path       = require('path');

var config     = require('../config'),
    hbs        = require('../lib/hbs'),
    utils      = require('../lib/utils'),
    middleware = require('../middleware');

exports.index = [
    normalizeOptions,
    middleware.exposeTemplates('start'),
    generateCSS,
    showStart
];

exports.download = [
    normalizeOptions,
    generateHTML,
    generateCSS,
    downloadStart
];

// -----------------------------------------------------------------------------

var LIMITS = {
    cols        : {min: 2, max: 100},
    prefix      : {min: 0, max: 20},
    mediaQueries: {min: 0, max: 10}
};

var SELECTED_GRIDS_UNITS = {
    med: new GridUnits(config.pure.grid.med),
    lrg: new GridUnits(config.pure.grid.lrg)
};

function GridUnits(mq) {
    utils.extend(this, {mq: mq}, mediaQuery.parse(mq)[0]);
}

GridUnits.prototype.toString = function () {
    return this.mq;
};

function normalizeOptions(req, res, next) {
    var mediaQueries = [],
        cols, prefix;

    function badRequest(label, message) {
        res.locals.message = message;
        throw utils.error(400, 'Bad Request: ' + label);
    }

    Object.keys(req.query).forEach(function (param) {
        var val = req.query[param];

        if (Array.isArray(val)) {
            badRequest('Duplicate param',
                '"' + param + '" must only have a single value.');
        }

        switch (param.toLowerCase()) {
            case 'cols':
                val = parseInt(val, 10);

                if (val < LIMITS.cols.min || val > LIMITS.cols.max) {
                    badRequest('Column range',
                        '"cols" must be between 2—100, inclusively.');
                }

                //This is for the ?query=&nextQuery= case.
                else if (!val) {
                    cols = 24;
                }
                else {
                    cols = val;
                }
                break;

            case 'prefix':
                if (val.length > LIMITS.prefix.max) {
                    badRequest('Prefix length',
                        '"prefix" must be between 0—80 characters.');
                }

                //This is for the ?query=&nextQuery= case.
                else if (!val) {
                    prefix = '.pure-u-';
                }
                else {
                    prefix = val;
                }
                break;

            // Assume it's a media query.
            default:
                try {
                    val = normalizeMediaQuery(val);
                } catch (e) {
                    badRequest('Media Query',
                        'Invalid CSS Media Query: "' + val + '".');
                }

                mediaQueries.push({
                    id: param,
                    mq: val
                });

                break;
        }
    });

    if (mediaQueries.length > LIMITS.mediaQueries.max) {
        badRequest('Media Query',
            'More than 10 CSS Media Queries were provided.');
    }

    req.startOptions = {
        cols        : cols,
        prefix      : prefix,
        mediaQueries: mediaQueries
    };
    next();
}

function normalizeMediaQuery(mq, options) {
    mq = mq.trim();
    var expand = options && options.expand;

    if (expand) {
        mq = 'screen and (min-width: ' + mq + ')';
    }

    try {
        mediaQuery.parse(mq);
        return mq;
    } catch (e) {
        // When we've already expanded the short-hand MQ syntax, or when the
        // short-hand form doesn't look like a length value, re-throw the error.
        if (expand || !/^(\d|\.)/.test(mq)) {
            throw e;
        }
    }

    // Try again, this time expanding the `mq` assuming it's in the short-hand.
    return normalizeMediaQuery(mq, {expand: true});
}

function generateHTML(req, res, next) {
    var template = path.join(config.dirs.shared, 'start', 'html' + hbs.extname);

    hbs.render(template, {
        cache: req.app.enabled('view cache'),
        pure : config.pure
    }, function (err, html) {
        if (err) { return next(err); }
        res.html = html;
        next();
    });
}

function generateCSS(req, res, next) {
    var options = req.startOptions,
        opts = {};

    opts.mediaQueries = options.mediaQueries.reduce(function (map, mq) {
        map[mq.id] = mq.mq;
        return map;
    }, {});

    if (options.prefix) {
        opts.selectorPrefix = options.prefix;
    }

    res.css = rework('').use(grids.units(options.cols, opts))
                .toString({indent: '    '});

    next();
}

function showStart(req, res, next) {
    var options = req.startOptions;

    res.locals.selectedUnits = SELECTED_GRIDS_UNITS;
    res.locals.css           = res.css;
    res.locals(options);

    res.expose(LIMITS, 'start.limits');
    res.expose(options, 'start.options');
    res.render('start');
}

function downloadStart(req, res, next) {
    var archive = archiver('zip');

    archive.append(res.html,         {name: 'index.html'});
    archive.append(res.css || '\n',  {name: 'grid.css'});

    res.set('Content-Disposition', 'attachment; filename="pure-start.zip"');
    archive.finalize().pipe(res);
}
<|endoftext|>


<commit_before>var express = require('express')
   , app    = express()
   , path   = require('path');

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

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

app.listen(app.get('port'), function () {
	console.log(' 127.0.0.1:'+ app.get('port') + ' Serving statics files in public');
});
<commit_msg>update server<commit_after>var express = require('express'),
	app  	= express(),
	fs 		= require('fs'),
	path	= require('path');

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

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

app.use(function (req, res) {
	var filePath 	= '.' + req.url,
	 	contentType = 'text/html';

	if (filePath == './' || './public/views/index.tpl.html' )
		filePath = './public/views/index.tpl.html';

	fs.readFile(filePath, function(error, content) {
	    if (error) {
	        if(error.code == 'ENOENT'){
	            fs.readFile('./404.html', function(error, content) {
	                res.writeHead(200, { 'Content-Type': contentType });
	                res.end(content, 'utf-8');
	            });
	        }
	        else {
	            res.writeHead(500);
	            res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
	            res.end();
	        }
	    }
	    else {
	        res.writeHead(200, { 'Content-Type': contentType });
	        res.end(content, 'utf-8');
	    }
	});
});

app.listen(app.get('port'), function () {
	console.log(' 127.0.0.1:'+ app.get('port') + ' Serving statics files in public');
});
<|endoftext|>


<commit_before>"use strict";

var util = require("util");

// import the express router
var router = require("express").Router();

// create model
var User = require("../models/model_user");

// on routes that end in /users
router.route("/")

    // create a user (POST /$apiBaseUrl/users)
    .post(function(req, res) {
        // create instance of User model
        var user = new User();

        // check inputs
        req.assert("deviceId", "deviceId must not be empty").notEmpty();
        req.assert("platform", "platform must not be empty").notEmpty();
        req.assert("platformVersion", "platformVersion must not be empty").notEmpty();
        req.assert("appVersion", "appVersion must not be empty").notEmpty();

        // if there are errors, send 400
        var errors = req.validationErrors(true);
        if (errors) {
            res.status(400).send("There have been validation errors: " + util.inspect(errors));
            return;
        }

        var now = new Date();

        // set attributes
        user.deviceId = req.body.deviceId;
        user.platform = req.body.platform;
        user.platformVersion = req.body.platformVersion;
        user.pushToken = req.body.pushToken;
        user.appVersion = req.body.appVersion;
        user.lastSeen = now;

        // create an object from our document
        var upsertData = user.toObject();
        // delete attributes to upsert
        delete upsertData._id;
        delete upsertData.firstSeen;

        // upsert in db
        User.update({ deviceId: user.deviceId }, { $setOnInsert: { firstSeen: now }, $set: upsertData }, { upsert: true }, function(err, user) {
            if (err) { res.send(err); }
            res.status(200).json({ message: "successful!", id: user._id });
            res.end();
        });
    });

    // on routes that end in /users/:userDevId/lectures
    router.route("/:deviceId/lectures")

        // get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
        .get(function(req, res) {
            User.findById(req.params.deviceId, function(err, user) {
                if (err) { res.status(500).send(err); }

                // update users selectedLectures
                User.update({ deviceId: user.deviceId }, { selectedLectures: req.params.selectedLectures }, function(err, user) {
                    if (err) { res.send(err); }
                    res.status(200).json({ message: "successful!", id: user._id });
                });
            });
        });

module.exports = router;
<commit_msg>whoooops! post, not get, sorry....<commit_after>"use strict";

var util = require("util");

// import the express router
var router = require("express").Router();

// create model
var User = require("../models/model_user");

// on routes that end in /users
router.route("/")

    // create a user (POST /$apiBaseUrl/users)
    .post(function(req, res) {
        // create instance of User model
        var user = new User();

        // check inputs
        req.assert("deviceId", "deviceId must not be empty").notEmpty();
        req.assert("platform", "platform must not be empty").notEmpty();
        req.assert("platformVersion", "platformVersion must not be empty").notEmpty();
        req.assert("appVersion", "appVersion must not be empty").notEmpty();

        // if there are errors, send 400
        var errors = req.validationErrors(true);
        if (errors) {
            res.status(400).send("There have been validation errors: " + util.inspect(errors));
            return;
        }

        var now = new Date();

        // set attributes
        user.deviceId = req.body.deviceId;
        user.platform = req.body.platform;
        user.platformVersion = req.body.platformVersion;
        user.pushToken = req.body.pushToken;
        user.appVersion = req.body.appVersion;
        user.lastSeen = now;

        // create an object from our document
        var upsertData = user.toObject();
        // delete attributes to upsert
        delete upsertData._id;
        delete upsertData.firstSeen;

        // upsert in db
        User.update({ deviceId: user.deviceId }, { $setOnInsert: { firstSeen: now }, $set: upsertData }, { upsert: true }, function(err, user) {
            if (err) { res.send(err); }
            res.status(200).json({ message: "successful!", id: user._id });
            res.end();
        });
    });

    // on routes that end in /users/:userDevId/lectures
    router.route("/:deviceId/lectures")

        // get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
        .post(function(req, res) {
            User.findById(req.params.deviceId, function(err, user) {
                if (err) { res.status(500).send(err); }

                // update users selectedLectures
                User.update({ deviceId: user.deviceId }, { selectedLectures: req.params.selectedLectures }, function(err, user) {
                    if (err) { res.send(err); }
                    res.status(200).json({ message: "successful!", id: user._id });
                });
            });
        });

module.exports = router;
<|endoftext|>


<commit_before>const Pulse = require('./adt-pulse.js');
const mqtt = require('mqtt');
var config = require('/data/options.json');

var myAlarm = new Pulse(config.pulse_login.username, config.pulse_login.password);
var client = new mqtt.connect("mqtt://"+config.mqtt_host,config.mqtt_connect_options);
var alarm_state_topic = config.alarm_state_topic;
var alarm_command_topic = config.alarm_command_topic;
var zone_state_topic = config.zone_state_topic;
var smartthings_topic = config.smartthings_topic;
var smartthings = config.smartthings;

var alarm_last_state = "unknown";
var devices = {};

client.on('connect', function () {
  console.log("MQTT Sub to: "+alarm_command_topic);
  client.subscribe(alarm_command_topic)
  if (smartthings){
      client.subscribe(smartthings_topic+"/ADT Alarm System/alarm/state")
  }
});

client.on('message', function (topic, message) {
  console.log((new Date()).toLocaleString()+" Received Message:"+ topic + ":"+message);

  if (smartthings && topic==smartthings_topic+"/ADT Alarm System/alarm/state" && message.toString().includes("_push")){
      var toState=null;

      switch (message.toString()){
        case "off_push":
          toState="disarm";
          break;
        case "stay_push":
          toState="arm_home";
          break;
        case "away_push":
          toState="arm_away";
          break;
      }
      console.log((new Date()).toLocaleString()+" Pushing alarm state to Hass:"+toState);

      if (toState!=null){
        client.publish(alarm_command_topic, toState,{"retain":false});
      }
      return;
  }
  if (topic!=alarm_command_topic){
    return;
  }

  var msg = message.toString();
  var action;
  var prev_state="disarmed";

  if(alarm_last_state=="armed_home") prev_state = "stay";
  if(alarm_last_state=="armed_away") prev_state = "away";

  if (msg =="arm_home"){
      action= {'newstate':'stay','prev_state':prev_state};
  }
  else if (msg=="disarm") {
     action= {'newstate':'disarm','prev_state':prev_state};
  }
  else if (msg=="arm_away") {
    action = {'newstate':'away','prev_state':prev_state};
  }  else{ // I don't know this mode #5
      console.log((new Date()).toLocaleString()+" Unsupportated state requested:"+msg);
      return;
  }

  myAlarm.setAlarmState(action);
});

// Register Callbacks:
myAlarm.onDeviceUpdate(
    function(device) {
        console.log("Device callback"+ JSON.stringify(device));
    }
);

myAlarm.onStatusUpdate(
  function(device) {
      var mqtt_state = "unknown";
      var sm_alarm_value = "off";

      var status = device.status.toLowerCase();

      // smartthings bridge has no typical alarm device with stay|away|alarm|home status.
      // we'll re-use the "alarm" and map strobe|siren|both|off to stay|away|alarm|home
      // Sorry I'm too lazy to write my own smartthngs bridge for now.

      if (status.includes('disarmed')) {
          mqtt_state = "disarmed";
          sm_alarm_value = "off";
      }
      if (status.includes('armed stay')) {
          mqtt_state = "armed_home";
          sm_alarm_value = "strobe";
      }
      if (status.includes('armed away')) {
          mqtt_state = "armed_away";
          sm_alarm_value = "siren";
      }
      if (status.includes('alarm')) {
          mqtt_state = "triggered";
          sm_alarm_value = "both";
      }
      if (status.includes('arming')) {
          mqtt_state = "pending";
          sm_alarm_value = "siren"; // temporary
      }

      if (!mqtt_state.includes(alarm_last_state) && !mqtt_state.includes('unknown')) {
         console.log((new Date()).toLocaleString()+": Pushing alarm state: "+mqtt_state+" to "+alarm_state_topic);
         client.publish(alarm_state_topic, mqtt_state,{"retain":true});
         if (smartthings){
           var sm_alarm_topic = smartthings_topic+"/ADT Alarm System/alarm/cmd";
           console.log((new Date()).toLocaleString()+": Pushing alarm state to smartthings"+sm_alarm_topic);
           client.publish(sm_alarm_topic, sm_alarm_value,{"retain":false});
         }
		  alarm_last_state = mqtt_state;
      }
  }
);

myAlarm.onZoneUpdate(
  function(device) {

    var dev_zone_state_topic = zone_state_topic+"/"+device.name+"/state";
    var devValue = JSON.stringify(device);
    var sm_dev_zone_state_topic;

    // smartthings bridge assumes actionable devices have a topic set with cmd
    // adt/zone/DEVICE_NAME/state needs to turn Macintosh
    // smartthings/DEVICE_NAME/contact/cmd
    // or
    // smartthings/DEVICE_NAME/motion/cmd

    if (smartthings){
      var contactType = "contact";
      var contactValue= (device.status == "devStatOK")? "closed":"open";

      if (device.tags.includes("motion")) {
        contactType="motion";
        contactValue = (device.status == "devStatOK")? "inactive":"active";
      }
       sm_dev_zone_state_topic=smartthings_topic+"/"+device.name+"/"+contactType+"/cmd";
    }

    if (devices[device.id]==null || device.activityTs!=devices[device.id].activityTs){
        client.publish(dev_zone_state_topic, devValue, {"retain":false});
        console.log((new Date()).toLocaleString()+": Pushing  "+dev_zone_state_topic+" to "+devValue);

        if (smartthings){
          client.publish(sm_dev_zone_state_topic, contactValue, {"retain":false});
          console.log((new Date()).toLocaleString()+": Pushing to smartthings: "+sm_dev_zone_state_topic+" to "+contactValue);
        }
	  }
      devices[device.id] = device;
  }
);

myAlarm.pulse();
<commit_msg>reverting previous change.<commit_after>const Pulse = require('./adt-pulse.js');
const mqtt = require('mqtt');
var config = require('/data/options.json');

var myAlarm = new Pulse(config.pulse_login.username, config.pulse_login.password);
var client = new mqtt.connect("mqtt://"+config.mqtt_host,config.mqtt_connect_options);
var alarm_state_topic = config.alarm_state_topic;
var alarm_command_topic = config.alarm_command_topic;
var zone_state_topic = config.zone_state_topic;
var smartthings_topic = config.smartthings_topic;
var smartthings = config.smartthings;

var alarm_last_state = "unknown";
var devices = {};

client.on('connect', function () {
  console.log("MQTT Sub to: "+alarm_command_topic);
  client.subscribe(alarm_command_topic)
  if (smartthings){
      client.subscribe(smartthings_topic+"/ADT Alarm System/alarm/state")
  }
});

client.on('message', function (topic, message) {
  console.log((new Date()).toLocaleString()+" Received Message:"+ topic + ":"+message);

  if (smartthings && topic==smartthings_topic+"/ADT Alarm System/alarm/state" && message.toString().includes("_push")){
      var toState=null;

      switch (message.toString()){
        case "off_push":
          toState="disarm";
          break;
        case "stay_push":
          toState="arm_home";
          break;
        case "away_push":
          toState="arm_away";
          break;
      }
      console.log((new Date()).toLocaleString()+" Pushing alarm state to Hass:"+toState);

      if (toState!=null){
        client.publish(alarm_command_topic, toState,{"retain":false});
      }
      return;
  }
  if (topic!=alarm_command_topic){
    return;
  }

  var msg = message.toString();
  var action;
  var prev_state="disarmed";

  if(alarm_last_state=="armed_home") prev_state = "stay";
  if(alarm_last_state=="armed_away") prev_state = "away";

  if (msg =="arm_home"){
      action= {'newstate':'stay','prev_state':prev_state};
  }
  else if (msg=="disarm") {
     action= {'newstate':'disarm','prev_state':prev_state};
  }
  else if (msg=="arm_away") {
    action = {'newstate':'away','prev_state':prev_state};
  }  else{ // I don't know this mode #5
      console.log((new Date()).toLocaleString()+" Unsupportated state requested:"+msg);
      return;
  }

  myAlarm.setAlarmState(action);
});

// Register Callbacks:
myAlarm.onDeviceUpdate(
    function(device) {
        console.log("Device callback"+ JSON.stringify(device));
    }
);

myAlarm.onStatusUpdate(
  function(device) {
      var mqtt_state = "unknown";
      var sm_alarm_value = "off";

      var status = device.status.toLowerCase();

      // smartthings bridge has no typical alarm device with stay|away|alarm|home status.
      // we'll re-use the "alarm" and map strobe|siren|both|off to stay|away|alarm|home
      // Sorry I'm too lazy to write my own smartthngs bridge for now.

      if (status.includes('disarmed')) {
          mqtt_state = "disarmed";
          sm_alarm_value = "off";
      }
      if (status.includes('armed stay')) {
          mqtt_state = "armed_home";
          sm_alarm_value = "strobe";
      }
      if (status.includes('armed away')) {
          mqtt_state = "armed_away";
          sm_alarm_value = "siren";
      }
      if (status.includes('alarm')) {
          mqtt_state = "triggered";
          sm_alarm_value = "both";
      }
      if (status.includes('arming')) {
          mqtt_state = "pending";
          sm_alarm_value = "siren"; // temporary
      }

      if (!mqtt_state.includes(alarm_last_state) && !mqtt_state.includes('unknown')) {
         console.log((new Date()).toLocaleString()+": Pushing alarm state: "+mqtt_state+" to "+alarm_state_topic);
         client.publish(alarm_state_topic, mqtt_state,{"retain":true});
         if (smartthings){
           var sm_alarm_topic = smartthings_topic+"/ADT Alarm System/alarm/cmd";
           console.log((new Date()).toLocaleString()+": Pushing alarm state to smartthings"+sm_alarm_topic);
           client.publish(sm_alarm_topic, sm_alarm_value,{"retain":false});
         }
		  alarm_last_state = mqtt_state;
      }
  }
);

myAlarm.onZoneUpdate(
  function(device) {

    var dev_zone_state_topic = zone_state_topic+"/"+device.name+"/state";
    var devValue = JSON.stringify(device);
    var sm_dev_zone_state_topic;

    // smartthings bridge assumes actionable devices have a topic set with cmd
    // adt/zone/DEVICE_NAME/state needs to turn into
    // smartthings/DEVICE_NAME/door/cmd
    // or
    // smartthings/DEVICE_NAME/motion/cmd

    if (smartthings){
      var contactType = "door";
      var contactValue= (device.status == "devStatOK")? "closed":"open";

      if (device.tags.includes("motion")) {
        contactType="motion";
        contactValue = (device.status == "devStatOK")? "inactive":"active";
      }
       sm_dev_zone_state_topic=smartthings_topic+"/"+device.name+"/"+contactType+"/cmd";
    }

    if (devices[device.id]==null || device.activityTs!=devices[device.id].activityTs){
        client.publish(dev_zone_state_topic, devValue, {"retain":false});
        console.log((new Date()).toLocaleString()+": Pushing  "+dev_zone_state_topic+" to "+devValue);

        if (smartthings){
          client.publish(sm_dev_zone_state_topic, contactValue, {"retain":false});
          console.log((new Date()).toLocaleString()+": Pushing to smartthings: "+sm_dev_zone_state_topic+" to "+contactValue);
        }
	  }
      devices[device.id] = device;
  }
);

myAlarm.pulse();
<|endoftext|>


<commit_before>/************************ require ************************/

const Koa = require('koa'); // koa
const console = require('tracer').colorConsole(); // 增强console
const koaStatic = require('koa-static'); // koa-static   设置静态资源目录
const koaMount = require('koa-mount');  // koa-mount 将中间件挂载到特定url下
const koaBodyParser = require('koa-bodyparser');    // koa-bodyparser 解析post中的data
const staticFiles = require('./middlewares/staticFiles');   // 自己写的静态资源中间件
const templating = require('./middlewares/templating'); // 自己写的nunjucks模板渲染中间件

const renderRouter = require('./routers/render'); // 渲染路由
const apiRouter = require('./routers/api'); // 接口路由

/************************ initial ************************/

const app = new Koa();

// 是否是生产环境
const isProduction = process.env.NODE_ENV === 'production';
console.debug('当前环境 process.env.NODE_ENV', process.env.NODE_ENV);

/************************ middleware ************************/

// x-response-time 记录请求时间
app.use(async function (ctx, next) {
    const startTime = new Date();
    await next();
    const ms = new Date() - startTime;
    ctx.set('X-Response-Time', `${ms}ms`); // 把请求开始到响应完成的时间存到ctx里
    console.info(`响应时间 x-response-time ${ms}ms`);
});

// 开发环境下才会设置静态文件目录
if (!isProduction) {

    // // 设置静态目录，使用 koa-mount 将静态资源目录挂载到 /static 路径下
    // app.use(koaMount('/static', koaStatic('static')));

    // 设置静态资源目录，使用自己写的中间件
    app.use(staticFiles('/static', __dirname + '/static'));
}

// 解析post的data
app.use(koaBodyParser());

// 给ctx添加render方法，渲染模板文件
app.use(templating('views', {
    noCache: !isProduction, // 生产环境需要缓存
    watch: !isProduction,   // 生产环境不需要实时监测文件变化
}));

/************************ 路由 ************************/

// 渲染路由，用来渲染页面
app.use(renderRouter.routes());
app.use(renderRouter.allowedMethods());

// 接口路由，用来做逻辑处理
app.use(apiRouter.routes());
app.use(apiRouter.allowedMethods());

/************************ start server ************************/

app.listen(3000);
console.debug('listenning 3000...');

/************************ error handler ************************/

app.on('error', err =>
    console.error('server error', err)
);<commit_msg>设置React格式化快捷键<commit_after>/************************ require ************************/

const Koa = require('koa'); // koa
const console = require('tracer').colorConsole(); // 增强console
const koaStatic = require('koa-static'); // koa-static   设置静态资源目录
const koaMount = require('koa-mount'); // koa-mount 将中间件挂载到特定url下
const koaBodyParser = require('koa-bodyparser'); // koa-bodyparser 解析post中的data
const staticFiles = require('./middlewares/staticFiles'); // 自己写的静态资源中间件
const templating = require('./middlewares/templating'); // 自己写的nunjucks模板渲染中间件

const renderRouter = require('./routers/render'); // 渲染路由
const apiRouter = require('./routers/api'); // 接口路由

/************************ initial ************************/

const app = new Koa();

// 是否是生产环境
const isProduction = process.env.NODE_ENV === 'production';
console.debug('当前环境 process.env.NODE_ENV', process.env.NODE_ENV);

/************************ middleware ************************/

// x-response-time 记录请求时间
app.use(async function (ctx, next) {
    const startTime = new Date();
    await next();
    const ms = new Date() - startTime;
    ctx.set('X-Response-Time', `${ms}ms`); // 把请求开始到响应完成的时间存到ctx里
    console.info(`响应时间 x-response-time ${ms}ms`);
});

// 开发环境下才会设置静态文件目录
if (!isProduction) {

    // // 设置静态目录，使用 koa-mount 将静态资源目录挂载到 /static 路径下 app.use(koaMount('/static',
    // koaStatic('static'))); 设置静态资源目录，使用自己写的中间件
    app.use(staticFiles('/static', __dirname + '/static'));
}

// 解析post的data
app.use(koaBodyParser());

// 给ctx添加render方法，渲染模板文件
app.use(templating('views', {
    noCache: !isProduction, // 生产环境需要缓存
    watch: !isProduction, // 生产环境不需要实时监测文件变化
}));

/************************ 路由 ************************/

// 渲染路由，用来渲染页面
app.use(renderRouter.routes());
app.use(renderRouter.allowedMethods());

// 接口路由，用来做逻辑处理
app.use(apiRouter.routes());
app.use(apiRouter.allowedMethods());

/************************ start server ************************/

app.listen(3000);
console.debug('listenning 3000...');

/************************ error handler ************************/

app.on('error', err => console.error('server error', err));<|endoftext|>


<commit_before>'use strict';
module.exports = function(express) {

const router = express.Router();
const async = require('async');
const db = require('../server/db.js');
let users = require('../models/users.js');

router.route('/')

.get((req, res) => {
  res.send('Howdy partna');
})

.put((req, res) => {
  let data = req.body;

  async.waterfall([
    (callback) => {
      users.findOrCreate(data, (err) => {
        res.status(500).json({ error: err });
      },
      (user) => {
        callback(null, user.dataValues);
      });
    },
    (user, callback) => {
      users.find(user, (err) => {
        res.status(500).json({ error: err });
      },
    (foundUser) => {
      callback(null, foundUser);
    })
    }
  ],
  (err, foundUser) => {
    if(err) {
      res.status(500).json({ error: err });
    }
    res.status(200).json(foundUser);
  });
});

return router;

}
<commit_msg>Removed the dataValues<commit_after>'use strict';
module.exports = function(express) {

const router = express.Router();
const async = require('async');
const db = require('../server/db.js');
let users = require('../models/users.js');

router.route('/')

.get((req, res) => {
  res.send('Howdy partna');
})

.put((req, res) => {
  let data = req.body;

  async.waterfall([
    (callback) => {
      users.findOrCreate(data, (err) => {
        res.status(500).json({ error: err });
      },
      (user) => {
        callback(null, user);
      });
    },
    (user, callback) => {
      users.find(user, (err) => {
        res.status(500).json({ error: err });
      },
    (foundUser) => {
      callback(null, foundUser);
    })
    }
  ],
  (err, foundUser) => {
    if(err) {
      res.status(500).json({ error: err });
    }
    res.status(200).json(foundUser);
  });
});

return router;

}
<|endoftext|>