<commit_before> // deprecating, replacing with serverless mode
var RUNNING_LOCAL = (document.location.host == 'localhost' || document.location.host == '127.0.0.1' || document.location.protocol == 'file:');
var API_URL = RUNNING_LOCAL ? 'http://0.0.0.0:5000/' : 'https://opentaba-server.herokuapp.com/';

var gushimLayer;
leafletPip.bassackwards = true;

var CITY_NAME = "ירושלים"; //TODO: replace this with something more scalable.

var MAP_CENTER = [31.765, 35.17];
var DEFAULT_ZOOM = 13;

// var API_URL = '/'; // serverless, bitches! just store the JSON in the directory and grab it from there.

var highlit = [];

// Utility endsWith function
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function show_data(url){
	if (url.indexOf('.pdf', url.length - 4) !== -1) { // endsWith('.pdf')?
		new PDFObject({ url: url }).embed("modal-doc");
	} else {
		$("#modal-doc").html('');
	}

	$("#doc_new_window").attr("href", url);
	$("#docModal").modal().css({ width: '90%', height: '80%', 'margin-left': function () { return -($(this).width() / 2); } });
}

function render_plans(plans, gid) {
	//TODO: rewrite this DRY
	var out = '
גוש ' + gid + '
';

	// html brought to you courtsey of 1998
	out += "
";
	for (var i = 0 ; i<plans.length ; i++) {
		var p = plans[i];

		//plan_link = 'http://www.mmi.gov.il/IturTabot/taba2.asp?Gush=' + p.gush_id + '&MisTochnit=' + escape(p.number)
		//plan_link = 'http://mmi.gov.il/IturTabot/taba4.asp?kod=3000&MsTochnit=' + escape(p.number);
		plan_link = p.details_link;

		out+='
' +
			 '	' + [p.day, p.month, p.year].join('/') + '	' +
			 '	' + p.status  + '	'+
			 '	' + p.essence + '	'+
			 '
' +
			 '
' +
			 '	' +
			 '		'+
			 '		תוכנית ' + p.number + '' +
			 '		' +
			 '	';
		var j;
		for (j=0 ; j<p.tasrit_link.length ; j++)
			out += '';

		for (j=0 ; j<p.takanon_link.length ; j++)
			out += '';

		for (j=0 ; j<p.nispahim_link.length ; j++)
			out += '';

		for (j=0 ; j<p.files_link.length ; j++)
			out += '';

		out+='		'  +
			 '
' 	+
			 '

';
	}
	out += '
';

	$("#info").html(out);

	// activate Boostrap tooltips on attachment icons
	$("[rel='tooltip']").tooltip({'placement' : 'bottom'});

	$(".item").hover(
			function () { $(this).css("background","#fff"); $(this).next(".details").css("background","#fff"); }, //#f7f7f9
			function () { $(this).css("background","")	  ; $(this).next(".details").css("background",""); }
	);

	$(".details").hover(
			function () { $(this).css("background","#fff"); $(this).prev(".item").css("background","#fff"); },
			function () { $(this).css("background","")	  ; $(this).prev(".item").css("background",""); }
	);

}

function get_gush(gush_id) {
	// console.log("get_gush: " + API_URL + 'gush/' + gush_id + '/plans')
	clear_all_highlit();
	highlight_gush(gush_id);
	location.hash = "#/gush/" + gush_id;

	$.getJSON(
		API_URL + 'gush/' + gush_id + '/plans.json',
		function(d) {
			//console.log(d.length);
			render_plans(d, gush_id);
		}
		);

	console.log('waiting for json');

}

// find a rendered gush based on ID
function find_gush(gush_id){
	g = gushim.features.filter(
		function(f){ return (f.properties.Name == gush_id); }
	);
	return g[0];
}

// get a gush by street address
function get_gush_by_addr(addr) {
	if (!addr.endsWith(" " + CITY_NAME)) { //TODO: change to regex with cityname
		addr = addr + " " + CITY_NAME;
	}

	console.log("get_gush_by_addr: " + addr);

	// Use Google api to find a gush by address
	$.getJSON(
		'https://maps.googleapis.com/maps/api/geocode/json?address='+addr+'&sensor=false',
		function (r) {
			$('#scrobber').hide();
			$('#addr-error-p').html('');

			if (r['status'] == 'OK' && r['results'].length > 0) {
				// Here we have a case when Google api returns without an actual place (even a street),
				// so it only has a city. This happens because it didn't find the address, but we
				// did append the name of the current city at the end, and Google apparently thinks
				// 'better something than nothing'. We're trying to ignore this (should test though)
				if (r['results'][0]['types'].length == 2 &&
					$.inArray('locality', r['results'][0]['types']) > -1 &&
					$.inArray('political', r['results'][0]['types']) > -1) {
					$('#addr-error-p').html('כתובת שגויה או שלא נמצאו נתונים');
				}
				else {
					var lat = r['results'][0]['geometry']['location']['lat'];
					var lon = r['results'][0]['geometry']['location']['lng'];
					console.log('got lon: ' + lon + ', lat: ' + lat);

					// Using leafletpip we try to find an object in the gushim layer with the coordinate we got
					var gid = leafletPip.pointInLayer([lat, lon], gushimLayer, true);
					if (gid && gid.length > 0) {
						get_gush(gid[0].gushid);
						var pp = L.popup().setLatLng([lat, lon]).setContent('' + addr + '').openOn(map);
					} else {
						$('#addr-error-p').html('לא נמצא גוש התואם לכתובת'); // TODO: when enabling multiple cities change the message to point users to try a differenct city
					}
				}
			}
			else if (r['status'] == 'ZERO_RESULTS') {
				$('#addr-error-p').html('כתובת שגויה או שלא נמצאו נתונים');
			}
			else {
				$('#addr-error-p').html('חלה שגיאה בחיפוש הכתובת, אנא נסו שנית מאוחר יותר');
			}
		}
	)
   .fail(
   		function(){
   			$('#scrobber').hide();
   			$('#addr-error-p').html('חלה שגיאה בחיפוש הכתובת, אנא נסו שנית מאוחר יותר');
   		}
   	);
}

function highlight_gush(id) {
	gush = 'gush_' + id;
	console.log("highlight_gush ", gush);
	map.fitBounds(map._layers[gush].getBounds());
	map._layers[gush].setStyle({opacity: 0 	, color: "blue"});
	highlit.push(id);
}

function clear_highlight(id) {
	gush = 'gush_' + id;
	map._layers[gush].setStyle({opacity: 0.05 , color: "#777"});
	highlit.splice(highlit.indexOf(id), 1);
}

function clear_all_highlit() {
	while (highlit.length > 0) {
		clear_highlight(highlit[0]);
	}
}

function onEachFeature(feature, layer) {
	// layer.bindPopup(feature.properties.Name + " גוש ");
	layer.on({
				'mouseover'	: function() { if (highlit.indexOf(this["gushid"]) < 0) { this.setStyle({ opacity: 0 	, color: "red" 	}) } } ,
				'mouseout'	: function() { if (highlit.indexOf(this["gushid"]) < 0) { this.setStyle({ opacity: 0.95, color: "#777" }) } },
				'click'		: function() {
					$("#info").html("עוד מעט...");
					location.hash = "#/gush/" + feature.properties.Name;
					get_gush(feature.properties.Name);
				}
			});
	layer["gushid"] = feature.properties.Name;
	layer._leaflet_id = 'gush_' + feature.properties.Name;
}

// jQuery startup funcs
$(document).ready(function(){

	// comment out for serverless
	// wake up possibly-idling heroku dyno to make sure later requests aren't too slow
	$.getJSON( API_URL + "wakeup" , function(){
		// do nothing
	});

	// setup a path.js router to allow distinct URLs for each block
	Path.map("#/gush/:gush_id").to(
		function(){
			$("#docModal").modal('hide');
			get_gush(this.params['gush_id'].split('?')[0]);  // remove '?params' if exists
		}
	);

	Path.map("").to(
		function(){
			$("#docModal").modal('hide');
			$("#info").html("");
			clear_all_highlit();
			map.setView(MAP_CENTER, DEFAULT_ZOOM);
		}
	);

	Path.listen();

	$('#addr-form').submit(
		function() {
			var addr = $('#addr-text').val();
			console.log('Getting gush for address "' + addr + '"');
			$('#scrobber').show();
			get_gush_by_addr(addr);
			return false;
		}
	);
});

var map = L.map('map', { scrollWheelZoom: true, attributionControl: false }).setView(MAP_CENTER, DEFAULT_ZOOM);

// tile_url = 'http://{s}.tile.cloudmade.com/424caca899ea4a53b055c5e3078524ca/997/256/{z}/{x}/{y}.png';
// tile_url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
tile_url = "http://{s}.tiles.mapbox.com/v3/niryariv.map-n3zuwkkz/{z}/{x}/{y}.png";

L.tileLayer(tile_url, {
	maxZoom: 16,
	minZoom: 13
}).addTo(map);

gushimLayer = L.geoJson(gushim,
	{
		onEachFeature: onEachFeature,
		style : {
			"color" : "#777",
			"weight": 1,
			"opacity": 0.9
		}
	}
).addTo(map);
<commit_msg>use clean mapbox tiles<commit_after> // deprecating, replacing with serverless mode
var RUNNING_LOCAL = (document.location.host == 'localhost' || document.location.host == '127.0.0.1' || document.location.protocol == 'file:');
var API_URL = RUNNING_LOCAL ? 'http://0.0.0.0:5000/' : 'https://opentaba-server.herokuapp.com/';

var gushimLayer;
leafletPip.bassackwards = true;

var CITY_NAME = "ירושלים"; //TODO: replace this with something more scalable.

var MAP_CENTER = [31.765, 35.17];
var DEFAULT_ZOOM = 13;

// var API_URL = '/'; // serverless, bitches! just store the JSON in the directory and grab it from there.

var highlit = [];

// Utility endsWith function
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function show_data(url){
	if (url.indexOf('.pdf', url.length - 4) !== -1) { // endsWith('.pdf')?
		new PDFObject({ url: url }).embed("modal-doc");
	} else {
		$("#modal-doc").html('');
	}

	$("#doc_new_window").attr("href", url);
	$("#docModal").modal().css({ width: '90%', height: '80%', 'margin-left': function () { return -($(this).width() / 2); } });
}

function render_plans(plans, gid) {
	//TODO: rewrite this DRY
	var out = '
גוש ' + gid + '
';

	// html brought to you courtsey of 1998
	out += "
";
	for (var i = 0 ; i<plans.length ; i++) {
		var p = plans[i];

		//plan_link = 'http://www.mmi.gov.il/IturTabot/taba2.asp?Gush=' + p.gush_id + '&MisTochnit=' + escape(p.number)
		//plan_link = 'http://mmi.gov.il/IturTabot/taba4.asp?kod=3000&MsTochnit=' + escape(p.number);
		plan_link = p.details_link;

		out+='
' +
			 '	' + [p.day, p.month, p.year].join('/') + '	' +
			 '	' + p.status  + '	'+
			 '	' + p.essence + '	'+
			 '
' +
			 '
' +
			 '	' +
			 '		'+
			 '		תוכנית ' + p.number + '' +
			 '		' +
			 '	';
		var j;
		for (j=0 ; j<p.tasrit_link.length ; j++)
			out += '';

		for (j=0 ; j<p.takanon_link.length ; j++)
			out += '';

		for (j=0 ; j<p.nispahim_link.length ; j++)
			out += '';

		for (j=0 ; j<p.files_link.length ; j++)
			out += '';

		out+='		'  +
			 '
' 	+
			 '

';
	}
	out += '
';

	$("#info").html(out);

	// activate Boostrap tooltips on attachment icons
	$("[rel='tooltip']").tooltip({'placement' : 'bottom'});

	$(".item").hover(
			function () { $(this).css("background","#fff"); $(this).next(".details").css("background","#fff"); }, //#f7f7f9
			function () { $(this).css("background","")	  ; $(this).next(".details").css("background",""); }
	);

	$(".details").hover(
			function () { $(this).css("background","#fff"); $(this).prev(".item").css("background","#fff"); },
			function () { $(this).css("background","")	  ; $(this).prev(".item").css("background",""); }
	);

}

function get_gush(gush_id) {
	// console.log("get_gush: " + API_URL + 'gush/' + gush_id + '/plans')
	clear_all_highlit();
	highlight_gush(gush_id);
	location.hash = "#/gush/" + gush_id;

	$.getJSON(
		API_URL + 'gush/' + gush_id + '/plans.json',
		function(d) {
			//console.log(d.length);
			render_plans(d, gush_id);
		}
		);

	console.log('waiting for json');

}

// find a rendered gush based on ID
function find_gush(gush_id){
	g = gushim.features.filter(
		function(f){ return (f.properties.Name == gush_id); }
	);
	return g[0];
}

// get a gush by street address
function get_gush_by_addr(addr) {
	if (!addr.endsWith(" " + CITY_NAME)) { //TODO: change to regex with cityname
		addr = addr + " " + CITY_NAME;
	}

	console.log("get_gush_by_addr: " + addr);

	// Use Google api to find a gush by address
	$.getJSON(
		'https://maps.googleapis.com/maps/api/geocode/json?address='+addr+'&sensor=false',
		function (r) {
			$('#scrobber').hide();
			$('#addr-error-p').html('');

			if (r['status'] == 'OK' && r['results'].length > 0) {
				// Here we have a case when Google api returns without an actual place (even a street),
				// so it only has a city. This happens because it didn't find the address, but we
				// did append the name of the current city at the end, and Google apparently thinks
				// 'better something than nothing'. We're trying to ignore this (should test though)
				if (r['results'][0]['types'].length == 2 &&
					$.inArray('locality', r['results'][0]['types']) > -1 &&
					$.inArray('political', r['results'][0]['types']) > -1) {
					$('#addr-error-p').html('כתובת שגויה או שלא נמצאו נתונים');
				}
				else {
					var lat = r['results'][0]['geometry']['location']['lat'];
					var lon = r['results'][0]['geometry']['location']['lng'];
					console.log('got lon: ' + lon + ', lat: ' + lat);

					// Using leafletpip we try to find an object in the gushim layer with the coordinate we got
					var gid = leafletPip.pointInLayer([lat, lon], gushimLayer, true);
					if (gid && gid.length > 0) {
						get_gush(gid[0].gushid);
						var pp = L.popup().setLatLng([lat, lon]).setContent('' + addr + '').openOn(map);
					} else {
						$('#addr-error-p').html('לא נמצא גוש התואם לכתובת'); // TODO: when enabling multiple cities change the message to point users to try a differenct city
					}
				}
			}
			else if (r['status'] == 'ZERO_RESULTS') {
				$('#addr-error-p').html('כתובת שגויה או שלא נמצאו נתונים');
			}
			else {
				$('#addr-error-p').html('חלה שגיאה בחיפוש הכתובת, אנא נסו שנית מאוחר יותר');
			}
		}
	)
   .fail(
   		function(){
   			$('#scrobber').hide();
   			$('#addr-error-p').html('חלה שגיאה בחיפוש הכתובת, אנא נסו שנית מאוחר יותר');
   		}
   	);
}

function highlight_gush(id) {
	gush = 'gush_' + id;
	console.log("highlight_gush ", gush);
	map.fitBounds(map._layers[gush].getBounds());
	map._layers[gush].setStyle({opacity: 0 	, color: "blue"});
	highlit.push(id);
}

function clear_highlight(id) {
	gush = 'gush_' + id;
	map._layers[gush].setStyle({opacity: 0.05 , color: "#777"});
	highlit.splice(highlit.indexOf(id), 1);
}

function clear_all_highlit() {
	while (highlit.length > 0) {
		clear_highlight(highlit[0]);
	}
}

function onEachFeature(feature, layer) {
	// layer.bindPopup(feature.properties.Name + " גוש ");
	layer.on({
				'mouseover'	: function() { if (highlit.indexOf(this["gushid"]) < 0) { this.setStyle({ opacity: 0 	, color: "red" 	}) } } ,
				'mouseout'	: function() { if (highlit.indexOf(this["gushid"]) < 0) { this.setStyle({ opacity: 0.95, color: "#777" }) } },
				'click'		: function() {
					$("#info").html("עוד מעט...");
					location.hash = "#/gush/" + feature.properties.Name;
					get_gush(feature.properties.Name);
				}
			});
	layer["gushid"] = feature.properties.Name;
	layer._leaflet_id = 'gush_' + feature.properties.Name;
}

// jQuery startup funcs
$(document).ready(function(){

	// comment out for serverless
	// wake up possibly-idling heroku dyno to make sure later requests aren't too slow
	$.getJSON( API_URL + "wakeup" , function(){
		// do nothing
	});

	// setup a path.js router to allow distinct URLs for each block
	Path.map("#/gush/:gush_id").to(
		function(){
			$("#docModal").modal('hide');
			get_gush(this.params['gush_id'].split('?')[0]);  // remove '?params' if exists
		}
	);

	Path.map("").to(
		function(){
			$("#docModal").modal('hide');
			$("#info").html("");
			clear_all_highlit();
			map.setView(MAP_CENTER, DEFAULT_ZOOM);
		}
	);

	Path.listen();

	$('#addr-form').submit(
		function() {
			var addr = $('#addr-text').val();
			console.log('Getting gush for address "' + addr + '"');
			$('#scrobber').show();
			get_gush_by_addr(addr);
			return false;
		}
	);
});

var map = L.map('map', { scrollWheelZoom: true, attributionControl: false }).setView(MAP_CENTER, DEFAULT_ZOOM);

// tile_url = 'http://{s}.tile.cloudmade.com/424caca899ea4a53b055c5e3078524ca/997/256/{z}/{x}/{y}.png';
// tile_url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
tile_url = "http://{s}.tiles.mapbox.com/v3/niryariv.i6e92njd/{z}/{x}/{y}.png";

L.tileLayer(tile_url, {
	maxZoom: 16,
	minZoom: 13
}).addTo(map);

gushimLayer = L.geoJson(gushim,
	{
		onEachFeature: onEachFeature,
		style : {
			"color" : "#777",
			"weight": 1,
			"opacity": 0.9
		}
	}
).addTo(map);
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cheerio = require('cheerio');
var http = require('http');
var request = require('request');
var fs = require("fs");
var mysql = require("mysql");
var io = require('socket.io');

// new modules
var stats = require("stats");

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// global urls array
var wu = {
    login: "https://wu.wsiz.rzeszow.pl/wunet/Logowanie2.aspx",
    podzgodzin: "https://wu.wsiz.rzeszow.pl/wunet/PodzGodzin.aspx",
    oceny: "https://wu.wsiz.rzeszow.pl/wunet/OcenyP.aspx",
    uwagi: "https://wu.wsiz.rzeszow.pl/wunet/UwagiDecyzje.aspx",
    wplaty: "https://wu.wsiz.rzeszow.pl/wunet/Wplaty2.aspx"
};

// global pages array
var page = {
    podzialgodzin: {
        title: "Podział godzin",
        url: "/podzialgodzin"
    },
    oceny: {
        title: "Oceny",
        url: "/oceny"
    },
    uwagi: {
        title: "Uwagi i decyzje",
        url: "/uwagi"
    },
    wplaty: {
        title: "Wpłaty",
        url: "/wplaty"
    }
};

app.route('/')
.get(function(req, res){
        res.render("login");
        stats.init(fs, req.ip);
})
.post(function(req, res) {
    var user = req.body;
    var viewstate_val, login_name, login_value = "w"+user.login, password_name, password_value = user.password, submit_name, submit_value;
        // parse login form
        request(wu.login, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(body);
                viewstate_val = $('#__VIEWSTATE').val();
                login_name = $('.login_field').find("input[type=text]").attr("name");
                password_name = $('.login_field').find("input[type=password]").attr("name");
                submit_name = $('.login_button').find("input[type=submit]").attr("name");
                submit_value = $('.login_button').find("input[type=submit]").val();

                var formData = {
                    __VIEWSTATE: viewstate_val
                };
                formData[login_name] = login_value;
                formData[password_name] = password_value;
                formData[submit_name] = submit_value;

                console.log(formData);

                request.post({url:'https://wu.wsiz.rzeszow.pl/wunet/Logowanie2.aspx', jar: true, form: formData}, function optionalCallback(err, httpResponse, body) {
                    if (err) {
                        return console.error('upload failed:', err);
                    } else {
                        console.log();
                        var status = httpResponse.statusCode;
                        if(status==302) {
                            //console.log("redirect");
                            res.redirect("/podzialgodzin");
                        } else {
                            return res.render("login", {error: "Auth error"});
                        }
                    }
                });
            } else {
                res.redirect("/#someproblems");
            }
        });
});

app.get(page.podzialgodzin.url, function(req, res) {
    return request({url: wu.podzgodzin, jar:true}, function(err, httpResponse, body) {
        var path = httpResponse.request.uri.pathname;
        if(path == "/wunet/Logowanie2.aspx") {
            res.redirect("/");
        } else {
            var $ = cheerio.load(body);
            $("#ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_dgDane").addClass("table table-hover table-responsive").find(".opisPrzedmDyd").remove();
            var data = $("#ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_dgDane");
            return res.render("page", {
                title: page.podzialgodzin.title,
                menu: page,
                data: data
            });
        }
    });
});

module.exports = app;
<commit_msg>Added Socket.IO<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cheerio = require('cheerio');
var http = require('http');
var request = require('request');
var fs = require("fs");
var mysql = require("mysql");
var io = require('socket.io');

// new modules
var stats = require("stats");

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// global urls array
var wu = {
    login: "https://wu.wsiz.rzeszow.pl/wunet/Logowanie2.aspx",
    podzgodzin: "https://wu.wsiz.rzeszow.pl/wunet/PodzGodzin.aspx",
    oceny: "https://wu.wsiz.rzeszow.pl/wunet/OcenyP.aspx",
    uwagi: "https://wu.wsiz.rzeszow.pl/wunet/UwagiDecyzje.aspx",
    wplaty: "https://wu.wsiz.rzeszow.pl/wunet/Wplaty2.aspx"
};

// global pages array
var page = {
    podzialgodzin: {
        title: "Podział godzin",
        url: "/podzialgodzin"
    },
    oceny: {
        title: "Oceny",
        url: "/oceny"
    },
    uwagi: {
        title: "Uwagi i decyzje",
        url: "/uwagi"
    },
    wplaty: {
        title: "Wpłaty",
        url: "/wplaty"
    }
};

app.route('/')
.get(function(req, res){
        res.render("login");
        stats.init(fs, req.ip);
})
.post(function(req, res) {
    var user = req.body;
    var viewstate_val, login_name, login_value = "w"+user.login, password_name, password_value = user.password, submit_name, submit_value;
        // parse login form
        request(wu.login, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(body);
                viewstate_val = $('#__VIEWSTATE').val();
                login_name = $('.login_field').find("input[type=text]").attr("name");
                password_name = $('.login_field').find("input[type=password]").attr("name");
                submit_name = $('.login_button').find("input[type=submit]").attr("name");
                submit_value = $('.login_button').find("input[type=submit]").val();

                var formData = {
                    __VIEWSTATE: viewstate_val
                };
                formData[login_name] = login_value;
                formData[password_name] = password_value;
                formData[submit_name] = submit_value;

                console.log(formData);

                request.post({url:'https://wu.wsiz.rzeszow.pl/wunet/Logowanie2.aspx', jar: true, form: formData}, function optionalCallback(err, httpResponse, body) {
                    if (err) {
                        return console.error('upload failed:', err);
                    } else {
                        console.log();
                        var status = httpResponse.statusCode;
                        if(status==302) {
                            //console.log("redirect");
                            res.redirect("/podzialgodzin");
                        } else {
                            return res.render("login", {error: "Auth error"});
                        }
                    }
                });
            } else {
                res.redirect("/#someproblems");
            }
        });
});

app.get(page.podzialgodzin.url, function(req, res) {
    return request({url: wu.podzgodzin, jar:true}, function(err, httpResponse, body) {
        var path = httpResponse.request.uri.pathname;
        if(path == "/wunet/Logowanie2.aspx") {
            res.redirect("/");
        } else {
            var $ = cheerio.load(body);
            $("#ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_dgDane").addClass("table table-hover table-responsive").find(".opisPrzedmDyd").remove();
            var data = $("#ctl00_ctl00_ContentPlaceHolder_RightContentPlaceHolder_dgDane");
            return res.render("page", {
                title: page.podzialgodzin.title,
                menu: page,
                data: data
            });
        }
    });
});

module.exports = app;
<|endoftext|>


<commit_before>function runNpm(command) {
	console.log('Running `npm ' + command + '`...');
	var child_process = require('child_process');
	var npm = child_process.spawn('npm', [command]);
	npm.stdout.on('data', function(data) {
		process.stdout.write(data);
	});
	npm.stderr.on('data', function(data) {
		process.stderr.write(data);
	});
	npm.on('close', function(code) {
		if (!code) {
			child_process.fork('app.js').disconnect();
		}
	});
}

try {
	require('sugar');
} catch (e) {
	return runNpm('install');
}
if (!Object.select) {
	return runNpm('update');
}

fs = require('fs');
if (!('existsSync' in fs)) {
	fs.existsSync = require('path').existsSync;
}

LoginServer = require('./loginserver.js');

// Synchronously copy config-example.js over to config.js if it doesn't exist
if (!fs.existsSync('./config/config.js')) {
	console.log("config.js doesn't exist - creating one with default settings...");
	fs.writeFileSync('./config/config.js',
		fs.readFileSync('./config/config-example.js')
	);
}

config = require('./config/config.js');

if (config.watchconfig) {
	fs.watchFile('./config/config.js', function(curr, prev) {
		if (curr.mtime <= prev.mtime) return;
		try {
			delete require.cache[require.resolve('./config/config.js')];
			config = require('./config/config.js');
			console.log('Reloaded config/config.js');
		} catch (e) {}
	});
}

config.pkg = {};
fs.readFile('package.json', function(err, data) {
	if (err) return;
	config.pkg = JSON.parse(data);
});

if (process.argv[2] && parseInt(process.argv[2])) {
	config.port = parseInt(process.argv[2]);
}
if (process.argv[3]) {
	config.setuid = process.argv[3];
}

var app = require('http').createServer();
var appssl;
if (config.ssl) {
	appssl = require('https').createServer(config.ssl.options);
}
try {
	(function() {
		var nodestatic = require('node-static');
		var cssserver = new nodestatic.Server('./config');
		var avatarserver = new nodestatic.Server('./config/avatars');
		var staticserver = new nodestatic.Server('./static');
		var staticRequestHandler = function(request, response) {
			request.resume();
			request.addListener('end', function() {
				if (config.customhttpresponse &&
						config.customhttpresponse(request, response)) {
					return;
				}
				var server;
				if (request.url === '/custom.css') {
					server = cssserver;
				} else if (request.url.substr(0, 9) === '/avatars/') {
					request.url = request.url.substr(8);
					server = avatarserver;
				} else {
					if (/^\/(teambuilder|ladder|lobby|battle)\/?$/.test(request.url) ||
							/^\/(lobby|battle)-([A-Za-z0-9-]*)$/.test(request.url)) {
						request.url = '/';
					}
					server = staticserver;
				}
				server.serve(request, response, function(e, res) {
					if (e && (e.status === 404)) {
						staticserver.serveFile('404.html', 404, {}, request, response);
					}
				});
			});
		};
		app.on('request', staticRequestHandler);
		if (appssl) {
			appssl.on('request', staticRequestHandler);
		}
	})();
} catch (e) {
	console.log('Could not start node-static - try `npm install` if you want to use it');
}
var server = require('sockjs').createServer({
	sockjs_url: "http://cdn.sockjs.org/sockjs-0.3.min.js",
	log: function(severity, message) {
		if (severity === 'error') console.log('ERROR: '+message);
	},
	prefix: '/showdown'
});

// Make `app`, `appssl`, and `server` available to the console.
App = app;
AppSSL = appssl;
Server = server;

/**
 * Converts anything to an ID. An ID must have only lowercase alphanumeric
 * characters.
 * If a string is passed, it will be converted to lowercase and
 * non-alphanumeric characters will be stripped.
 * If an object with an ID is passed, its ID will be returned.
 * Otherwise, an empty string will be returned.
 */
toId = function(text) {
	if (text && text.id) text = text.id;
	else if (text && text.userid) text = text.userid;

	return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
toUserid = toId;

/**
 * Validates a username or Pokemon nickname
 */
var bannedNameStartChars = {'~':1, '&':1, '@':1, '%':1, '+':1, '-':1, '!':1, '?':1, '#':1, ' ':1};
toName = function(name) {
	name = string(name);
	name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim();
	while (bannedNameStartChars[name.charAt(0)]) {
		name = name.substr(1);
	}
	if (name.length > 18) name = name.substr(0,18);
	return name;
};

/**
 * Escapes a string for HTML
 * If strEscape is true, escapes it for JavaScript, too
 */
sanitize = function(str, strEscape) {
	str = (''+(str||''));
	str = str.escapeHTML();
	if (strEscape) str = str.replace(/'/g, '\\\'');
	return str;
};

/**
 * Safely ensures the passed variable is a string
 * Simply doing ''+str can crash if str.toString crashes or isn't a function
 * If we're expecting a string and being given anything that isn't a string
 * or a number, it's safe to assume it's an error, and return ''
 */
string = function(str) {
	if (typeof str === 'string' || typeof str === 'number') return ''+str;
	return '';
}

/**
 * Converts any variable to an integer (numbers get floored, non-numbers
 * become 0). Then clamps it between min and (optionally) max.
 */
clampIntRange = function(num, min, max) {
	if (typeof num !== 'number') num = 0;
	num = Math.floor(num);
	if (num < min) num = min;
	if (typeof max !== 'undefined' && num > max) num = max;
	return num;
};

try {
	if (config.setuid) {
		process.setuid(config.setuid);
		console.log("setuid succeeded, we are now running as "+config.setuid);
	}
}
catch (err) {
	console.log("ERROR: setuid failed: [%s] Call: [%s]", err.message, err.syscall);
	process.exit(1);
}

Data = {};

Users = require('./users.js');

Rooms = require('./rooms.js');

delete process.send; // in case we're a child process
Verifier = require('./verifier.js');

parseCommand = require('./chat-commands.js').parseCommand;

Simulator = require('./simulator.js');

lockdown = false;

emit = function(socket, type, data) {
	if (typeof data === 'object') data.type = type;
	else data = {type: type, message: data};
	socket.write(JSON.stringify(data));
};

sendData = function(socket, data) {
	socket.write(data);
};

if (config.crashguard) {
	// graceful crash - allow current battles to finish before restarting
	process.on('uncaughtException', (function() {
		var lastCrash = 0;
		return function(err) {
			var dateNow = Date.now();
			var quietCrash = require('./crashlogger.js')(err, 'The main process');
			quietCrash = quietCrash || ((dateNow - lastCrash) <= 1000 * 60 * 5)
			lastCrash = Date.now();
			if (quietCrash) return;
			var stack = (""+err.stack).split("\n").slice(0,2).join("
");
			Rooms.lobby.addRaw('
THE SERVER HAS CRASHED: '+stack+'
Please restart the server.
');
			Rooms.lobby.addRaw('
You will not be able to talk in the lobby or start new battles until the server restarts.
');
			config.modchat = 'crash';
			lockdown = true;
		};
	})());
}

var socketCounter = 0;
server.on('connection', function(socket) {
	if (!socket.remoteAddress) {
		// This condition occurs several times per day. It may be a SockJS bug.
		try {
			socket.end();
		} catch (e) {}
		return;
	}
	socket.id = (++socketCounter);

	if (config.proxyip && (config.proxyip.indexOf(socket.remoteAddress) >= 0)) {
		var ips = (socket.headers['x-forwarded-for'] || '').split(',');
		var ip;
		while (ip = ips.pop()) {
			ip = ip.trim();
			if (config.proxyip.indexOf(ip) < 0) {
				socket.remoteAddress = ip;
				break;
			}
		}
	}

	if (Users.checkBanned(socket.remoteAddress)) {
		console.log('CONNECT BLOCKED - IP BANNED: '+socket.remoteAddress);
		socket.end();
		return;
	}
	console.log('CONNECT: '+socket.remoteAddress+' ['+socket.id+']');
	var interval;
	if (config.herokuhack) {
		// see https://github.com/sockjs/sockjs-node/issues/57#issuecomment-5242187
		interval = setInterval(function() {
			try {
				socket._session.recv.didClose();
			} catch (e) {}
		}, 15000);
	}

	var you;

	socket.on('data', function(message) {
		if (message.substr(0,1) === '{') return; // drop legacy JSON messages

		var youUser = you.user;
		if (!youUser) {
			// User has already disconnected from server.
			// It is not clear how this could happen and it may be impossible.
			console.log('WARNING: youUser is empty in `data` event!');
			return;
		}

		var pipeIndex = message.indexOf('|');
		if (pipeIndex < 0) return; // invalid message format

		var roomid = message.substr(0, pipeIndex);
		var lines = message.substr(pipeIndex + 1);
		var room = Rooms.get(roomid, 'lobby');
		lines.split('\n').forEach(function(text){
			youUser.chat(text, room, socket);
		});
	});

	socket.on('close', function() {
		if (interval) {
			clearInterval(interval);
		}
		var youUser = you.user;
		if (!youUser) return;
		youUser.onDisconnect(socket);
	});

	you = Users.connectUser(socket);
});
server.installHandlers(app, {});
app.listen(config.port);
if (appssl) {
	server.installHandlers(appssl, {});
	appssl.listen(config.ssl.port);
}

console.log('Server started on port ' + config.port);
if (appssl) {
	console.log('SSL server started on port ' + config.ssl.port);
}

console.log('Test your server at http://localhost:' + config.port);

// This slow operation is done *after* we start listening for connections
// to the server. Anybody who connects while this require() is running will
// have to wait a couple seconds before they are able to join the server, but
// at least they probably won't receive a connection error message.
Tools = require('./tools.js');

// After loading tools, generate and cache the format list.
Rooms.global.formatListText = Rooms.global.getFormatListText();
<commit_msg>Actually remove old `config.pkg` code<commit_after>function runNpm(command) {
	console.log('Running `npm ' + command + '`...');
	var child_process = require('child_process');
	var npm = child_process.spawn('npm', [command]);
	npm.stdout.on('data', function(data) {
		process.stdout.write(data);
	});
	npm.stderr.on('data', function(data) {
		process.stderr.write(data);
	});
	npm.on('close', function(code) {
		if (!code) {
			child_process.fork('app.js').disconnect();
		}
	});
}

try {
	require('sugar');
} catch (e) {
	return runNpm('install');
}
if (!Object.select) {
	return runNpm('update');
}

fs = require('fs');
if (!('existsSync' in fs)) {
	fs.existsSync = require('path').existsSync;
}

LoginServer = require('./loginserver.js');

// Synchronously copy config-example.js over to config.js if it doesn't exist
if (!fs.existsSync('./config/config.js')) {
	console.log("config.js doesn't exist - creating one with default settings...");
	fs.writeFileSync('./config/config.js',
		fs.readFileSync('./config/config-example.js')
	);
}

config = require('./config/config.js');

if (config.watchconfig) {
	fs.watchFile('./config/config.js', function(curr, prev) {
		if (curr.mtime <= prev.mtime) return;
		try {
			delete require.cache[require.resolve('./config/config.js')];
			config = require('./config/config.js');
			console.log('Reloaded config/config.js');
		} catch (e) {}
	});
}

if (process.argv[2] && parseInt(process.argv[2])) {
	config.port = parseInt(process.argv[2]);
}
if (process.argv[3]) {
	config.setuid = process.argv[3];
}

var app = require('http').createServer();
var appssl;
if (config.ssl) {
	appssl = require('https').createServer(config.ssl.options);
}
try {
	(function() {
		var nodestatic = require('node-static');
		var cssserver = new nodestatic.Server('./config');
		var avatarserver = new nodestatic.Server('./config/avatars');
		var staticserver = new nodestatic.Server('./static');
		var staticRequestHandler = function(request, response) {
			request.resume();
			request.addListener('end', function() {
				if (config.customhttpresponse &&
						config.customhttpresponse(request, response)) {
					return;
				}
				var server;
				if (request.url === '/custom.css') {
					server = cssserver;
				} else if (request.url.substr(0, 9) === '/avatars/') {
					request.url = request.url.substr(8);
					server = avatarserver;
				} else {
					if (/^\/(teambuilder|ladder|lobby|battle)\/?$/.test(request.url) ||
							/^\/(lobby|battle)-([A-Za-z0-9-]*)$/.test(request.url)) {
						request.url = '/';
					}
					server = staticserver;
				}
				server.serve(request, response, function(e, res) {
					if (e && (e.status === 404)) {
						staticserver.serveFile('404.html', 404, {}, request, response);
					}
				});
			});
		};
		app.on('request', staticRequestHandler);
		if (appssl) {
			appssl.on('request', staticRequestHandler);
		}
	})();
} catch (e) {
	console.log('Could not start node-static - try `npm install` if you want to use it');
}
var server = require('sockjs').createServer({
	sockjs_url: "http://cdn.sockjs.org/sockjs-0.3.min.js",
	log: function(severity, message) {
		if (severity === 'error') console.log('ERROR: '+message);
	},
	prefix: '/showdown'
});

// Make `app`, `appssl`, and `server` available to the console.
App = app;
AppSSL = appssl;
Server = server;

/**
 * Converts anything to an ID. An ID must have only lowercase alphanumeric
 * characters.
 * If a string is passed, it will be converted to lowercase and
 * non-alphanumeric characters will be stripped.
 * If an object with an ID is passed, its ID will be returned.
 * Otherwise, an empty string will be returned.
 */
toId = function(text) {
	if (text && text.id) text = text.id;
	else if (text && text.userid) text = text.userid;

	return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
toUserid = toId;

/**
 * Validates a username or Pokemon nickname
 */
var bannedNameStartChars = {'~':1, '&':1, '@':1, '%':1, '+':1, '-':1, '!':1, '?':1, '#':1, ' ':1};
toName = function(name) {
	name = string(name);
	name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim();
	while (bannedNameStartChars[name.charAt(0)]) {
		name = name.substr(1);
	}
	if (name.length > 18) name = name.substr(0,18);
	return name;
};

/**
 * Escapes a string for HTML
 * If strEscape is true, escapes it for JavaScript, too
 */
sanitize = function(str, strEscape) {
	str = (''+(str||''));
	str = str.escapeHTML();
	if (strEscape) str = str.replace(/'/g, '\\\'');
	return str;
};

/**
 * Safely ensures the passed variable is a string
 * Simply doing ''+str can crash if str.toString crashes or isn't a function
 * If we're expecting a string and being given anything that isn't a string
 * or a number, it's safe to assume it's an error, and return ''
 */
string = function(str) {
	if (typeof str === 'string' || typeof str === 'number') return ''+str;
	return '';
}

/**
 * Converts any variable to an integer (numbers get floored, non-numbers
 * become 0). Then clamps it between min and (optionally) max.
 */
clampIntRange = function(num, min, max) {
	if (typeof num !== 'number') num = 0;
	num = Math.floor(num);
	if (num < min) num = min;
	if (typeof max !== 'undefined' && num > max) num = max;
	return num;
};

try {
	if (config.setuid) {
		process.setuid(config.setuid);
		console.log("setuid succeeded, we are now running as "+config.setuid);
	}
}
catch (err) {
	console.log("ERROR: setuid failed: [%s] Call: [%s]", err.message, err.syscall);
	process.exit(1);
}

Data = {};

Users = require('./users.js');

Rooms = require('./rooms.js');

delete process.send; // in case we're a child process
Verifier = require('./verifier.js');

parseCommand = require('./chat-commands.js').parseCommand;

Simulator = require('./simulator.js');

lockdown = false;

emit = function(socket, type, data) {
	if (typeof data === 'object') data.type = type;
	else data = {type: type, message: data};
	socket.write(JSON.stringify(data));
};

sendData = function(socket, data) {
	socket.write(data);
};

if (config.crashguard) {
	// graceful crash - allow current battles to finish before restarting
	process.on('uncaughtException', (function() {
		var lastCrash = 0;
		return function(err) {
			var dateNow = Date.now();
			var quietCrash = require('./crashlogger.js')(err, 'The main process');
			quietCrash = quietCrash || ((dateNow - lastCrash) <= 1000 * 60 * 5)
			lastCrash = Date.now();
			if (quietCrash) return;
			var stack = (""+err.stack).split("\n").slice(0,2).join("
");
			Rooms.lobby.addRaw('
THE SERVER HAS CRASHED: '+stack+'
Please restart the server.
');
			Rooms.lobby.addRaw('
You will not be able to talk in the lobby or start new battles until the server restarts.
');
			config.modchat = 'crash';
			lockdown = true;
		};
	})());
}

var socketCounter = 0;
server.on('connection', function(socket) {
	if (!socket.remoteAddress) {
		// This condition occurs several times per day. It may be a SockJS bug.
		try {
			socket.end();
		} catch (e) {}
		return;
	}
	socket.id = (++socketCounter);

	if (config.proxyip && (config.proxyip.indexOf(socket.remoteAddress) >= 0)) {
		var ips = (socket.headers['x-forwarded-for'] || '').split(',');
		var ip;
		while (ip = ips.pop()) {
			ip = ip.trim();
			if (config.proxyip.indexOf(ip) < 0) {
				socket.remoteAddress = ip;
				break;
			}
		}
	}

	if (Users.checkBanned(socket.remoteAddress)) {
		console.log('CONNECT BLOCKED - IP BANNED: '+socket.remoteAddress);
		socket.end();
		return;
	}
	console.log('CONNECT: '+socket.remoteAddress+' ['+socket.id+']');
	var interval;
	if (config.herokuhack) {
		// see https://github.com/sockjs/sockjs-node/issues/57#issuecomment-5242187
		interval = setInterval(function() {
			try {
				socket._session.recv.didClose();
			} catch (e) {}
		}, 15000);
	}

	var you;

	socket.on('data', function(message) {
		if (message.substr(0,1) === '{') return; // drop legacy JSON messages

		var youUser = you.user;
		if (!youUser) {
			// User has already disconnected from server.
			// It is not clear how this could happen and it may be impossible.
			console.log('WARNING: youUser is empty in `data` event!');
			return;
		}

		var pipeIndex = message.indexOf('|');
		if (pipeIndex < 0) return; // invalid message format

		var roomid = message.substr(0, pipeIndex);
		var lines = message.substr(pipeIndex + 1);
		var room = Rooms.get(roomid, 'lobby');
		lines.split('\n').forEach(function(text){
			youUser.chat(text, room, socket);
		});
	});

	socket.on('close', function() {
		if (interval) {
			clearInterval(interval);
		}
		var youUser = you.user;
		if (!youUser) return;
		youUser.onDisconnect(socket);
	});

	you = Users.connectUser(socket);
});
server.installHandlers(app, {});
app.listen(config.port);
if (appssl) {
	server.installHandlers(appssl, {});
	appssl.listen(config.ssl.port);
}

console.log('Server started on port ' + config.port);
if (appssl) {
	console.log('SSL server started on port ' + config.ssl.port);
}

console.log('Test your server at http://localhost:' + config.port);

// This slow operation is done *after* we start listening for connections
// to the server. Anybody who connects while this require() is running will
// have to wait a couple seconds before they are able to join the server, but
// at least they probably won't receive a connection error message.
Tools = require('./tools.js');

// After loading tools, generate and cache the format list.
Rooms.global.formatListText = Rooms.global.getFormatListText();
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
//var logger = require('morgan');
var bodyParser = require('body-parser');
var cors = require('cors');
var helmet = require('helmet');
// var Memcached = require('memcached');
var compression = require('compression');
var config = require('./config');
var flash  = require('connect-flash');

// development, production or staging
require('dotenv').config({path: './config/.' +  process.env.NODE_ENV})

var debug = require('debug')('api');
var bunyan = require('bunyan');
var app = express();

global.log = bunyan.createLogger({
  name: 'LS_NODE',
  serializers: {
    req: bunyan.stdSerializers.req,
    res: bunyan.stdSerializers.res
  }
});

// view engine setup
app.set('views', path.join(__dirname, './app/views'));
app.use(express.static(path.join(__dirname, './app/public')));

//app.set('view engine', 'swig');
app.set('view engine', 'pug');
//app.locals.Sequelize = require("sequelize");
// var memcached = new Memcached(config.MEMCACHED);
app.use(function(req, res, next) {
   // global.memcached = memcached;
    next();
});

// ==============
// Create passport instance && JWT
// app.set('superSecret', "ThisislucstocksecretKeyforJWT");

var passport = require("passport");
require('./app/passport')(passport); // pass passport for configuration

var session = require('express-session');
var MemcachedStore = require('connect-memcached')(session);

app.use(session({
    secret: 'user_idnetity',
    name : 'user identity',
    resave : false,
    saveUninitialized : false,
    // store : new MemcachedStore({
    //     hosts : [config.MEMCACHED],
    //     secret : 'iloveluckstock.com!@#$%^'
    // }),
    cookie: { secure: true }
    }
));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
//module.exports = passport;
global.passport = passport;
app.use(flash()); // use connect-flash for flash messages stored in session
////// ====== END OF PASSPORT
app.use(compression());
app.use(cors());
app.use(helmet());
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
// app.use(express.static(path.join(__dirname, './client/static')));
// load config

app.set('configuration', config);

app.use(function(req, res, next) {
    res.setHeader('X-Powered-By', 'luckstock');
    next();
});

// extend app for route object mapping
app.map = (a, route) =>{
    route = route || '';
    for (var key in a) {
        if (Array.isArray(a[key])) {
            // get: [function(){ ... }]
            app[key](route, a[key]);
        } else if (typeof a[key] === 'object') {
            // { '/path': { ... }}
            //debug("key : ", key);
            app.map(a[key], route + key);
        } else if (typeof a[key] === 'function') {
            // get: function(){ ... }
            app[key](route, a[key]);
        }
    }
};

// bootstrap api
require('./index')(app);

// DONT REMOVE
//list all routes
// app._router.stack.forEach(function (r) {
// if (r.route && r.route.path) {
// console.log(r.route.path)
// }
// });

module.exports = app;
<commit_msg>setHeader<commit_after>var express = require('express');
var path = require('path');
//var logger = require('morgan');
var bodyParser = require('body-parser');
var cors = require('cors');
var helmet = require('helmet');
// var Memcached = require('memcached');
var compression = require('compression');
var config = require('./config');
var flash  = require('connect-flash');

// development, production or staging
require('dotenv').config({path: './config/.' +  process.env.NODE_ENV})

var debug = require('debug')('api');
var bunyan = require('bunyan');
var app = express();

global.log = bunyan.createLogger({
  name: 'LS_NODE',
  serializers: {
    req: bunyan.stdSerializers.req,
    res: bunyan.stdSerializers.res
  }
});

// view engine setup
app.set('views', path.join(__dirname, './app/views'));
app.use(express.static(path.join(__dirname, './app/public')));

//app.set('view engine', 'swig');
app.set('view engine', 'pug');
//app.locals.Sequelize = require("sequelize");
// var memcached = new Memcached(config.MEMCACHED);
app.use(function(req, res, next) {
   // global.memcached = memcached;
    next();
});

app.use(function (req, res, next) {
    res.setHeader("X-Powered-By", "user identity");
    next();
});

// ==============
// Create passport instance && JWT
// app.set('superSecret', "ThisislucstocksecretKeyforJWT");

var passport = require("passport");
require('./app/passport')(passport); // pass passport for configuration

var session = require('express-session');
var MemcachedStore = require('connect-memcached')(session);

app.use(session({
    secret: 'user_idnetity',
    name : 'user identity',
    resave : false,
    saveUninitialized : false,
    // store : new MemcachedStore({
    //     hosts : [config.MEMCACHED],
    //     secret : 'iloveluckstock.com!@#$%^'
    // }),
    cookie: { secure: true }
    }
));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
//module.exports = passport;
global.passport = passport;
app.use(flash()); // use connect-flash for flash messages stored in session
////// ====== END OF PASSPORT
app.use(compression());
app.use(cors());
app.use(helmet());
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
// app.use(express.static(path.join(__dirname, './client/static')));
// load config

app.set('configuration', config);

app.use(function(req, res, next) {
    res.setHeader('X-Powered-By', 'luckstock');
    next();
});

// extend app for route object mapping
app.map = (a, route) =>{
    route = route || '';
    for (var key in a) {
        if (Array.isArray(a[key])) {
            // get: [function(){ ... }]
            app[key](route, a[key]);
        } else if (typeof a[key] === 'object') {
            // { '/path': { ... }}
            //debug("key : ", key);
            app.map(a[key], route + key);
        } else if (typeof a[key] === 'function') {
            // get: function(){ ... }
            app[key](route, a[key]);
        }
    }
};

// bootstrap api
require('./index')(app);

// DONT REMOVE
//list all routes
// app._router.stack.forEach(function (r) {
// if (r.route && r.route.path) {
// console.log(r.route.path)
// }
// });

module.exports = app;
<|endoftext|>


<commit_before>//Set up Reqs
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var qs = require('querystring');

//Server Details
var app = express();
var port = process.env.PORT || 3000;

//Set Body Parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

//Routes
app.get('/', function(req, res){
	res.send('here');
});

app.post('/collect', function(req, res){

	var channel = {
		id: 	req.body.channel_id,
		name: 	req.body.channel_name
	};
	var user = {
		id: 	req.body.user_id
	};

	var msgText = req.body.text;

	function searchM(regex){
		var searchStr = msgText.match(regex);
		if(searchStr != null){
			return searchStr.length;
		}
		return 0;
	};

	function searchS(regex){
		var searchStr = msgText.split(regex);
		if(searchStr != undefined){
			return searchStr.length;
		}
		return 0;
	};

	var wordCount = searchS(/\s+\b/);
	var emojiCount = searchM(/:[a-z_0-9]*:/g);
	var exclaCount = searchM(/!/g);
	var questionMark = searchM(/\?/g);
	var elipseCount = searchM(/\.\.\./g)
	//still in the works
	//var letterCount = msgText.length
	//console.log(msgText.length)

	//Structure Data
	var data = {
		v: 		1,
		tid: 	"UA-61435895-1",
		cid: 	user.id,
		ds:  	"slack", //data source
		cd1: 	user.id,
		cd2: 	channel.name,
		cd3: 	msgText,
		cm1: 	wordCount,
		cm2: 	emojiCount,
		cm3: 	exclaCount,
	//	cm4: 	letterCount,
		cm5: 	elipseCount,
		cm6: 	questionMark, //need to set up in GA
		t: 		"event",
		ec: 	"slack: "+ channel.name + "|" + req.body.channel_id,
		ea: 	"post by " + "|"+req.body.user_id,
		el: 	msgText,
		ev: 	1
	};
	console.log(JSON.stringify(data));
	console.log(req.body);
	//Make Post Request
	request.post("https://www.google-analytics.com/collect?" + qs.stringify(data),
		function(error, resp, body){
		console.log(error);
	})
});
function textSearch (str,regex) {
	return str.match(regex).length
}

//Start Server
app.listen(port, function () {
	console.log('Listening on port ' + port);
});<commit_msg>small fixes<commit_after>//Set up Reqs
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var qs = require('querystring');

//Server Details
var app = express();
var port = process.env.PORT || 3000;

//Set Body Parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

//Routes
app.get('/', function(req, res){
	res.send('here');
});

app.post('/collect', function(req, res){

	var channel = {
		id: 	req.body.channel_id,
		name: 	req.body.channel_name
	};
	var user = {
		id: 	req.body.user_id
	};

	var msgText = req.body.text;

	function searchM(regex){
		var searchStr = msgText.match(regex);
		if(searchStr != null){
			return searchStr.length;
		}
		return 0;
	};

	function searchS(regex){
		var searchStr = msgText.split(regex);
		if(searchStr != undefined){
			return searchStr.length;
		}
		return 0;
	};

	var wordCount = searchS(/\s+\b/);
	var emojiCount = searchM(/:[a-z_0-9]*:/g);
	var exclaCount = searchM(/!/g);
	var questionMark = searchM(/\?/g);
	var elipseCount = searchM(/\.\.\./g);
	//still in the works
	//var letterCount = msgText.length
	//console.log(msgText.length)

	//Structure Data
	var data = {
		v: 		1,
		tid: 	"UA-61435895-1",
		cid: 	user.id,
		ds:  	"slack", //data source
		cd1: 	user.id,
		cd2: 	channel.name,
		cd3: 	msgText,
		cm1: 	wordCount,
		cm2: 	emojiCount,
		cm3: 	exclaCount,
	//	cm4: 	letterCount,
		cm5: 	elipseCount,
		cm6: 	questionMark, //need to set up in GA
		t: 		"event",
		ec: 	"slack: "+ channel.name + "|" + req.body.channel_id,
		ea: 	"post by " + "|"+req.body.user_id,
		el: 	msgText,
		ev: 	1
	};
	console.log(JSON.stringify(data));
	console.log(req.body);
	//Make Post Request
	request.post("https://www.google-analytics.com/collect?" + qs.stringify(data),
		function(error, resp, body){
		console.log(error);
	})
});
function textSearch (str,regex) {
	return str.match(regex).length
}

//Start Server
app.listen(port, function () {
	console.log('Listening on port ' + port);
});<|endoftext|>


<commit_before>const express = require('express'),
  ProtoBuf = require('protobufjs'),
  bodyParser = require('body-parser'),
  lzString = require('lz-string'),
  db = require('./db.js');

var app = express(),
  messages = ProtoBuf.loadJsonFile('messages.json').build();

// Set up middleware.
app.enable('trust proxy');
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept');
  next();
});
app.use(bodyParser.raw());

// Legacy API conversions
const AGE = {
    'Under 15': messages.bikemoves.User.Age.AGE_UNDER_15,
    '15 to 19': messages.bikemoves.User.Age.AGE_15_TO_19,
    '20 to 24': messages.bikemoves.User.Age.AGE_20_TO_24,
    '25 to 34': messages.bikemoves.User.Age.AGE_25_TO_34,
    '35 to 44': messages.bikemoves.User.Age.AGE_35_TO_44,
    '45 to 54': messages.bikemoves.User.Age.AGE_45_TO_54,
    '55 to 64': messages.bikemoves.User.Age.AGE_55_TO_64,
    '65 to 74': messages.bikemoves.User.Age.AGE_65_TO_74,
    '75 and Older': messages.bikemoves.User.Age.AGE_75_AND_OLDER
  },
  EXPERIENCE_LEVEL = {
    'Beginner': messages.bikemoves.User.ExperienceLevel.BEGINNER,
    'Intermediate': messages.bikemoves.User.ExperienceLevel.INTERMEDIATE,
    'Advanced': messages.bikemoves.User.ExperienceLevel.ADVANCED
  },
  GENDER = {
    'Male': messages.bikemoves.User.Gender.MALE,
    'Female': messages.bikemoves.User.Gender.FEMALE,
    'Other': messages.bikemoves.User.Gender.OTHER
  },
  LOCATION_TYPE = {
    'Home': messages.bikemoves.Trip.LocationType.HOME,
    'Work': messages.bikemoves.Trip.LocationType.WORK,
    'K-12 School': messages.bikemoves.Trip.LocationType.K12_SCHOOL,
    'University': messages.bikemoves.Trip.LocationType.UNIVERSITY,
    'Shopping': messages.bikemoves.Trip.LocationType.SHOPPING,
    'Other':  messages.bikemoves.Trip.LocationType.OTHER
  };

var messageFromData = function(body, Message) {
  if (!body.data) throw 'Data key is empty';
  var data = JSON.parse(lzString.decompressFromBase64(
    JSON.stringify(body.data)));
  if (!data.deviceUUID) throw 'Missing device UUID';

  data.deviceUuid = data.deviceUUID;
  delete data.deviceUUID;

  if ('age' in data) data.age = AGE[data.age] || 0;
  if ('cyclingExperience' in data) data.cyclingExperience =
    EXPERIENCE_LEVEL[data.cyclingExperience] || 0;
  if ('gender' in data) data.gender = GENDER[data.gender] || 0;
  if ('origin' in data) data.origin = LOCATION_TYPE[data.origin] || 0;
  if ('destination' in data) data.destination =
    LOCATION_TYPE[data.destination] || 0;
};

// Helper functions
var extractMessage = function(req, Message) {
    if (!req.body) throw 'Missing post data';
    try {
      return Message.decode(req.body);
    } catch(e) {
      console.error(e.stack);
      throw 'Malformed request';
    }
  };

app.post('/:version/user', function(req, res) {
  var userMsg = (req.params.version == 'v0.1') ?
    messageFromData(req.body, messages.bikemoves.User) :
    extractMessage(req, messages.bikemoves.User);
  db.User.upsert(userMsg).then(function(createdUser) {
    res.send(((createdUser) ? 'Created' : 'Updated') + ' user');
  }).catch(function(e) {
    console.error(e.stack);
    res.status(500).send('Error saving user');
  });
});

app.post('/:version/trip', function(req, res) {
  var tripMsg = (req.params.version == 'v0.1') ?
    messageFromData(req.body, messages.bikemoves.Trip) :
    extractMessage(req, messages.bikemoves.Trip);
  db.User.findOrCreate({
    where: {deviceUUID: tripMsg.deviceUuid}
  }).spread(function(user, created) {
    return db.Trip.create(db.Trip.fromMessage(tripMsg, user.id));
  }).then(function(trip) {
    return db.Point.bulkCreate(db.Point.fromTripMessage(tripMsg, trip.id));
  }).then(function() {
    res.send('Saved trip');
  }).catch(function(e) {
    console.error(e.stack);
    res.status(500).send('Error saving trip');
  });
});

app.listen(8888);
<commit_msg>Use different middleware depending on the API version.<commit_after>const express = require('express'),
  ProtoBuf = require('protobufjs'),
  bodyParser = require('body-parser'),
  lzString = require('lz-string'),
  db = require('./db.js');

var app = express(),
  messages = ProtoBuf.loadJsonFile('messages.json').build();

// Set up middleware.
app.enable('trust proxy');
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept');
  next();
});
app.use('/v0.1/*', bodyParser.json());
app.use('/v0.2/*', bodyParser.raw());

// Legacy API conversions
const AGE = {
    'Under 15': messages.bikemoves.User.Age.AGE_UNDER_15,
    '15 to 19': messages.bikemoves.User.Age.AGE_15_TO_19,
    '20 to 24': messages.bikemoves.User.Age.AGE_20_TO_24,
    '25 to 34': messages.bikemoves.User.Age.AGE_25_TO_34,
    '35 to 44': messages.bikemoves.User.Age.AGE_35_TO_44,
    '45 to 54': messages.bikemoves.User.Age.AGE_45_TO_54,
    '55 to 64': messages.bikemoves.User.Age.AGE_55_TO_64,
    '65 to 74': messages.bikemoves.User.Age.AGE_65_TO_74,
    '75 and Older': messages.bikemoves.User.Age.AGE_75_AND_OLDER
  },
  EXPERIENCE_LEVEL = {
    'Beginner': messages.bikemoves.User.ExperienceLevel.BEGINNER,
    'Intermediate': messages.bikemoves.User.ExperienceLevel.INTERMEDIATE,
    'Advanced': messages.bikemoves.User.ExperienceLevel.ADVANCED
  },
  GENDER = {
    'Male': messages.bikemoves.User.Gender.MALE,
    'Female': messages.bikemoves.User.Gender.FEMALE,
    'Other': messages.bikemoves.User.Gender.OTHER
  },
  LOCATION_TYPE = {
    'Home': messages.bikemoves.Trip.LocationType.HOME,
    'Work': messages.bikemoves.Trip.LocationType.WORK,
    'K-12 School': messages.bikemoves.Trip.LocationType.K12_SCHOOL,
    'University': messages.bikemoves.Trip.LocationType.UNIVERSITY,
    'Shopping': messages.bikemoves.Trip.LocationType.SHOPPING,
    'Other':  messages.bikemoves.Trip.LocationType.OTHER
  };

var messageFromData = function(body, Message) {
  if (!body.data) throw 'Data key is empty';
  var data = JSON.parse(lzString.decompressFromBase64(body.data));
  if (!data.deviceUUID) throw 'Missing device UUID';

  data.deviceUuid = data.deviceUUID;
  delete data.deviceUUID;

  if ('age' in data) data.age = AGE[data.age] || 0;
  if ('cyclingExperience' in data) data.cyclingExperience =
    EXPERIENCE_LEVEL[data.cyclingExperience] || 0;
  if ('gender' in data) data.gender = GENDER[data.gender] || 0;
  if ('origin' in data) data.origin = LOCATION_TYPE[data.origin] || 0;
  if ('destination' in data) data.destination =
    LOCATION_TYPE[data.destination] || 0;
};

// Helper functions
var extractMessage = function(req, Message) {
    if (!req.body) throw 'Missing post data';
    try {
      return Message.decode(req.body);
    } catch(e) {
      console.error(e.stack);
      throw 'Malformed request';
    }
  };

app.post('/:version/user', function(req, res) {
  var userMsg = (req.params.version == 'v0.1') ?
    messageFromData(req.body, messages.bikemoves.User) :
    extractMessage(req, messages.bikemoves.User);
  db.User.upsert(userMsg).then(function(createdUser) {
    res.send(((createdUser) ? 'Created' : 'Updated') + ' user');
  }).catch(function(e) {
    console.error(e.stack);
    res.status(500).send('Error saving user');
  });
});

app.post('/:version/trip', function(req, res) {
  var tripMsg = (req.params.version == 'v0.1') ?
    messageFromData(req.body, messages.bikemoves.Trip) :
    extractMessage(req, messages.bikemoves.Trip);
  db.User.findOrCreate({
    where: {deviceUUID: tripMsg.deviceUuid}
  }).spread(function(user, created) {
    return db.Trip.create(db.Trip.fromMessage(tripMsg, user.id));
  }).then(function(trip) {
    return db.Point.bulkCreate(db.Point.fromTripMessage(tripMsg, trip.id));
  }).then(function() {
    res.send('Saved trip');
  }).catch(function(e) {
    console.error(e.stack);
    res.status(500).send('Error saving trip');
  });
});

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


<commit_before>'use strict';

function makeGridTable(board) {

  var size = board.size;

  var domTarget = document.getElementById('grid_table');
  var table = document.createElement('table');

  for (var i = 0; i < size; i++) {
    var row = document.createElement('tr');

    for (var j = 0; j < size; j++) {
      var square = document.createElement('td');
      square.textContent = ' ';

      row.appendChild(square);
      board.addRef(i,j,square);

    }
    table.appendChild(row);
  }
  domTarget.appendChild(table);
}

Coord.prototype.checkSub = function () {
  if (this.sub){
    this.status = 'hit';
    this.squareRef.textContent = 'X';
    return true;
  }
  this.status = 'miss';
  this.squareRef.textContent = 'O';
  return false;
};

function GameBoard(size) {
  if (localStorage.getItem('board') === null){
    this.size = size;
    this.grid = [];
    this.setupBoard(size);
    this.save();
    console.log('being created');
  }else {
    console.log('being restored');
    this.restore();
    this.setupBoard(size);
  }
}

GameBoard.prototype.save = function() {
  localStorage.setItem('board', JSON.stringify(this));
};

GameBoard.prototype.restore = function(){
  var boardProps = JSON.parse(localStorage.getItem('board'));
  for (var key in boardProps) {
    if (boardProps.hasOwnProperty(key)) {
      this[key] = boardProps[key];
    }
  }
};

GameBoard.prototype.updateBoard = function () {
  for (var i = 0; i < this.size; i++) {
    for (var j = 0; j < this.size; j++) {
      var status = this.grid[i][j].status ;
      var squareRef = this.grid[i][j].squareRef;

      if(status === 'miss'){
        squareRef.textContent = 'O';
      }else if(status === 'hit'){
        squareRef.textContent = 'X';
      }
    }
  }
};

GameBoard.prototype.setupBoard = function (size) {
  this.createGrid(size);
};

GameBoard.prototype.addRef = function (i,j,ref) {
  this.grid[i][j].squareRef = ref;
};

//make table
GameBoard.prototype.createGrid = function (size) {
  if(this.grid.length === 0) {
    for (var i = 0; i < size; i++) {
      var row = [];
      for (var j = 0; j < size; j++) {
        row.push(new Coord());
      }
      this.grid.push(row);
    }
  }else {
    for (i = 0; i < size; i++) {
      for (j = 0; j < size; j++) {
        this.grid[i][j] = new Coord(this.grid[i][j]);
      }
    }
  }
};

GameBoard.prototype.addSub = function (x, y) {
  //subtract one so that grid coordinates start at 1.
  this.grid[x][y].sub = true;
};

GameBoard.prototype.guessed = function (x,y) {
  //subtract one so that grid coordinates start at 1.
  return this.grid[x - 1][y - 1].checkSub();
};

function Coord (object) {
  if(object) {
    for (var key in object) {
      if (object.hasOwnProperty(key)) {
        this[key] = object[key];
      }
    }
  }else {
    //the default is unseen; once coordinate is picked, status ==== hit || miss.
    this.status = 'unseen';
    //this tells whether there is a sub at this location.
    this.sub = false;
  }
}

var board = new GameBoard(10);
makeGridTable(board);
board.updateBoard();

// paste from player.js
var score = 0;

function Sub(length) {
  if (localStorage.getItem('sub') === null) {
    this.alive = true;
    this.length = length;
    this.lifePoints = this.length;
    this.orientation = this.getOriention();
    this.location = this.getLocation();
    this.save();
  } else {
    this.restore();
  }
  this.addToBoard();
}

Sub.prototype.save = function() {
  localStorage.setItem('sub', JSON.stringify(this));
};

Sub.prototype.restore = function(){
  var subProps = JSON.parse(localStorage.getItem('sub'));
  for (var key in subProps) {
    if (subProps.hasOwnProperty(key)) {
      this[key] = subProps[key];
    }
  }
};

Sub.prototype.getOriention = function() {
  var coin = Math.round(Math.random());
  if (coin) {
    return 'north-south';
  } else {
    return 'east-west';
  }
};

Sub.prototype.hit = function() {
  this.lifePoints--;
  if (this.lifePoints === 0) {
    this.alive = false;
  }
  this.save();
};

Sub.prototype.addToBoard = function() {
  // setting physical location of sub on board.
  var x = this.location[0];
  var y = this.location[1];
  for (var i = 0; i < this.length; i++) {
    console.log(x,y);
    board.addSub(x, y);
    if (this.orientation === 'north-south') {
      y++;
    } else {
      x++;
    }
  }
  board.save();
};

Sub.prototype.getLocation = function() {
  var offsetX = 0;
  var offsetY = 0;
  if (this.orientation === 'north-south') {
    offsetY = this.length - 1;
  } else {
    offsetX = this.length - 1;
  }
  var x = Math.floor(Math.random() * (board.size - offsetX));
  var y = Math.floor(Math.random() * (board.size - offsetY));
  return [x, y];
};

var sub = new Sub(3);

var count = 10;

function Player() {
  if (localStorage.getItem('player') === null) {
    this.name = name;
    this.score = score;
    this.turns = [];
    this.save();
  }else {
    this.restore();
  }
}

Player.prototype.save = function() {
  localStorage.setItem('player', JSON.stringify(this));
};

Player.prototype.restore = function(){
  var playerProps = JSON.parse(localStorage.getItem('player'));
  for (var key in playerProps) {
    if (playerProps.hasOwnProperty(key)) {
      this[key] = playerProps[key];
    }
  }
};

Player.prototype.attack = function(x, y) {
  var result = board.guessed(x, y);
  board.save();
  if(result === true) {
    // Game Over!
    sub.hit();
    alert('Hit!');
    player.updateScore();
    if(sub.alive === false) {
      alert('You destroyed the sub!');
      player.updateScore();
      fire.removeEventListener('submit', fireMissles);
    }
  } else {
    alert('Miss!');
  }
  this.turns.push([x, y]);
  this.save();
};
var total = 0;
Player.prototype.updateScore = function() {
  score = count;
  total += score;
  var scoreboard = document.getElementById('scoreboard');
  scoreboard.textContent = total;
};

var player = new Player();

var fire = document.getElementById('fire');
fire.addEventListener('submit', fireMissles);

function fireMissles (event) {
  if (count === 0) {
    alert('You Lose!');
    fire.removeEventListener('submit', fireMissles);
  }
  event.preventDefault();
  event.stopPropagation();
  var x = parseInt(event.target.x.value);
  var y = parseInt(event.target.y.value);
  player.attack(x, y);
  count--;
  console.log(count);
}
<commit_msg>fixed repeated coordinate win bug<commit_after>'use strict';

function makeGridTable(board) {

  var size = board.size;

  var domTarget = document.getElementById('grid_table');
  var table = document.createElement('table');

  for (var i = 0; i < size; i++) {
    var row = document.createElement('tr');

    for (var j = 0; j < size; j++) {
      var square = document.createElement('td');
      square.textContent = ' ';

      row.appendChild(square);
      board.addRef(i,j,square);

    }
    table.appendChild(row);
  }
  domTarget.appendChild(table);
}

Coord.prototype.checkSub = function () {
  if (this.status == 'unseen') {
    if (this.sub){
      this.status = 'hit';
      this.squareRef.textContent = 'X';
      return true;
    }
    this.status = 'miss';
    this.squareRef.textContent = 'O';
    return false;
  }
  else {
    alert('You need to pick a different square!');
    return false;
  }
};

function GameBoard(size) {
  if (localStorage.getItem('board') === null){
    this.size = size;
    this.grid = [];
    this.setupBoard(size);
    this.save();
    console.log('being created');
  }else {
    console.log('being restored');
    this.restore();
    this.setupBoard(size);
  }
}

GameBoard.prototype.save = function() {
  localStorage.setItem('board', JSON.stringify(this));
};

GameBoard.prototype.restore = function(){
  var boardProps = JSON.parse(localStorage.getItem('board'));
  for (var key in boardProps) {
    if (boardProps.hasOwnProperty(key)) {
      this[key] = boardProps[key];
    }
  }
};

GameBoard.prototype.updateBoard = function () {
  for (var i = 0; i < this.size; i++) {
    for (var j = 0; j < this.size; j++) {
      var status = this.grid[i][j].status ;
      var squareRef = this.grid[i][j].squareRef;

      if(status === 'miss'){
        squareRef.textContent = 'O';
      }else if(status === 'hit'){
        squareRef.textContent = 'X';
      }
    }
  }
};

GameBoard.prototype.setupBoard = function (size) {
  this.createGrid(size);
};

GameBoard.prototype.addRef = function (i,j,ref) {
  this.grid[i][j].squareRef = ref;
};

//make table
GameBoard.prototype.createGrid = function (size) {
  if(this.grid.length === 0) {
    for (var i = 0; i < size; i++) {
      var row = [];
      for (var j = 0; j < size; j++) {
        row.push(new Coord());
      }
      this.grid.push(row);
    }
  }else {
    for (i = 0; i < size; i++) {
      for (j = 0; j < size; j++) {
        this.grid[i][j] = new Coord(this.grid[i][j]);
      }
    }
  }
};

GameBoard.prototype.addSub = function (x, y) {
  //subtract one so that grid coordinates start at 1.
  this.grid[x][y].sub = true;
};

GameBoard.prototype.guessed = function (x,y) {
  //subtract one so that grid coordinates start at 1.
  return this.grid[x - 1][y - 1].checkSub();
};

function Coord (object) {
  if(object) {
    for (var key in object) {
      if (object.hasOwnProperty(key)) {
        this[key] = object[key];
      }
    }
  }else {
    //the default is unseen; once coordinate is picked, status ==== hit || miss.
    this.status = 'unseen';
    //this tells whether there is a sub at this location.
    this.sub = false;
  }
}

var board = new GameBoard(10);
makeGridTable(board);
board.updateBoard();

// paste from player.js
var score = 0;

function Sub(length) {
  if (localStorage.getItem('sub') === null) {
    this.alive = true;
    this.length = length;
    this.lifePoints = this.length;
    this.orientation = this.getOriention();
    this.location = this.getLocation();
    this.save();
  } else {
    this.restore();
  }
  this.addToBoard();
}

Sub.prototype.save = function() {
  localStorage.setItem('sub', JSON.stringify(this));
};

Sub.prototype.restore = function(){
  var subProps = JSON.parse(localStorage.getItem('sub'));
  for (var key in subProps) {
    if (subProps.hasOwnProperty(key)) {
      this[key] = subProps[key];
    }
  }
};

Sub.prototype.getOriention = function() {
  var coin = Math.round(Math.random());
  if (coin) {
    return 'north-south';
  } else {
    return 'east-west';
  }
};

Sub.prototype.hit = function() {
  this.lifePoints--;
  if (this.lifePoints === 0) {
    this.alive = false;
  }
  this.save();
};

Sub.prototype.addToBoard = function() {
  // setting physical location of sub on board.
  var x = this.location[0];
  var y = this.location[1];
  for (var i = 0; i < this.length; i++) {
    console.log(x,y);
    board.addSub(x, y);
    if (this.orientation === 'north-south') {
      y++;
    } else {
      x++;
    }
  }
  board.save();
};

Sub.prototype.getLocation = function() {
  var offsetX = 0;
  var offsetY = 0;
  if (this.orientation === 'north-south') {
    offsetY = this.length - 1;
  } else {
    offsetX = this.length - 1;
  }
  var x = Math.floor(Math.random() * (board.size - offsetX));
  var y = Math.floor(Math.random() * (board.size - offsetY));
  return [x, y];
};

var sub = new Sub(3);

var count = 10;

function Player() {
  if (localStorage.getItem('player') === null) {
    this.name = name;
    this.score = score;
    this.turns = [];
    this.save();
  }else {
    this.restore();
  }
}

Player.prototype.save = function() {
  localStorage.setItem('player', JSON.stringify(this));
};

Player.prototype.restore = function(){
  var playerProps = JSON.parse(localStorage.getItem('player'));
  for (var key in playerProps) {
    if (playerProps.hasOwnProperty(key)) {
      this[key] = playerProps[key];
    }
  }
};

Player.prototype.attack = function(x, y) {
  var result = board.guessed(x, y);
  board.save();
  if(result === true) {
    // Game Over!
    sub.hit();
    alert('Hit!');
    player.updateScore();
    if(sub.alive === false) {
      alert('You destroyed the sub!');
      player.updateScore();
      fire.removeEventListener('submit', fireMissles);
    }
  } else {
    alert('Miss!');
  }
  this.turns.push([x, y]);
  this.save();
};
var total = 0;
Player.prototype.updateScore = function() {
  score = count;
  total += score;
  var scoreboard = document.getElementById('scoreboard');
  scoreboard.textContent = total;
};

var player = new Player();

var fire = document.getElementById('fire');
fire.addEventListener('submit', fireMissles);

function fireMissles (event) {
  if (count === 0) {
    alert('You Lose!');
    fire.removeEventListener('submit', fireMissles);
  }
  event.preventDefault();
  event.stopPropagation();
  var x = parseInt(event.target.x.value);
  var y = parseInt(event.target.y.value);
  player.attack(x, y);
  count--;
  console.log(count);
}
<|endoftext|>


<commit_before>chrome.storage.local.get(['pattern', 'case_insensitive', 'color', 'opacity'], function(items) {
  var pattern, case_insensitive, color, opacity;
  var re, flags;

  pattern = items.pattern;
  if (!pattern) {
    pattern = 'WIP';
  }

  case_insensitive = !!items.case_insensitive;
  if (case_insensitive) {
    flags = 'i';
  } else {
    flags = '';
  }

  re = new RegExp(pattern, flags);

  color   = items.color   || 'lightgray';
  opacity = items.opacity || 0.7;

  var unhighlighter = function(element, re, color, opacity) {
    if (element.querySelector('.list-group-item-name').innerText.match(re)) {
      element.style.backgroundColor = color;
      element.style.opacity = opacity;
    }
  };

  var target = document.querySelector('body');
  var config = {
    childList: true,
    subtree: true
  };

  var observer = new MutationObserver(function(mutations, self) {
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        var elements = document.querySelectorAll('.pulls-list-group li.list-group-item');

        Array.prototype.forEach.call(elements, function(element) {
          unhighlighter(element, re, color, opacity);
        });
      }
    });
  });

  observer.observe(target, config);
});
<commit_msg>get back issue elements<commit_after>chrome.storage.local.get(['pattern', 'case_insensitive', 'color', 'opacity'], function(items) {
  var pattern, case_insensitive, color, opacity;
  var re, flags;

  pattern = items.pattern;
  if (!pattern) {
    pattern = 'WIP';
  }

  case_insensitive = !!items.case_insensitive;
  if (case_insensitive) {
    flags = 'i';
  } else {
    flags = '';
  }

  re = new RegExp(pattern, flags);

  color   = items.color   || 'lightgray';
  opacity = items.opacity || 0.7;

  var unhighlighter = function(element, re, color, opacity) {
    if (element.querySelector('.issue-title-link').innerText.match(re)) {
      element.style.backgroundColor = color;
      element.style.opacity = opacity;
    }
  };

  var target = document.querySelector('body');
  var config = {
    childList: true,
    subtree: true
  };

  var observer = new MutationObserver(function(mutations, self) {
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList') {
        var elements = document.querySelectorAll('ul.table-list-issues li.table-list-item');

        Array.prototype.forEach.call(elements, function(element) {
          unhighlighter(element, re, color, opacity);
        });
      }
    });
  });

  observer.observe(target, config);
});
<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require('compression');
const redis = require('redis');
const connectRedis = require('connect-redis');
const session = require('express-session');
const methodOverride = require('method-override');
const csurf = require('csurf');
const handlebars = require('handlebars');
const layouts = require('handlebars-layouts');
const handlebarsWax = require('handlebars-wax');
const Sentry = require('@sentry/node');
const { Configuration } = require('@schul-cloud/commons');
const { tokenInjector, duplicateTokenHandler, csrfErrorHandler } = require('./helpers/csrf');

const { version } = require('./package.json');
const { sha } = require('./helpers/version');
const logger = require('./helpers/logger');

const {
	KEEP_ALIVE,
	SENTRY_DSN,
	SC_DOMAIN,
	SC_THEME,
	REDIS_URI,
	JWT_SHOW_TIMEOUT_WARNING_SECONDS,
	JWT_TIMEOUT_SECONDS,
	BACKEND_URL,
	PUBLIC_BACKEND_URL,
} = require('./config/global');

const app = express();
const Config = new Configuration();
Config.init(app);

if (SENTRY_DSN) {
	Sentry.init({
		dsn: SENTRY_DSN,
		environment: app.get('env'),
		release: version,
		integrations: [
			new Sentry.Integrations.Console(),
		],
	});
	Sentry.configureScope((scope) => {
		scope.setTag('frontend', false);
		scope.setLevel('warning');
		scope.setTag('domain', SC_DOMAIN);
		scope.setTag('sha', sha);
	});
	app.use(Sentry.Handlers.requestHandler());
}

// template stuff
const authHelper = require('./helpers/authentication');

// set custom response header for ha proxy
if (KEEP_ALIVE) {
	app.use((req, res, next) => {
		res.setHeader('Connection', 'Keep-Alive');
		next();
	});
}

// set security headers
const securityHeaders = require('./middleware/security_headers');

app.use(securityHeaders);

// set cors headers
const cors = require('./middleware/cors');

app.use(cors);

app.use(compression());
app.set('trust proxy', true);
const themeName = SC_THEME;
// view engine setup
const handlebarsHelper = require('./helpers/handlebars');

const wax = handlebarsWax(handlebars)
	.partials(path.join(__dirname, 'views/**/*.{hbs,js}'))
	.helpers(layouts)
	.helpers(handlebarsHelper.helpers(app));

wax.partials(path.join(__dirname, `theme/${themeName}/views/**/*.{hbs,js}`));

const viewDirs = [path.join(__dirname, 'views')];
viewDirs.unshift(path.join(__dirname, `theme/${themeName}/views/`));

app.set('views', viewDirs);
app.engine('hbs', wax.engine);
app.set('view engine', 'hbs');

app.set('view cache', true);

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(morgan('dev', {
	skip(req, res) {
		return req && ((req.route || {}).path || '').includes('tsp-login');
	},
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, `build/${themeName}`)));

let sessionStore;
const redisUrl = REDIS_URI;
if (redisUrl) {
	logger.info(`Using Redis session store at '${redisUrl}'.`);
	const RedisStore = connectRedis(session);
	const client = redis.createClient({
		url: redisUrl,
	});
	sessionStore = new RedisStore({ client });
} else {
	logger.info('Using in-memory session store.');
	sessionStore = new session.MemoryStore();
}

app.use(session({
	cookie: { maxAge: 1000 * 60 * 60 * 6 },
	rolling: true, // refresh session with every request within maxAge
	store: sessionStore,
	saveUninitialized: true,
	resave: false,
	secret: 'secret', // only used for cookie encryption; the cookie does only contain the session id though
}));

// CSRF middlewares
app.use(duplicateTokenHandler);
app.use(csurf());
app.use(tokenInjector);

const setTheme = require('./helpers/theme');

function removeIds(url) {
	const checkForHexRegExp = /[a-f\d]{24}/ig;
	return url.replace(checkForHexRegExp, 'ID');
}

// Custom flash middleware
app.use(async (req, res, next) => {
	// if there's a flash message in the session request, make it available in the response, then delete it
	res.locals.notification = req.session.notification;
	res.locals.inline = req.query.inline || false;
	setTheme(res);
	res.locals.domain = SC_DOMAIN;
	res.locals.production = req.app.get('env') === 'production';
	res.locals.env = req.app.get('env') || false; // TODO: ist das false hier nicht quatsch?
	res.locals.SENTRY_DSN = SENTRY_DSN;
	res.locals.JWT_SHOW_TIMEOUT_WARNING_SECONDS = Number(JWT_SHOW_TIMEOUT_WARNING_SECONDS);
	res.locals.JWT_TIMEOUT_SECONDS = Number(JWT_TIMEOUT_SECONDS);
	res.locals.BACKEND_URL = PUBLIC_BACKEND_URL || BACKEND_URL;
	res.locals.version = version;
	res.locals.sha = sha;
	delete req.session.notification;
	try {
		await authHelper.populateCurrentUser(req, res);
	} catch (error) {
		logger.error('could not populate current user', error);
		return next(error);
	}
	if (SENTRY_DSN) {
		Sentry.configureScope((scope) => {
			if (res.locals.currentUser) {
				scope.setTag({ schoolId: res.locals.currentUser.schoolId });
			}
			const { url, header } = req;
			scope.request = { url: removeIds(url), header };
		});
	}
	return next();
});

app.use(methodOverride('_method')); // for GET requests
app.use(methodOverride((req, res, next) => { // for POST requests
	if (req.body && typeof req.body === 'object' && '_method' in req.body) {
		// eslint-disable-next-line no-underscore-dangle
		const method = req.body._method;
		// eslint-disable-next-line no-underscore-dangle
		delete req.body._method;
		return method;
	}
}));

// Initialize the modules and their routes
app.use(require('./controllers/'));

app.get('/', (req, res, next) => {
	res.redirect('/login/');
});

// sentry error handler
app.use(Sentry.Handlers.errorHandler());

// catch 404 and forward to error handler
app.use((req, res, next) => {
	const err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handlers
app.use(csrfErrorHandler);
app.use((err, req, res, next) => {
	// set locals, only providing error in development
	const status = err.status || err.statusCode || 500;
	if (err.statusCode && err.error) {
		res.setHeader('error-message', err.error.message);
		res.locals.message = err.error.message;
	} else {
		res.locals.message = err.message;
	}

	if (res.locals && res.locals.message.includes('ESOCKETTIMEDOUT') && err.options) {
		const message = `ESOCKETTIMEDOUT by route: ${err.options.baseUrl + err.options.uri}`;
		logger.warn(message);
		Sentry.captureMessage(message);
	}
	res.locals.error = req.app.get('env') === 'development' ? err : { status };

	if (res.locals.currentUser) res.locals.loggedin = true;
	// render the error page
	res.status(status);
	res.render('lib/error', {
		loggedin: res.locals.loggedin,
		inline: res.locals.inline ? true : !res.locals.loggedin,
	});
});

module.exports = app;
<commit_msg>custom error message for timeouts added<commit_after>const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require('compression');
const redis = require('redis');
const connectRedis = require('connect-redis');
const session = require('express-session');
const methodOverride = require('method-override');
const csurf = require('csurf');
const handlebars = require('handlebars');
const layouts = require('handlebars-layouts');
const handlebarsWax = require('handlebars-wax');
const Sentry = require('@sentry/node');
const { Configuration } = require('@schul-cloud/commons');
const { tokenInjector, duplicateTokenHandler, csrfErrorHandler } = require('./helpers/csrf');

const { version } = require('./package.json');
const { sha } = require('./helpers/version');
const logger = require('./helpers/logger');

const {
	KEEP_ALIVE,
	SENTRY_DSN,
	SC_DOMAIN,
	SC_THEME,
	REDIS_URI,
	JWT_SHOW_TIMEOUT_WARNING_SECONDS,
	JWT_TIMEOUT_SECONDS,
	BACKEND_URL,
	PUBLIC_BACKEND_URL,
} = require('./config/global');

const app = express();
const Config = new Configuration();
Config.init(app);

if (SENTRY_DSN) {
	Sentry.init({
		dsn: SENTRY_DSN,
		environment: app.get('env'),
		release: version,
		integrations: [
			new Sentry.Integrations.Console(),
		],
	});
	Sentry.configureScope((scope) => {
		scope.setTag('frontend', false);
		scope.setLevel('warning');
		scope.setTag('domain', SC_DOMAIN);
		scope.setTag('sha', sha);
	});
	app.use(Sentry.Handlers.requestHandler());
}

// template stuff
const authHelper = require('./helpers/authentication');

// set custom response header for ha proxy
if (KEEP_ALIVE) {
	app.use((req, res, next) => {
		res.setHeader('Connection', 'Keep-Alive');
		next();
	});
}

// set security headers
const securityHeaders = require('./middleware/security_headers');

app.use(securityHeaders);

// set cors headers
const cors = require('./middleware/cors');

app.use(cors);

app.use(compression());
app.set('trust proxy', true);
const themeName = SC_THEME;
// view engine setup
const handlebarsHelper = require('./helpers/handlebars');

const wax = handlebarsWax(handlebars)
	.partials(path.join(__dirname, 'views/**/*.{hbs,js}'))
	.helpers(layouts)
	.helpers(handlebarsHelper.helpers(app));

wax.partials(path.join(__dirname, `theme/${themeName}/views/**/*.{hbs,js}`));

const viewDirs = [path.join(__dirname, 'views')];
viewDirs.unshift(path.join(__dirname, `theme/${themeName}/views/`));

app.set('views', viewDirs);
app.engine('hbs', wax.engine);
app.set('view engine', 'hbs');

app.set('view cache', true);

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(morgan('dev', {
	skip(req, res) {
		return req && ((req.route || {}).path || '').includes('tsp-login');
	},
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, `build/${themeName}`)));

let sessionStore;
const redisUrl = REDIS_URI;
if (redisUrl) {
	logger.info(`Using Redis session store at '${redisUrl}'.`);
	const RedisStore = connectRedis(session);
	const client = redis.createClient({
		url: redisUrl,
	});
	sessionStore = new RedisStore({ client });
} else {
	logger.info('Using in-memory session store.');
	sessionStore = new session.MemoryStore();
}

app.use(session({
	cookie: { maxAge: 1000 * 60 * 60 * 6 },
	rolling: true, // refresh session with every request within maxAge
	store: sessionStore,
	saveUninitialized: true,
	resave: false,
	secret: 'secret', // only used for cookie encryption; the cookie does only contain the session id though
}));

// CSRF middlewares
app.use(duplicateTokenHandler);
app.use(csurf());
app.use(tokenInjector);

const setTheme = require('./helpers/theme');

function removeIds(url) {
	const checkForHexRegExp = /[a-f\d]{24}/ig;
	return url.replace(checkForHexRegExp, 'ID');
}

// Custom flash middleware
app.use(async (req, res, next) => {
	// if there's a flash message in the session request, make it available in the response, then delete it
	res.locals.notification = req.session.notification;
	res.locals.inline = req.query.inline || false;
	setTheme(res);
	res.locals.domain = SC_DOMAIN;
	res.locals.production = req.app.get('env') === 'production';
	res.locals.env = req.app.get('env') || false; // TODO: ist das false hier nicht quatsch?
	res.locals.SENTRY_DSN = SENTRY_DSN;
	res.locals.JWT_SHOW_TIMEOUT_WARNING_SECONDS = Number(JWT_SHOW_TIMEOUT_WARNING_SECONDS);
	res.locals.JWT_TIMEOUT_SECONDS = Number(JWT_TIMEOUT_SECONDS);
	res.locals.BACKEND_URL = PUBLIC_BACKEND_URL || BACKEND_URL;
	res.locals.version = version;
	res.locals.sha = sha;
	delete req.session.notification;
	try {
		await authHelper.populateCurrentUser(req, res);
	} catch (error) {
		logger.error('could not populate current user', error);
		return next(error);
	}
	if (SENTRY_DSN) {
		Sentry.configureScope((scope) => {
			if (res.locals.currentUser) {
				scope.setTag({ schoolId: res.locals.currentUser.schoolId });
			}
			const { url, header } = req;
			scope.request = { url: removeIds(url), header };
		});
	}
	return next();
});

app.use(methodOverride('_method')); // for GET requests
app.use(methodOverride((req, res, next) => { // for POST requests
	if (req.body && typeof req.body === 'object' && '_method' in req.body) {
		// eslint-disable-next-line no-underscore-dangle
		const method = req.body._method;
		// eslint-disable-next-line no-underscore-dangle
		delete req.body._method;
		return method;
	}
}));

// Initialize the modules and their routes
app.use(require('./controllers/'));

app.get('/', (req, res, next) => {
	res.redirect('/login/');
});

// sentry error handler
app.use(Sentry.Handlers.errorHandler());

// catch 404 and forward to error handler
app.use((req, res, next) => {
	const err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handlers
app.use(csrfErrorHandler);
app.use((err, req, res, next) => {
	// set locals, only providing error in development
	const status = err.status || err.statusCode || 500;
	if (err.statusCode && err.error) {
		res.setHeader('error-message', err.error.message);
		res.locals.message = err.error.message;
	} else {
		res.locals.message = err.message;
	}

	if (res.locals && res.locals.message && res.locals.message.includes('ESOCKETTIMEDOUT') && err.options) {
		const message = `ESOCKETTIMEDOUT by route: ${err.options.baseUrl + err.options.uri}`;
		logger.warn(message);
		Sentry.captureMessage(message);
		res.locals.message = 'Es ist ein Fehler aufgetreten. Bitte versuche es erneut.'
	}
	res.locals.error = req.app.get('env') === 'development' ? err : { status };

	if (res.locals.currentUser) res.locals.loggedin = true;
	// render the error page
	res.status(status);
	res.render('lib/error', {
		loggedin: res.locals.loggedin,
		inline: res.locals.inline ? true : !res.locals.loggedin,
	});
});

module.exports = app;
<|endoftext|>


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

var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars');
var moment = require('moment');
var fs = require('fs');
var sqlite3 = require('sqlite3');
var randomstring = require('randomstring');
var bodyParser = require("body-parser");

var login = require('./routes/login');

var index = require('./routes/index');

var entry = require('./routes/entry');

var add = require('./routes/add');

var setting = require('./routes/setting');

var database = require('./routes/database');

// Example route
// var user = require('./routes/user');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// Add routes here
app.get('/', login.viewLogin);

app.get('/index', index.view);
app.get('/indexB', index.viewPlayButton);

app.get('/entry/:id', entry.viewEntry);

app.get('/add', add.viewAdd);

app.get('/setting', setting.viewSetting);

app.post('/login', login.saveLoginName);

app.post('/insertMemory', database.insertMemory);
app.post('/deleteMemory', database.deleteMemory);
app.post('/updateMemory', database.updateMemory);

app.post("/test", function(req,res){

  var data = String(req.body.data.toString().match(/,(.*)$/)[1]);
  var decodeData = new Buffer(data.toString(), 'base64');
  fs.writeFile('./test.webm', decodeData, function (err){
      if (err) return console.log(err);
   });
});

// Example route
// app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>remove parser<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars');
var moment = require('moment');
var fs = require('fs');
var sqlite3 = require('sqlite3');
var randomstring = require('randomstring');

var login = require('./routes/login');

var index = require('./routes/index');

var entry = require('./routes/entry');

var add = require('./routes/add');

var setting = require('./routes/setting');

var database = require('./routes/database');

// Example route
// var user = require('./routes/user');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// Add routes here
app.get('/', login.viewLogin);

app.get('/index', index.view);
app.get('/indexB', index.viewPlayButton);

app.get('/entry/:id', entry.viewEntry);

app.get('/add', add.viewAdd);

app.get('/setting', setting.viewSetting);

app.post('/login', login.saveLoginName);

app.post('/insertMemory', database.insertMemory);
app.post('/deleteMemory', database.deleteMemory);
app.post('/updateMemory', database.updateMemory);

app.post("/test", function(req,res){

  var data = String(req.body.data.toString().match(/,(.*)$/)[1]);
  var decodeData = new Buffer(data.toString(), 'base64');
  fs.writeFile('./test.webm', decodeData, function (err){
      if (err) return console.log(err);
   });
});

// Example route
// app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>