<commit_before>var express = require('express'),
	app = express(),
	server = require('http').createServer(app),
	io = require('socket.io').listen(server),
	path = require('path');

var port = process.env.PORT || 80;
server.listen(port);

/* io.configure(function () {
	io.set("transports", ["xhr-polling"]);
	io.set("polling duration", 10);
}); */

var rooms = {};

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

//POSTS
app.post('/test', function(req, res) {
	console.log('got make_room post');
	console.log(req.body);
	var map = req.body.map;
	var roomname;
	do{
		var crypto = require('crypto'),
			shasum = crypto.createHash('sha1');
		shasum.update('' + Math.random() + new Date().getTime());
		roomname = shasum.digest('hex');
	}while(rooms[roomname] !== undefined);
	rooms[roomname] = new Room(roomname);
	rooms[roomname].map = map;
	res.redirect('/room=' + roomname);
});

//GETS
app.get('/', function(req, res) {
	console.log('sent index');
	res.sendfile('index.html');
});
app.get('/room=:roomId', function(req, res) {
	var roomId = req.params.roomId;
	console.log('room id is: ' + roomId);
	if(rooms[roomId] !== undefined) {
		var mapurl = getMap(rooms[roomId].map);
		res.render('editor', {imgurl: mapurl});
	}
	else
		res.send('invalid room!');
});

function getMap(map) {
	switch(map) {
		case 'dust2':
			return 'imgs/de_dust2_radar_spectate.png';
			break;
		case 'inferno':
			return 'imgs/de_inferno_radar_spectate.png';
			break;
		case 'dust':
			return 'imgs/de_dust_radar_spectate.png';
			break;
		case 'train':
			return 'imgs/de_train_radar_spectate.png';
			break;
		case 'vertigo':
			return 'imgs/de_vertigo_radar.png';
			break;
		default:
			return 'imgs/de_dust2_radar_spectate_default.png';
			break;
	}
}

function Shape(id, type, x, y, points) {
	this.id = id;
	this.type = type;
	this.user = 'none';
	this.xPos = x;
	this.yPos = y;
	this.points = points;
	this.setX = function(newX) {
		this.xPos = newX;
	}
	this.setY = function(newY) {
		this.yPos = newY;
	}
}

function Player(name, num, img) {
	this.num = num;
	this.name = name;
	this.img = img;
	this.color;
	this.drawings = [];
}

function Room(name) {
	this.name = name;
	this.shapesBeingUsed = false;
	this.shapes = {};
	this.players = [];
	this.colors = ["#FF0000", "#0000FF", "#FF00FF", "#00FF00", "#FF6600"];
	this.getShapes = function() {
		return this.shapes;
	}
}

io.on('connection', function(socket) {
	socket.on('info', function(data){
		console.log('got here');
		if(rooms[data.room] === undefined) {
			console.log('BAD ROOM!');
			socket.disconnect();
			return;
		}
		//if(rooms[data.room] === undefined) rooms[data.room] = new Room(data.room);
		var pnum = rooms[data.room].players.length;
		var tmpname = 'player ' + pnum;
		var player = new Player(tmpname, pnum, 'http://upload.wikimedia.org/wikipedia/en/a/af/Question_mark.png');
		if(rooms[data.room].colors.length > 0)
			player.color = rooms[data.room].colors.pop();
		else player.color = "#FF0000";
		rooms[data.room].players.push(player);
		var crypto = require('crypto')
			, shasum = crypto.createHash('sha1');
		var timestamp = (new Date).getTime();
		console.log('timestamp is: ' + timestamp);
		shasum.update(data.room + player.name + player.img + player.num + timestamp);
		var locid = shasum.digest('hex');
		console.log('LOCID IS: ' + locid);
		rooms[data.room].shapes[locid] = new Shape(locid, 'player', 200, 200);
		rooms[data.room].shapes[locid].img = player.img;
		player.imgid = locid;
		socket.emit('pinfo', player);
		socket.emit('all players', rooms[data.room].players);
		socket.emit('all shapes', rooms[data.room].getShapes());
		socket.join(data.room);
		io.sockets.in(data.room).emit('player change', {type: 'new', players: rooms[data.room].players, newPlayer: player});
		socket.set('room', {room: data.room, player: player}, function(){});
		socket.broadcast.to(data.room).emit('new shape', rooms[data.room].shapes[locid]);
	});
	socket.on('disconnect', function(data){
		socket.get('room', function(err, room) {
			if(room === undefined || room === null) {
				console.log('disconnecting bad request...');
				return;
			}
			for(var i=0; i<room.player.drawings.length; i++) {
				delete rooms[room.room].shapes[room.player.drawings[i]];
				io.sockets.in(room.room).emit('remove shape', room.player.drawings[i]);
			}
			io.sockets.in(room.room).emit('remove shape', room.player.imgid);
			delete rooms[room.room].shapes[room.player.imgid];
			rooms[room.room].colors.push(room.player.color);
			var index = room.player.num;
			rooms[room.room].players.splice(index,1);
			if(rooms[room.room].players.length < 1) {
				console.log('deleteing room: ' + room.room);
				delete rooms[room.room];
				return;
			}
			for(var i=index; i<rooms[room.room].players.length; i++){
				rooms[room.room].players[i].num--;
			}
			io.sockets.in(room.room).emit('player change', {type: 'disconnect', players: rooms[room.room].players, dcid: room.player.imgid});
		});
	});
	socket.on('draw', function(data){
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room) {
			var i=0;
			do {
				var crypto = require('crypto')
					, shasum = crypto.createHash('sha1');
				if(room === null) return;
				shasum.update(data.type + data.xPos + data.yPos + data.points + i);
				var locid = shasum.digest('hex');
				console.log(locid);
				i++;
			}
			while(rooms[room.room].shapes[locid] !== undefined);
			rooms[room.room].shapes[locid] = new Shape(locid, data.type, data.xPos, data.yPos, data.points);
			rooms[room.room].shapes[locid].color = room.player.color;
			if(data.type === 'brush'){
				rooms[room.room].players[room.player.num].drawings.push(locid);
				console.log("drawings are: " + rooms[room.room].players[room.player.num].drawings);
			}
			io.sockets.in(room.room).emit('new shape', rooms[room.room].shapes[locid]);
		});
	});
	socket.on('taking control', function(data) {
		console.log('got into taking control');
		socket.get('room', function(err, room) {
			if (data === null || data === undefined || rooms[room.room].shapes[data] === undefined) return;
			console.log('data is: ' + data);
			if(rooms[room.room].shapes[data].user === 'none' ||
				rooms[room.room].shapes[data].user === socket) {
					rooms[room.room].shapesBeingUsed = true;
					rooms[room.room].shapes[data].user = socket;
					socket.broadcast.to(room.room).emit('being used', data);
			}
		});
	});
	socket.on('relinquish control', function(data) {
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room) {
			rooms[room.room].shapes[data].user = 'none';
			rooms[room.room].shapesBeingUsed = false;
			io.sockets.in(room.room).emit('not used', {shape: data, color: room.player.color});
		});
	});
	socket.on('move obj', function(data) {
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room) {
			console.log('got into here');
			if(rooms[room.room].shapes[data.id] === null || rooms[room.room].shapes[data.id] === undefined) return;
			if(rooms[room.room].shapes[data.id].user === socket) {
				console.log('also, correct user');
				rooms[room.room].getShapes()[data.id].setX(data.xPos);
				rooms[room.room].getShapes()[data.id].setY(data.yPos);
				socket.broadcast.to(room.room).emit('shape move', {id: data.id, xPos: data.xPos, yPos: data.yPos});
			}
		});
	});
	socket.on('remove elm', function(data) {
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room){
			delete rooms[room.room].shapes[data];
			rooms[room.room].players[room.player.num].drawings.splice(rooms[room.room].players[room.player.num].drawings.indexOf(data), 1);
			io.sockets.in(room.room).emit('remove shape', data);
		});
	});
	socket.on('steam info', function(data) {
		console.log('got into steam info befoer html');
		socket.get('room', function(err, room) {
			var http = require('http');
			http.get('http://steamcommunity.com/id/' + data, function(resp){
				console.log('got into steam info during html');
				var html = '';
				resp.on('data', function(chunk) {
					html += chunk;
				});
				resp.on('end', function(){
					console.log('got into steam info after html');
					var imgregex = new RegExp("img src=\"(.*\_full.jpg)");
					var execs = imgregex.exec(html);
					if(execs === null) {
						console.log('bad login: ' + data);
						socket.emit('bad login');
						return;
					}
					else {
						var imgurl = imgregex.exec(html)[1];
						rooms[room.room].players[room.player.num].name = data;
						rooms[room.room].players[room.player.num].img = imgurl;
						rooms[room.room].shapes[room.player.imgid].img = imgurl;
						io.sockets.in(room.room).emit('player change', {type: 'change', players: rooms[room.room].players});
						io.sockets.in(room.room).emit('shape move', {type: 'image change', img: imgurl, id: rooms[room.room].players[room.player.num].imgid});
					}
				});
			});
		});
	});
	socket.on('request drawings', function(data) {
		socket.get('room', function(err, room) {
			socket.emit('player drawings', room.player.drawings);
		});
	});
});
<commit_msg>throwaway<commit_after>var express = require('express'),
	app = express(),
	server = require('http').createServer(app),
	io = require('socket.io').listen(server),
	path = require('path');

var port = process.env.PORT || 8080;
server.listen(port);

/* io.configure(function () {
	io.set("transports", ["xhr-polling"]);
	io.set("polling duration", 10);
}); */

var rooms = {};

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

//POSTS
app.post('/test', function(req, res) {
	console.log('got make_room post');
	console.log(req.body);
	var map = req.body.map;
	var roomname;
	do{
		var crypto = require('crypto'),
			shasum = crypto.createHash('sha1');
		shasum.update('' + Math.random() + new Date().getTime());
		roomname = shasum.digest('hex');
	}while(rooms[roomname] !== undefined);
	rooms[roomname] = new Room(roomname);
	rooms[roomname].map = map;
	res.redirect('/room=' + roomname);
});

//GETS
app.get('/', function(req, res) {
	console.log('sent index');
	res.sendfile('index.html');
});
app.get('/room=:roomId', function(req, res) {
	var roomId = req.params.roomId;
	console.log('room id is: ' + roomId);
	if(rooms[roomId] !== undefined) {
		var mapurl = getMap(rooms[roomId].map);
		res.render('editor', {imgurl: mapurl});
	}
	else
		res.send('invalid room!');
});

function getMap(map) {
	switch(map) {
		case 'dust2':
			return 'imgs/de_dust2_radar_spectate.png';
			break;
		case 'inferno':
			return 'imgs/de_inferno_radar_spectate.png';
			break;
		case 'dust':
			return 'imgs/de_dust_radar_spectate.png';
			break;
		case 'train':
			return 'imgs/de_train_radar_spectate.png';
			break;
		case 'vertigo':
			return 'imgs/de_vertigo_radar.png';
			break;
		default:
			return 'imgs/de_dust2_radar_spectate_default.png';
			break;
	}
}

function Shape(id, type, x, y, points) {
	this.id = id;
	this.type = type;
	this.user = 'none';
	this.xPos = x;
	this.yPos = y;
	this.points = points;
	this.setX = function(newX) {
		this.xPos = newX;
	}
	this.setY = function(newY) {
		this.yPos = newY;
	}
}

function Player(name, num, img) {
	this.num = num;
	this.name = name;
	this.img = img;
	this.color;
	this.drawings = [];
}

function Room(name) {
	this.name = name;
	this.shapesBeingUsed = false;
	this.shapes = {};
	this.players = [];
	this.colors = ["#FF0000", "#0000FF", "#FF00FF", "#00FF00", "#FF6600"];
	this.getShapes = function() {
		return this.shapes;
	}
}

io.on('connection', function(socket) {
	socket.on('info', function(data){
		console.log('got here');
		if(rooms[data.room] === undefined) {
			console.log('BAD ROOM!');
			socket.disconnect();
			return;
		}
		//if(rooms[data.room] === undefined) rooms[data.room] = new Room(data.room);
		var pnum = rooms[data.room].players.length;
		var tmpname = 'player ' + pnum;
		var player = new Player(tmpname, pnum, 'http://upload.wikimedia.org/wikipedia/en/a/af/Question_mark.png');
		if(rooms[data.room].colors.length > 0)
			player.color = rooms[data.room].colors.pop();
		else player.color = "#FF0000";
		rooms[data.room].players.push(player);
		var crypto = require('crypto')
			, shasum = crypto.createHash('sha1');
		var timestamp = (new Date).getTime();
		console.log('timestamp is: ' + timestamp);
		shasum.update(data.room + player.name + player.img + player.num + timestamp);
		var locid = shasum.digest('hex');
		console.log('LOCID IS: ' + locid);
		rooms[data.room].shapes[locid] = new Shape(locid, 'player', 200, 200);
		rooms[data.room].shapes[locid].img = player.img;
		player.imgid = locid;
		socket.emit('pinfo', player);
		socket.emit('all players', rooms[data.room].players);
		socket.emit('all shapes', rooms[data.room].getShapes());
		socket.join(data.room);
		io.sockets.in(data.room).emit('player change', {type: 'new', players: rooms[data.room].players, newPlayer: player});
		socket.set('room', {room: data.room, player: player}, function(){});
		socket.broadcast.to(data.room).emit('new shape', rooms[data.room].shapes[locid]);
	});
	socket.on('disconnect', function(data){
		socket.get('room', function(err, room) {
			if(room === undefined || room === null) {
				console.log('disconnecting bad request...');
				return;
			}
			for(var i=0; i<room.player.drawings.length; i++) {
				delete rooms[room.room].shapes[room.player.drawings[i]];
				io.sockets.in(room.room).emit('remove shape', room.player.drawings[i]);
			}
			io.sockets.in(room.room).emit('remove shape', room.player.imgid);
			delete rooms[room.room].shapes[room.player.imgid];
			rooms[room.room].colors.push(room.player.color);
			var index = room.player.num;
			rooms[room.room].players.splice(index,1);
			if(rooms[room.room].players.length < 1) {
				console.log('deleteing room: ' + room.room);
				delete rooms[room.room];
				return;
			}
			for(var i=index; i<rooms[room.room].players.length; i++){
				rooms[room.room].players[i].num--;
			}
			io.sockets.in(room.room).emit('player change', {type: 'disconnect', players: rooms[room.room].players, dcid: room.player.imgid});
		});
	});
	socket.on('draw', function(data){
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room) {
			var i=0;
			do {
				var crypto = require('crypto')
					, shasum = crypto.createHash('sha1');
				if(room === null) return;
				shasum.update(data.type + data.xPos + data.yPos + data.points + i);
				var locid = shasum.digest('hex');
				console.log(locid);
				i++;
			}
			while(rooms[room.room].shapes[locid] !== undefined);
			rooms[room.room].shapes[locid] = new Shape(locid, data.type, data.xPos, data.yPos, data.points);
			rooms[room.room].shapes[locid].color = room.player.color;
			if(data.type === 'brush'){
				rooms[room.room].players[room.player.num].drawings.push(locid);
				console.log("drawings are: " + rooms[room.room].players[room.player.num].drawings);
			}
			io.sockets.in(room.room).emit('new shape', rooms[room.room].shapes[locid]);
		});
	});
	socket.on('taking control', function(data) {
		console.log('got into taking control');
		socket.get('room', function(err, room) {
			if (data === null || data === undefined || rooms[room.room].shapes[data] === undefined) return;
			console.log('data is: ' + data);
			if(rooms[room.room].shapes[data].user === 'none' ||
				rooms[room.room].shapes[data].user === socket) {
					rooms[room.room].shapesBeingUsed = true;
					rooms[room.room].shapes[data].user = socket;
					socket.broadcast.to(room.room).emit('being used', data);
			}
		});
	});
	socket.on('relinquish control', function(data) {
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room) {
			rooms[room.room].shapes[data].user = 'none';
			rooms[room.room].shapesBeingUsed = false;
			io.sockets.in(room.room).emit('not used', {shape: data, color: room.player.color});
		});
	});
	socket.on('move obj', function(data) {
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room) {
			console.log('got into here');
			if(rooms[room.room].shapes[data.id] === null || rooms[room.room].shapes[data.id] === undefined) return;
			if(rooms[room.room].shapes[data.id].user === socket) {
				console.log('also, correct user');
				rooms[room.room].getShapes()[data.id].setX(data.xPos);
				rooms[room.room].getShapes()[data.id].setY(data.yPos);
				socket.broadcast.to(room.room).emit('shape move', {id: data.id, xPos: data.xPos, yPos: data.yPos});
			}
		});
	});
	socket.on('remove elm', function(data) {
		if(data === null || data === undefined) return;
		socket.get('room', function(err, room){
			delete rooms[room.room].shapes[data];
			rooms[room.room].players[room.player.num].drawings.splice(rooms[room.room].players[room.player.num].drawings.indexOf(data), 1);
			io.sockets.in(room.room).emit('remove shape', data);
		});
	});
	socket.on('steam info', function(data) {
		console.log('got into steam info befoer html');
		socket.get('room', function(err, room) {
			var http = require('http');
			http.get('http://steamcommunity.com/id/' + data, function(resp){
				console.log('got into steam info during html');
				var html = '';
				resp.on('data', function(chunk) {
					html += chunk;
				});
				resp.on('end', function(){
					console.log('got into steam info after html');
					var imgregex = new RegExp("img src=\"(.*\_full.jpg)");
					var execs = imgregex.exec(html);
					if(execs === null) {
						console.log('bad login: ' + data);
						socket.emit('bad login');
						return;
					}
					else {
						var imgurl = imgregex.exec(html)[1];
						rooms[room.room].players[room.player.num].name = data;
						rooms[room.room].players[room.player.num].img = imgurl;
						rooms[room.room].shapes[room.player.imgid].img = imgurl;
						io.sockets.in(room.room).emit('player change', {type: 'change', players: rooms[room.room].players});
						io.sockets.in(room.room).emit('shape move', {type: 'image change', img: imgurl, id: rooms[room.room].players[room.player.num].imgid});
					}
				});
			});
		});
	});
	socket.on('request drawings', function(data) {
		socket.get('room', function(err, room) {
			socket.emit('player drawings', room.player.drawings);
		});
	});
});
<|endoftext|>


<commit_before><commit_msg>ssl-mod<commit_after><|endoftext|>


<commit_before>'use strict';

// EXAMPLE: MINIMUM SERVER NECESSARY
// const express = require('express');
// const app = express();
// const PORT = process.env.PORT || 8888;
// app.use(express.static('./public'));
// app.get('*', (req, res) => {
//   res.sendFile('index.html', {root: './public'});
// });
// app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

const express = require('express');
const app = express();
// eslint-disable-next-line
const http = require('http').Server(app);
const io = require('socket.io')(http); // this requires socket.io, a live or active event/route handler.
const PORT = process.env.PORT || 3000;

let arenaNum = 1; // increment up as more player join arenas.
// keep track of each arenas, on disconnect, need to handle player left behind.

// ------ USE ------
app.use(express.static('./public'));

// ------ GET ------

// app.get('*', (req, res) => {
//   res.sendFile('index.html', { root: './public' })
// })

app.get('/', function(req, res){
  res.sendFile('index.html', {root: './public'});
});

app.get('/battle', function(req, res){
  res.sendFile('index.html', {root: './public'});
});

app.get('/about', function(req, res){
  res.sendFile('index.html', {root: './public'});
});

// EXAMPLE:
// app.get('/', (request, response) => response.sendFile('index.html', {root: '.'}));
// app.get('/new', (request, response) => response.sendFile('new.html', {root: '.'}));
// app.get('/articles', (request, response) => {
//   client.query(
//     SELECT...
//   )
//   .then(result => response.send(result.rows))
//   .catch(console.error);
// });

// ------ APP.POST ------

// EXAMPLE:
// app.post('/articles', (request, response) => {
//   client.query(
//     INSERT...
//   )
//   .then(() => {
//     client.query(
//       INSERT...
//     )
//   })
//   .then(() => response.send('Insert complete'))
//   .catch(console.error);
// });

// ------ APP.PUT ------

// EXAMPLE:
// app.put('/articles/:id', (request, response) => {
//   client.query(
//     UPDATE...
//   )
//   .then(() => {
//     client.query(
//       UPDATE...
//     )
//   })
//   .then(() => response.send('Update complete'))
//   .catch(console.error);
// });

// ------ APP.DELETE ------

// EXAMPLE:
// app.delete('/articles/:id', (request, response) => {
//   client.query(
//     DELETE...
//   )
//   .then(() => response.send('Delete complete'))
//   .catch(console.error);
// });

// ------ CALL DB ------

// EXAMPLE:
// loadDB();

// ------ APP.LISTEN ------

// EXAMPLE:
// app.listen(PORT, () => console.log(`Server started on port ${PORT}!`));

// app.listen(PORT, function() {
//   console.log('Your app is being served on ' + PORT);
// })

// Stretch goal custom 404 page

// ------ DATABASE ------

// ------ SOCKET ------

// Socket.io information channels---------
io.on('connection', function(socket){ //io.connection sets up the paths/connections
  let arena = 'arena-' + arenaNum;
  socket.join(arena, function(){
    //Send this event to everyone in the room.
    console.log('Player Conneted in ' + arena);
    io.to(arena).emit('connectToArena', {
      message: 'You are in ' + arena,
      arena: arena
    });
    if (io.nsps['/'].adapter.rooms[arena].length === 1){
      io.to(arena).emit('host', {
        message: 'You are hosting this game',
        host: true
      })
    }
  });

  socket.on('player', function(data){ // this sets up a listener route waiting for a client to send something on the 'player' route.
    socket.broadcast.to(data.arena).emit('player', data.player); // broadcast the boolean true/data.value if the listener hears another client join.
  });

  socket.on('pokes', function(data){
    socket.broadcast.to(data.arena).emit('pokes', data.pokes);
  });

  socket.on('attack', function(data){ //this is the route set up to handle attacks/switches
    socket.broadcast.to(data.arena).emit('attack', data.attack);
  });

  socket.on('results', function(data){ //this is the route set up to handle attacks/switches
    socket.broadcast.to(data.arena).emit('results', data.results);
  });

  socket.on('disconnect', function(socket){
    console.log('a user disconnected', socket)
    io.to(arena).emit('testDisconnect', true);
  });

  console.log('a user connected'); // this logs to the server console/terminal
  if(io.nsps['/'].adapter.rooms[arena] && io.nsps['/'].adapter.rooms[arena].length > 1){
    arenaNum++;
  }
});
// end Socket.io channels------------------

http.listen(PORT, function(){
  console.log(`listening on ${PORT}`);
});
<commit_msg>some page.js<commit_after>'use strict';

// EXAMPLE: MINIMUM SERVER NECESSARY
// const express = require('express');
// const app = express();
// const PORT = process.env.PORT || 8888;
// app.use(express.static('./public'));
// app.get('*', (req, res) => {
//   res.sendFile('index.html', {root: './public'});
// });
// app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

const express = require('express');
const app = express();
// eslint-disable-next-line
const http = require('http').Server(app);
const io = require('socket.io')(http); // this requires socket.io, a live or active event/route handler.
const PORT = process.env.PORT || 3000;

let arenaNum = 1; // increment up as more player join arenas.
// keep track of each arenas, on disconnect, need to handle player left behind.

// ------ USE ------
app.use(express.static('./public'));

// ------ GET ------

// app.get('*', (req, res) => {
//   res.sendFile('index.html', { root: './public' })
// })

app.get('/', function(req, res){
  res.sendFile('index.html', {root: './public'});
});

// app.get('/battle', function(req, res){
//   startSocketConnection();
// });

// app.get('/about', function(req, res){
//   res.sendFile('index.html', {root: './public'});
// });

// Socket.io information channels---------
// function startSocketConnection(){
  io.on('connection', function(socket){ //io.connection sets up the paths/connections
    let arena = 'arena-' + arenaNum;
    socket.join(arena, function(){
      //Send this event to everyone in the room.
      console.log('Player Conneted in ' + arena);
      io.to(arena).emit('connectToArena', {
        message: 'You are in ' + arena,
        arena: arena
      });
      if (io.nsps['/'].adapter.rooms[arena].length === 1){
        io.to(arena).emit('host', {
          message: 'You are hosting this game',
          host: true
        })
      }
    });

    socket.on('player', function(data){ // this sets up a listener route waiting for a client to send something on the 'player' route.
      socket.broadcast.to(data.arena).emit('player', data.player); // broadcast the boolean true/data.value if the listener hears another client join.
    });

    socket.on('pokes', function(data){
      socket.broadcast.to(data.arena).emit('pokes', data.pokes);
    });

    socket.on('attack', function(data){ //this is the route set up to handle attacks/switches
      socket.broadcast.to(data.arena).emit('attack', data.attack);
    });

    socket.on('results', function(data){ //this is the route set up to handle attacks/switches
      socket.broadcast.to(data.arena).emit('results', data.results);
    });

    socket.on('disconnect', function(socket){
      console.log('a user disconnected', socket)
      io.to(arena).emit('testDisconnect', true);
    });

    console.log('a user connected'); // this logs to the server console/terminal
    if(io.nsps['/'].adapter.rooms[arena] && io.nsps['/'].adapter.rooms[arena].length > 1){
      arenaNum++;
    }
  });
// }
// end Socket.io channels------------------

http.listen(PORT, function(){
  console.log(`listening on ${PORT}`);
});
<|endoftext|>


<commit_before>var _ = require('lodash'),
    util = require('util'),
    http = require('http'),
    https = require('https'),
    fs = require('fs');

var config = {};

if(process.argv[2] == '-f') { // We're using a config file
    fs.exists("hipfm.json", function(exists) {
        if (exists) {
            console.log('Using hipfm config file.');
            config = (JSON.parse(fs.readFileSync("hipfm.json", "utf8")));
            fetchTracks(true, config);
        } else {
            console.log('The hipfm.json file does not exist. Please create the file before using the -f flag.');
            process.exit(1);
        }
    });
} else {  // We're using the command line args
    if (process.argv.length < 6) {
        console.log('Usage: node server.js ' + ' [Last.fm Api Key] [Last.fm User] [HipChat Admin/Notification Key] [Room] [Display Name]');
        process.exit(1);
    }

    config = {
        "hipchat": {
            "key": process.argv[4],
            "room": process.argv[5]
        },
        "lastfm": {
            "users": [
                {
                    "displayName": process.argv[6] || 'HipFM',
                    "username": process.argv[3],
                    "key": process.argv[2]
                }
            ]
        }
    }
    fetchTracks(true, config);
}

function checkTracks(config) {

    config.lastfm.users.forEach(function(element, index, array){
        var lastfmURL = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + config.lastfm.users[index].username + '&api_key=' + config.lastfm.users[index].key + '&format=json&limit=10';
        http.get(lastfmURL, function(httpRes) {
            var data = '';

            httpRes.on('data', function (chunk){
                data += chunk;
            });

            httpRes.on('end',function(){
                processData(JSON.parse(data), index);
            });

        }).on('error', function(e) {
            util.log("ERROR::checkTracks " + e.message);
        });
    });
}

function processData(data, userIndex) {
    if (data.recenttracks && data.recenttracks.track) {
        var currentTrack = data.recenttracks.track[0];
        if (config.lastfm.users[userIndex].lastTrack != currentTrack.name) {
            var html = '';

            if (currentTrack.image[1]['#text'] !== '') {
                html += '';
            }
            html += '  ';
            html += '' + currentTrack.name + '';
            html += ' - ' + currentTrack.artist['#text'] + '';
            html += ', ' + currentTrack.album['#text'] + '';

            sendToHipChat(html, userIndex);
            config.lastfm.users[userIndex].lastTrack = currentTrack.name;
            util.log(config.lastfm.users[userIndex].lastTrack + ' - ' + currentTrack.artist['#text'] + ' - ' + currentTrack.album['#text']);
        }
    }

    if(userIndex==0) { // Only call the timeout callback once to prevent n*2 callbacks each time.
        fetchTracks(false, config);
    }
}

function sendToHipChat(message, userIndex) {
    message = encodeURIComponent(message);
    var url = 'https://api.hipchat.com/v1/rooms/message?format=json&auth_token=' + config.hipchat.key + '&room_id=' + config.hipchat.room + '&from=' + config.lastfm.users[userIndex].displayName + '&color=purple&message_format=html&message=' + message;

    https.get(url, function(httpRes) {
        var data = '';

        httpRes.on('data', function (chunk){
            data += chunk;
        });

        httpRes.on('end',function(){
            // util.log(data);
        });
    }).on('error', function(e) {
        util.log("ERROR::sendToHipChat " + e.message);
    });
}

function fetchTracks(instant, config) {
    var millis = instant ? 0 : 30000;

    setTimeout(function() {
        checkTracks(config);
    }, millis);
}

<commit_msg>real hacky adding of the DANGER ZONE<commit_after>var _ = require('lodash'),
    util = require('util'),
    http = require('http'),
    https = require('https'),
    fs = require('fs');

var config = {};

if(process.argv[2] == '-f') { // We're using a config file
    fs.exists("hipfm.json", function(exists) {
        if (exists) {
            console.log('Using hipfm config file.');
            config = (JSON.parse(fs.readFileSync("hipfm.json", "utf8")));
            fetchTracks(true, config);
        } else {
            console.log('The hipfm.json file does not exist. Please create the file before using the -f flag.');b
            process.exit(1);
        }
    });
} else {  // We're using the command line args
    if (process.argv.length < 6) {
        console.log('Usage: node server.js ' + ' [Last.fm Api Key] [Last.fm User] [HipChat Admin/Notification Key] [Room] [Display Name]');
        process.exit(1);
    }

    config = {
        "hipchat": {
            "key": process.argv[4],
            "room": process.argv[5]
        },
        "lastfm": {
            "users": [
                {
                    "displayName": process.argv[6] || 'HipFM',
                    "username": process.argv[3],
                    "key": process.argv[2]
                }
            ]
        }
    }
    fetchTracks(true, config);
}

function checkTracks(config) {
    var tracks = null;
    var dangerzone = null;

    config.lastfm.users.forEach(function(element, index, array){
        var lastfmURL = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + config.lastfm.users[index].username + '&api_key=' + config.lastfm.users[index].key + '&format=json&limit=10';
        http.get(lastfmURL, function(httpRes) {
            var data = '';

            httpRes.on('data', function (chunk){
                data += chunk;
            });

            httpRes.on('end',function(){
                tracks = JSON.parse(data);
                complete(index);
            });

        }).on('error', function(e) {
            util.log("ERROR::checkTracks " + e.message);
        });

        // danger zone
        var dangerZoneUrl = 'http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=' + config.lastfm.users[index].username + '&api_key=' + config.lastfm.users[index].key + '&period=3month&format=json&limit=10';
        http.get(dangerZoneUrl, function(httpRes) {
            var data = '';

            httpRes.on('data', function (chunk){
                data += chunk;
            });

            httpRes.on('end',function(){
                dangerzone = JSON.parse(data);
                complete(index);
            });

        }).on('error', function(e) {
            util.log("ERROR::checkTracks " + e.message);
        });
    });

    function complete(index) {
        if (tracks !== null && dangerzone !== null) {
            processData(tracks, dangerzone, index);
        }
    }

}

function processData(data, dangerzone, userIndex) {
    if (data.recenttracks && data.recenttracks.track) {
        var currentTrack = data.recenttracks.track[0];
        var dangerTracks = dangerzone.toptracks.track;

        if (config.lastfm.users[userIndex].lastTrack != currentTrack.name) {

            var dangerTrack = _.find(dangerTracks, function(track){
                if(track.mbid === currentTrack.mbid || track.name === currentTrack.name) {
                    return track;
                }
            });

            var html = '';
            var color = 'purple';

            if (currentTrack.image[1]['#text'] !== '') {
                html += '';
            }
            html += '  ';
            html += '' + currentTrack.name + '';
            html += ' - ' + currentTrack.artist['#text'] + '';
            html += ', ' + currentTrack.album['#text'] + '';

            if(dangerTrack) {
                color = 'red';
                html += "
   This track's on a highway to the DANGER ZONE! Please, somebody skip it.
";
            }

            sendToHipChat(html, userIndex, color);
            config.lastfm.users[userIndex].lastTrack = currentTrack.name;
            util.log(config.lastfm.users[userIndex].lastTrack + ' - ' + currentTrack.artist['#text'] + ' - ' + currentTrack.album['#text']);
        }
    }

    if(userIndex==0) { // Only call the timeout callback once to prevent n*2 callbacks each time.
        fetchTracks(false, config);
    }
}

function sendToHipChat(message, userIndex, color) {
    color = color || 'purple';
    message = encodeURIComponent(message);
    var url = 'https://api.hipchat.com/v1/rooms/message?format=json&auth_token=' + config.hipchat.key + '&room_id=' + config.hipchat.room + '&from=' + config.lastfm.users[userIndex].displayName + '&color='+ color +'&message_format=html&message=' + message;

    https.get(url, function(httpRes) {
        var data = '';

        httpRes.on('data', function (chunk){
            data += chunk;
        });

        httpRes.on('end',function(){
            // util.log(data);
        });
    }).on('error', function(e) {
        util.log("ERROR::sendToHipChat " + e.message);
    });
}

function fetchTracks(instant, config) {
    var millis = instant ? 0 : 30000;

    setTimeout(function() {
        checkTracks(config);
    }, millis);
}

<|endoftext|>


<commit_before>var express = require('express');
var passport = require('passport');
var path = require('path');
var Strategy = require('passport-local').Strategy;
var db = require('./db');

var authRouter = require('./routes/auth');
var profileRouter = require('./routes/profile');
var notificationsRouter = require('./routes/notifications');

// Create a new Express application.
var app = express();

require('./boot/auth')();

// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));

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

app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/',
  function(req, res) {
    res.render('home', { user: req.user });
  });

app.use('/', authRouter);
app.use('/profile', profileRouter);
app.use('/notifications', notificationsRouter);

app.listen(3000);
<commit_msg>Remove unused require statements.<commit_after>var express = require('express');
var passport = require('passport');
var path = require('path');

var authRouter = require('./routes/auth');
var profileRouter = require('./routes/profile');
var notificationsRouter = require('./routes/notifications');

// Create a new Express application.
var app = express();

require('./boot/auth')();

// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));

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

app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/',
  function(req, res) {
    res.render('home', { user: req.user });
  });

app.use('/', authRouter);
app.use('/profile', profileRouter);
app.use('/notifications', notificationsRouter);

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


<commit_before>var express = require('express');
var mongo = require('mongodb').MongoClient;
var session = require('express-session');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var md5 = require('md5');
var nodemailer = require('nodemailer');
var emailCheck = require('email-check');
var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'mailer.ssm.app@gmail.com',
        pass: process.env.MAILPW
    }
});
var mail_template = require('./views/welcome_mail');
var dburl = process.env.DBURL;
var port = process.env.PORT;
var app = express();

app.use(express.static(`${__dirname}/views`));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));
app.use(session({
    secret: "Shh, its a secret!"
}));
app.set('vew engine', 'ejs');

//PASSPORT FOR AUTHENTICATION
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
    done(null, user);
});
passport.deserializeUser(function (user, done) {
    done(null, user);
});
passport.use(new Strategy(
    function (username, password, done) {
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
            } else {
                var col = db.collection('data');
                username = username.toLowerCase();
                col.find({
                    username: username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                    } else {
                        if (ress.length == 0) {
                            console.log('user not found!');
                            done(null, false);
                        } else {
                            if (md5(password) == ress[0].hash) {
                                console.log('Verified!');
                                return done(null, ress[0]);
                            } else {
                                console.log('Wrong password!');
                                done(null, false);
                            }
                        }
                    }
                });
            }
        });

    }));

//ROUTES

//HOME PAGE
app.get('/', function (req, res) {
    res.render('home.ejs', {});
});

//SIGN UP PAGE
app.get('/signup', function (req, res) {
    console.log('\nSIGNUP ROUTE GET');
    res.render('signup.ejs');
});

//POSTING SIGNUP DATA
app.post('/signup', function (req, res) {
    console.log('\nSIGNUP ROUTE POST');
    var username = req.body.username.toLowerCase();
    var email = req.body.email;

    //PASSWORD IS HASHED WITH MD-5 AND THAT DIGEST IS STORED AT THE DATABASE
    var hash = md5(req.body.password);

    //VALIDATING EMAIL
    emailCheck(email).then(function (stat) {
        if (stat) {
            mongo.connect(dburl, function (err, db) {
                if (err) {
                    console.log(err);
                    res.json({
                        alert: 'Cannot connect to db'
                    });
                } else {
                    var col = db.collection('data');
                    col.find({
                        username: username
                    }).toArray(function (err, ress) {
                        if (err) {
                            console.log(err);
                            res.json({
                                alert: 'db err'
                            });
                        } else {
                            if (ress.length > 0) {
                                console.log('User exists');
                                res.json({
                                    log: 'Username taken',
                                    code: 101
                                });
                            } else {
                                col.find({
                                    email: email
                                }).toArray(function (err, results) {
                                    if (err) {
                                        console.log(err);
                                    } else {
                                        if (results.length > 0) {
                                            console.log('email taken');
                                            res.json({
                                                code: 750
                                            });
                                        } else {
                                            var user = {};
                                            user.username = username;
                                            user.hash = hash;
                                            user.email = email;
                                            user.key = `mailerkey${Date.now()}`;
                                            user.projects = [];
                                            col.insert(user);
                                            res.json({
                                                alert: 'Thank you. Log in with your credentials.',
                                                log: user.key,
                                                code: 100,
                                                redirect: '/'
                                            });
                                            console.log('DONE');

                                            ////SENDING THE WELCOME MESSAGE

                                            var html = mail_template.mail;

                                            let mailOptions = {
                                                from: 'mailer', // sender address
                                                to: email, // list of receivers
                                                subject: `Welcome to Mailer, ${username}!`, // Subject line
                                                text: 'Welcome to Mailer!', // plain text body
                                                html: html // html body
                                            };

                                            // send mail with defined transport object
                                            transporter.sendMail(mailOptions, (error, info) => {
                                                if (error) {
                                                    return console.log(error);
                                                }
                                                console.log('\n\nMessage sent to User');
                                            });

                                            /*SENDING ME A MESSAGE THAT A NEW MEMBER HAS REGISTERED*/
                                            col.find({}).toArray(function (err, all) {
                                                console.log("\n\nNEW ROUTE");
                                                if (err) {
                                                    console.log(err);
                                                } else {
                                                    var allDocs = all.length;
                                                    console.log("\nALL DOCS: " + allDocs);
                                                    mailOptions.to = "ssm123sssm@gmail.com";
                                                    mailOptions.subject = "New Registraion on Mailer!";
                                                    mailOptions.text = mailOptions.subject;
                                                    mailOptions.html = mail_template.reg;
                                                    mailOptions.html += `Time: ${Date()} <br> Email: ${email} <br>Username: ${username}<br><br>Currently Registered Users: ${allDocs}`;
                                                    transporter.sendMail(mailOptions, (error, info) => {
                                                        if (error) {
                                                            console.log("\nERROR IN NEW MAIL SENDING");
                                                            return console.log(error);
                                                        }
                                                        console.log("\n\nMAIL SENT!");
                                                        console.log('\n\nMessage sent to YOU');
                                                    });
                                                }
                                            });

                                        }
                                    }
                                });

                            }
                        }
                    });
                }
            });
        } else {

            res.json({
                alert: "Invalid email address!",
                log: "Invalid email address",
                code: 105
            });
        }
    }).catch(function (err) {
        console.log(err);
        res.json({
            alert: "Invalid email address!",
            log: "Invalid email address",
            code: 105
        });
    });

});

/*POSTING DATA THROUGH HOME PAGE (LOGIN PAGE)
IF AUTHENTICATION SUCCESS, DIRECTED TO /SUCCESS, OTHERWISE TO /FAIL*/
app.post('/login',
    passport.authenticate('local', {
        failureRedirect: '/fail'
    }),
    function (req, res) {
        res.redirect('/success');
    });
app.get('/success', function (req, res) {
    if (req.user) {
        res.json({
            redirect: '/profile'
        });
    } else {
        res.json({
            alert: 'Logged in as GUEST',
            redirect: '/fail'

        });
    }
});
app.get('/fail', function (req, res) {
    res.json({
        alert: 'Login Failure. Please check username and password.'
    });
});

/*SUBMITTING A NEW PROJECT WITH SUBIT BUTTON ON PROFILE PAGE*/
app.post('/submit_project', function (req, res) {
    var project = req.body.project;
    var id = Date.now();

    //IF NOT LOGGED IN ALERT THE USER
    if (!req.user) {
        res.json({
            alert: 'Please log in to submit projects...'
        });
    } else {
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
                res.json({
                    alert: 'Error connecting to database'
                });
            } else {
                var col = db.collection('data');
                col.find({
                    username: req.user.username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                        res.json({
                            alert: 'Error connecting to database'
                        });
                    } else {
                        //FINDIN IF A PROJECT WITH THE SAME NAME EXISTS
                        var exists = false;
                        ress[0].projects.forEach(function (item) {
                            if (item.name == project) {
                                exists = true;
                            }
                        });
                        if (exists) {
                            res.json({
                                code: 300
                            });
                            db.close();
                        } else {
                            var sub = {};
                            if (req.body.redirect) {
                                sub.redirect = req.body.redirect;
                            }
                            sub.name = project;
                            sub.id = id;
                            ress[0].projects.push(sub);
                            col.update({
                                username: req.user.username
                            }, ress[0]);
                            console.log('DB UPDATED!');
                            db.close();
                            res.json({
                                code: 400,
                                projects: ress[0].projects
                            });
                        }
                    }
                });
            }
        });
    }
});

/*REMOVING A PROJECTS WITH REMOVE BUTTON UNDER MY PROJECTS*/
app.post('/remove', function (req, res) {
    if (!req.user) {
        res.json({
            alert: 'Please log in first'
        });
    } else {
        var name = req.body.name;
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
                res.json({
                    alert: 'Error connecting to database',
                    log: err
                });
            } else {
                var col = db.collection('data');
                col.find({
                    username: req.user.username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                        res.json({
                            alert: 'Error connecting to databse',
                            log: err
                        });
                    } else {
                        var index;
                        for (var i = 0; i < ress[0].projects.length; i++) {
                            if (ress[0].projects[i].name == name) {
                                index = i;
                            }
                        }
                        ress[0].projects.splice(index, 1);
                        col.update({
                            username: req.user.username
                        }, ress[0]);
                        res.json({
                            code: 500,
                            projects: ress[0].projects
                        });
                    }
                });
            }
        });
    }
});

//LOGGING OUT THE USER
app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/');
});

/*SENT THE USER HERE FROM SUCCESS ROUTE AFTER AUTHENTICATION*/
app.get('/profile', function (req, res) {
    if (req.user) {
        console.log(req.user);
        res.render('profile.ejs', req.user);
    } else {
        console.log('\nNOT LOGGED IN!');
        res.render('profile.ejs', {
            username: 'GUEST'
        });
        //        res.send('Authentication error! Please log in');
    }
});

/*GETTING USER'S PROJECT WITH ANGULAR*/
app.get('/myProjects', function (req, res) {
    if (req.user) {
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
                res.json({
                    alert: 'mongo err. See log',
                    log: err
                });
            } else {
                var col = db.collection('data');
                col.find({
                    username: req.user.username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                        res.json({
                            alert: 'Mongo err. see log',
                            log: err
                        });
                    } else {
                        res.json({
                            log: 'Success at obtainig user projects',
                            projects: ress[0].projects,
                            code: 200

                        });
                        db.close();
                    }
                });
            }
        });
    } else {
        res.json({
            alert: 'Not logged in'
        });
    }
});

/*GETTING FORM DATA*/
app.post('/mailer', function (req, res) {
    console.log('\nMAILER ROUTE');
    var message = req.body;
    console.log(message);
    var id = req.query.id;
    mongo.connect(dburl, function (err, db) {
        if (err) {
            console.log(err);
        } else {
            var col = db.collection('data');
            var found = false;
            var email, username, project, redirect;
            col.find({}).toArray(function (err, ress) {
                if (err) {
                    console.log(err);
                } else {
                    ress.forEach(function (user) {
                        user.projects.forEach(function (item) {
                            if (!found) {
                                if (item.id == id) {
                                    found = true;
                                    email = user.email;
                                    username = user.username;
                                    project = item.name;
                                    if (item.redirect) {
                                        redirect = item.redirect;
                                    } else {
                                        redirect = '/default_redirect';
                                    }
                                }
                            }
                        });
                    });

                    if (found) {
                        var html = '
Form data from ' + project + '
';
                        for (var key in message) {
                            html += '' + key + ':  ' + message[key] + '
';
                        }
                        html += '

generated by Mailer
';
                        console.log(html);

                        let mailOptions = {
                            from: 'mailer', // sender address
                            to: email, // list of receivers
                            subject: `Form submission from ${project}`, // Subject line
                            text: 'Data', // plain text body
                            html: html // html body
                        };
                        // send mail with defined transport object
                        transporter.sendMail(mailOptions, (error, info) => {
                            if (error) {
                                return console.log(error);
                            }
                            console.log('Message %s sent: %s', info.messageId, info.response);
                        });
                        res.redirect(redirect);
                    } else {
                        res.render('broken.ejs');
                    }

                }
            });
        }
    });
});

/*IF DEFAULT REDIRECT WAS SELECTED, THIS THANK YOU PAGE IS DISPLAYED*/
app.get('/default_redirect', function (req, res) {
    res.render('default_redirect.ejs');
});

/*HOW TO PAGE*/
app.get('/howto', function (req, res) {
    if (req.user) {
        res.render('howto.ejs', req.user);

    } else {
        res.render('howto.ejs', {
            username: 'GUEST'
        });

    }
});

/*STARTING THE SERVER*/
app.listen(port, function () {
    console.log(`App started on port ${port}`);
});
<commit_msg>feedback<commit_after>var express = require('express');
var mongo = require('mongodb').MongoClient;
var session = require('express-session');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var md5 = require('md5');
var nodemailer = require('nodemailer');
var emailCheck = require('email-check');
var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'mailer.ssm.app@gmail.com',
        pass: process.env.MAILPW
    }
});
var mail_template = require('./views/welcome_mail');
var dburl = process.env.DBURL;
var port = process.env.PORT;
var app = express();

app.use(express.static(`${__dirname}/views`));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));
app.use(session({
    secret: "Shh, its a secret!"
}));
app.set('vew engine', 'ejs');

//PASSPORT FOR AUTHENTICATION
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
    done(null, user);
});
passport.deserializeUser(function (user, done) {
    done(null, user);
});
passport.use(new Strategy(
    function (username, password, done) {
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
            } else {
                var col = db.collection('data');
                username = username.toLowerCase();
                col.find({
                    username: username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                    } else {
                        if (ress.length == 0) {
                            console.log('user not found!');
                            done(null, false);
                        } else {
                            if (md5(password) == ress[0].hash) {
                                console.log('Verified!');
                                return done(null, ress[0]);
                            } else {
                                console.log('Wrong password!');
                                done(null, false);
                            }
                        }
                    }
                });
            }
        });

    }));

//ROUTES

//HOME PAGE
app.get('/', function (req, res) {
    res.render('home.ejs', {});
});

//SIGN UP PAGE
app.get('/signup', function (req, res) {
    console.log('\nSIGNUP ROUTE GET');
    res.render('signup.ejs');
});

//POSTING SIGNUP DATA
app.post('/signup', function (req, res) {
    console.log('\nSIGNUP ROUTE POST');
    var username = req.body.username.toLowerCase();
    var email = req.body.email;

    //PASSWORD IS HASHED WITH MD-5 AND THAT DIGEST IS STORED AT THE DATABASE
    var hash = md5(req.body.password);

    //VALIDATING EMAIL
    emailCheck(email).then(function (stat) {
        if (stat) {
            mongo.connect(dburl, function (err, db) {
                if (err) {
                    console.log(err);
                    res.json({
                        alert: 'Cannot connect to db'
                    });
                } else {
                    var col = db.collection('data');
                    col.find({
                        username: username
                    }).toArray(function (err, ress) {
                        if (err) {
                            console.log(err);
                            res.json({
                                alert: 'db err'
                            });
                        } else {
                            if (ress.length > 0) {
                                console.log('User exists');
                                res.json({
                                    log: 'Username taken',
                                    code: 101
                                });
                            } else {
                                col.find({
                                    email: email
                                }).toArray(function (err, results) {
                                    if (err) {
                                        console.log(err);
                                    } else {
                                        if (results.length > 0) {
                                            console.log('email taken');
                                            res.json({
                                                code: 750
                                            });
                                        } else {
                                            var user = {};
                                            user.username = username;
                                            user.hash = hash;
                                            user.email = email;
                                            user.key = `mailerkey${Date.now()}`;
                                            user.projects = [];
                                            col.insert(user);
                                            res.json({
                                                alert: 'Thank you. Log in with your credentials.',
                                                log: user.key,
                                                code: 100,
                                                redirect: '/'
                                            });
                                            console.log('DONE');

                                            ////SENDING THE WELCOME MESSAGE

                                            var html = mail_template.mail;

                                            let mailOptions = {
                                                from: 'mailer', // sender address
                                                to: email, // list of receivers
                                                subject: `Welcome to Mailer, ${username}!`, // Subject line
                                                text: 'Welcome to Mailer!', // plain text body
                                                html: html // html body
                                            };

                                            // send mail with defined transport object
                                            transporter.sendMail(mailOptions, (error, info) => {
                                                if (error) {
                                                    return console.log(error);
                                                }
                                                console.log('\n\nMessage sent to User');
                                            });

                                            /*SENDING ME A MESSAGE THAT A NEW MEMBER HAS REGISTERED*/
                                            col.find({}).toArray(function (err, all) {
                                                console.log("\n\nNEW ROUTE");
                                                if (err) {
                                                    console.log(err);
                                                } else {
                                                    var allDocs = all.length;
                                                    let mailOptions = {
                                                        from: 'mailer', // sender address
                                                        to: "ssm123sssm@gmail.com", // list of receivers
                                                        subject: "New Registraion on Mailer!", // Subject line
                                                        text: "New Registraion on Mailer!", // plain text body
                                                        html: mail_template.reg; // html body
                                                    };
                                                    console.log("\nALL DOCS: " + allDocs);
                                                    mailOptions.html += `Time: ${Date()} <br> Email: ${email} <br>Username: ${username}<br><br>Currently Registered Users: ${allDocs}`;
                                                    transporter.sendMail(mailOptions, (error, info) => {
                                                        if (error) {
                                                            console.log("\nERROR IN NEW MAIL SENDING");
                                                            return console.log(error);
                                                        }
                                                        console.log("\n\nMAIL SENT!");
                                                        console.log('\n\nMessage sent to YOU');
                                                    });
                                                }
                                            });

                                        }
                                    }
                                });

                            }
                        }
                    });
                }
            });
        } else {

            res.json({
                alert: "Invalid email address!",
                log: "Invalid email address",
                code: 105
            });
        }
    }).catch(function (err) {
        console.log(err);
        res.json({
            alert: "Invalid email address!",
            log: "Invalid email address",
            code: 105
        });
    });

});

/*POSTING DATA THROUGH HOME PAGE (LOGIN PAGE)
IF AUTHENTICATION SUCCESS, DIRECTED TO /SUCCESS, OTHERWISE TO /FAIL*/
app.post('/login',
    passport.authenticate('local', {
        failureRedirect: '/fail'
    }),
    function (req, res) {
        res.redirect('/success');
    });
app.get('/success', function (req, res) {
    if (req.user) {
        res.json({
            redirect: '/profile'
        });
    } else {
        res.json({
            alert: 'Logged in as GUEST',
            redirect: '/fail'

        });
    }
});
app.get('/fail', function (req, res) {
    res.json({
        alert: 'Login Failure. Please check username and password.'
    });
});

/*SUBMITTING A NEW PROJECT WITH SUBIT BUTTON ON PROFILE PAGE*/
app.post('/submit_project', function (req, res) {
    var project = req.body.project;
    var id = Date.now();

    //IF NOT LOGGED IN ALERT THE USER
    if (!req.user) {
        res.json({
            alert: 'Please log in to submit projects...'
        });
    } else {
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
                res.json({
                    alert: 'Error connecting to database'
                });
            } else {
                var col = db.collection('data');
                col.find({
                    username: req.user.username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                        res.json({
                            alert: 'Error connecting to database'
                        });
                    } else {
                        //FINDIN IF A PROJECT WITH THE SAME NAME EXISTS
                        var exists = false;
                        ress[0].projects.forEach(function (item) {
                            if (item.name == project) {
                                exists = true;
                            }
                        });
                        if (exists) {
                            res.json({
                                code: 300
                            });
                            db.close();
                        } else {
                            var sub = {};
                            if (req.body.redirect) {
                                sub.redirect = req.body.redirect;
                            }
                            sub.name = project;
                            sub.id = id;
                            ress[0].projects.push(sub);
                            col.update({
                                username: req.user.username
                            }, ress[0]);
                            console.log('DB UPDATED!');
                            db.close();
                            res.json({
                                code: 400,
                                projects: ress[0].projects
                            });
                        }
                    }
                });
            }
        });
    }
});

/*REMOVING A PROJECTS WITH REMOVE BUTTON UNDER MY PROJECTS*/
app.post('/remove', function (req, res) {
    if (!req.user) {
        res.json({
            alert: 'Please log in first'
        });
    } else {
        var name = req.body.name;
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
                res.json({
                    alert: 'Error connecting to database',
                    log: err
                });
            } else {
                var col = db.collection('data');
                col.find({
                    username: req.user.username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                        res.json({
                            alert: 'Error connecting to databse',
                            log: err
                        });
                    } else {
                        var index;
                        for (var i = 0; i < ress[0].projects.length; i++) {
                            if (ress[0].projects[i].name == name) {
                                index = i;
                            }
                        }
                        ress[0].projects.splice(index, 1);
                        col.update({
                            username: req.user.username
                        }, ress[0]);
                        res.json({
                            code: 500,
                            projects: ress[0].projects
                        });
                    }
                });
            }
        });
    }
});

//LOGGING OUT THE USER
app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/');
});

/*SENT THE USER HERE FROM SUCCESS ROUTE AFTER AUTHENTICATION*/
app.get('/profile', function (req, res) {
    if (req.user) {
        console.log(req.user);
        res.render('profile.ejs', req.user);
    } else {
        console.log('\nNOT LOGGED IN!');
        res.render('profile.ejs', {
            username: 'GUEST'
        });
        //        res.send('Authentication error! Please log in');
    }
});

/*GETTING USER'S PROJECT WITH ANGULAR*/
app.get('/myProjects', function (req, res) {
    if (req.user) {
        mongo.connect(dburl, function (err, db) {
            if (err) {
                console.log(err);
                res.json({
                    alert: 'mongo err. See log',
                    log: err
                });
            } else {
                var col = db.collection('data');
                col.find({
                    username: req.user.username
                }, {
                    _id: 0
                }).toArray(function (err, ress) {
                    if (err) {
                        console.log(err);
                        res.json({
                            alert: 'Mongo err. see log',
                            log: err
                        });
                    } else {
                        res.json({
                            log: 'Success at obtainig user projects',
                            projects: ress[0].projects,
                            code: 200

                        });
                        db.close();
                    }
                });
            }
        });
    } else {
        res.json({
            alert: 'Not logged in'
        });
    }
});

/*GETTING FORM DATA*/
app.post('/mailer', function (req, res) {
    console.log('\nMAILER ROUTE');
    var message = req.body;
    console.log(message);
    var id = req.query.id;
    mongo.connect(dburl, function (err, db) {
        if (err) {
            console.log(err);
        } else {
            var col = db.collection('data');
            var found = false;
            var email, username, project, redirect;
            col.find({}).toArray(function (err, ress) {
                if (err) {
                    console.log(err);
                } else {
                    ress.forEach(function (user) {
                        user.projects.forEach(function (item) {
                            if (!found) {
                                if (item.id == id) {
                                    found = true;
                                    email = user.email;
                                    username = user.username;
                                    project = item.name;
                                    if (item.redirect) {
                                        redirect = item.redirect;
                                    } else {
                                        redirect = '/default_redirect';
                                    }
                                }
                            }
                        });
                    });

                    if (found) {
                        var html = '
Form data from ' + project + '
';
                        for (var key in message) {
                            html += '' + key + ':  ' + message[key] + '
';
                        }
                        html += '

generated by Mailer
';
                        console.log(html);

                        let mailOptions = {
                            from: 'mailer', // sender address
                            to: email, // list of receivers
                            subject: `Form submission from ${project}`, // Subject line
                            text: 'Data', // plain text body
                            html: html // html body
                        };
                        // send mail with defined transport object
                        transporter.sendMail(mailOptions, (error, info) => {
                            if (error) {
                                return console.log(error);
                            }
                            console.log('Message %s sent: %s', info.messageId, info.response);
                        });
                        res.redirect(redirect);
                    } else {
                        res.render('broken.ejs');
                    }

                }
            });
        }
    });
});

/*IF DEFAULT REDIRECT WAS SELECTED, THIS THANK YOU PAGE IS DISPLAYED*/
app.get('/default_redirect', function (req, res) {
    res.render('default_redirect.ejs');
});

/*HOW TO PAGE*/
app.get('/howto', function (req, res) {
    if (req.user) {
        res.render('howto.ejs', req.user);

    } else {
        res.render('howto.ejs', {
            username: 'GUEST'
        });

    }
});

/*STARTING THE SERVER*/
app.listen(port, function () {
    console.log(`App started on port ${port}`);
});
<|endoftext|>


<commit_before>/// <reference path="typings/node/node.d.ts"/>
var express = require("express");
var app = express();

// fucking dependencies
var server = require('http').Server(app)
var io = require('socket.io')(server);
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var session = require('express-session');
var path = require('path');
var async = require('async');
var md = require("node-markdown").Markdown;
var fs = require("fs");

require('colors');	// for fantastic debug

// setting app -> too dizzy to fuck with
app.use(cookieParser());
app.use(session({ secret: "secret" }));

var set = require('./setting.json');

var options = process.argv;
for( var num in options){
	if(options[num] == "--port" || options[num] == "-p"){
		set.port = options[Number(num)+1];
	}
	if(options[num] == "--quiet" || options[num] == "-q"){
		console.log = function(){};
	}
}

app.set("view engine", "ejs");
app.set("views", __dirname+"/app/views");
app.use( express.static( __dirname + "/public" ));
app.use(bodyParser.urlencoded({ extended: false }));

// homemade modules
var dbnotices = require("./dbmodules/dbnotices.js");
var dbusers = require("./dbmodules/dbusers.js");
var dbdislikes = require("./dbmodules/dbdislikes.js");
var dbjoins = require("./dbmodules/dbjoins.js");
var dbworks = require("./dbmodules/dbworks.js");
var dbowns = require("./dbmodules/dbowns.js");

var socketMod = require("./socketMod.js");
var systemMod = require("./systemMod.js");

var auth = require("./auth.js");
auth.init(app);
var passport = auth.getPassport();

require('./database.js')();

// fucking routing
app.get('/auth/fb', passport.authenticate('facebook'));

app.get('/auth/fb/callback',
    passport.authenticate('facebook', {
		successRedirect: '/join',
        failureRedirect: '/loginFail'
	})
);

app.get('/loginSuccess', auth.checkAuthState, function(req, res){
	console.log("로그인성공");
    res.send(req.user);
});
app.get('/logout', function(req, res){
    req.logout();
    res.redirect('/');
});

app.route("/")
	.get(auth.inspect, function(req, res) {
		systemMod.checkBrowser(req.headers['user-agent'],function(browserName){
			// && browserVersion <= 9
			if (browserName == 'IE') {
				res.write("<script>window.open('http://www.opera.com/ko/computer');</script>");
				res.write("<script>window.open('https://www.mozilla.org/ko/firefox/new/');</script>");
				res.end("<script>location.href='https://www.google.com/chrome/browser/desktop/index.html';</script>");
			}
		});

		async.parallel([
			function(callback) {
				Works.findAll({
					order: ['dislikes', 'DESC']
				}).then(function(works, err) {
		            if(err) callback(err, null);
		            else {
						console.log(works);
						callback(null, works);
		            }
		        });
			},
			function(callback) {
				Dislikes.findAll().then(function(dislikes, err){
					if(err)	callback(err, null);
					else{
						console.log(dislikes);
						callback(null, dislikes);
					}
				});
			},
			function(callback) {
				Joins.findAll().then(function(joins, err){
					if(err) callback(err, null);
					else{
						console.log(joins);
						callback(null, joins);
					}
				});
			}
		], function(err, results) {
			if(err) console.error(err);
			else{
				var works = results[0];
				var dislikes = results[1];
				var joins = results[2];
				dbdislikes.getWorksDislikesNum(works, function(arrWorksDislikesNum) {
					res.render("frontpage.ejs", {
						works: works,
						login: req.authState,
						user: req.user,
						dislikes: dislikes,
						numDislikes: arrWorksDislikesNum,
						joins: joins,
						host: set.host,
						port: ((set.main)?'':':'+set.port)
					});
				});
			}
		});
	});

app.route("/makework")
	.get(auth.checkAuthState, function(req, res){
		if(req.authState) {
			res.render('makework.ejs', {
				host: set.host,
				port: ((set.main)?'':':'+set.port),
				userId: req.user.id,
				user: req.user,
				pageTitle: '공작 모의'
			});
		} else {
			res.redirect('/');
		}
	})
	.post(auth.checkAuthState, function(req, res){
		async.waterfall([
			function(cb){
				dbworks.createWork( req.body.name, req.body.desc, function(work, err) {
					if(err) console.error(err);
					else {
						cb( null, work );
					}
				});
			},
			function(work, cb){
				async.parallel([
					function(callback){
						dbowns.createOwn(req.user.id, work.id, function(own, err){
							if(err) console.error(err);
							else{
								console.log("공작 생성 :".cyan, work.name);
								fs.mkdir("./public/workpage/"+work.name, function(err){
									if(err) console.error(err);
						        	else{
										callback(null, {});
									}
								});
							}
						});
					},
					function(callback){
						var data = {
							workId: work.id,
							userId: req.user.id
						};
						dbjoins.toggleTuple( null, data, function(){
							callback(null, {});
						});
					}
				],
				function(err, result){
					cb( null, work );
				});
			},
			function( work, cb){
				async.parallel([
					function(callback) {
						fs.writeFile("./public/workpage/" + work.name + "/front.html", md(req.body.readme), function(err) {
							if(err) callback(err, null);
							else callback(null);
						});
					},
					function(callback) {
						fs.writeFile("./public/workpage/" + work.name + "/needs.html", md(req.body.needs), function(err) {
							if(err) callback(err, null);
							else callback(null);
						});
					}
				], function(err, results) {
					if(err) console.error(err);
					else {
						console.log("공작 생성 리스폰스");
						cb( err, results, work );
					}
				});
			}
		], function(err, result, work){
			res.send({code: 201, url: '/work/'+encodeURIComponent(work.name)});
		});
	});

app.route("/join")
	.get(auth.checkAuthState, function(req, res) {
		console.log("REQ", req.user)
		dbusers.searchByFbid(req.user.fbId, function(user, err) {
			console.log(user);
			if(err) console.error("ERROR".red, err);
			else if(user) {
				if(user.nickname == null)
					res.render('join.ejs', {
						pageTitle: '가입',
						name: req.user.name,
						login: false,
						picture: req.user.picture,
						host: set.host,
						port: ((set.main)?'':':'+set.port)
					});
				else res.redirect('/'); //닉네임 이미 등록됨.
			} else {
				res.redirect('/'); //잘못된 접근: 세션은 인증되어 있는데 해당하는 정보가 DB에 없음
			}
		})
	})
	.post(auth.checkAuthState, function(req, res) {
		if(req.body.nickname) {
			dbusers.searchByNickname(req.body.nickname, function(user, err) {
				if(err) console.error(err);
				else if(!user) { // 가능한 닉네임
					dbusers.searchByFbid(req.user.fbId, function(user, err) {
						if(err) console.error(err);
						else if(!user){ // 그 세션의 uid에 해당하는 게 등록 안되어있음 (이상한 케이스)
							res.redirect('/');
						} else {
							dbusers.changeNickname(user, req.body.nickname, function(user, err) {
								if(err) {
									console.error(err);
									res.send("500").end();
								}
								else {
									console.log("유저 생성 :".cyan, user.name);
									res.send("201").end();
								}
							});
						}
					});
				} else {
					// 이미 존재하는 닉네임
					res.send("409").end();
				}
			})
		} else res.send("400").end();
	});

app.route("/work/:workName")
	.get(auth.inspect, function(req, res){
		Works.findOne({
			where: {
				name: req.params.workName
			}
		}).then(function(work, err) {
			if(err) console.error(err);
			else {
				dbdislikes.searchWorksDislikes(work.id, function(result){
					var numDislikes = result.length;
					res.render("workpage.ejs", {
						work: work,
						numDislikes: numDislikes,
						host: set.host,
						port: ((set.main)?'':':'+set.port),
						user: (req.authState)?req.user:null
					});
				});
			}
		});
	})
	.post(function(req, res){
		var workId = req.params.workId;
		Works.findOne({
			where: {
				id: workId
			}
		}).then(function(work, err) {
			if(err) console.error(err);
			else {
				fs.mkdir("./WorkPage/"+work.name, function(err){
					console.log(err);
					if (req.body.reqType == "md") {
						var html = md(req.body.md);
						fs.writeFile("./WorkPage/"+work.name+"/front.html", html, function(err){
							if(err) console.log(err);
							work.updateAttributes({
								frontboard: "./WorkPage" + work.name + "/front.html"
							}).then(function(work, err){
								if(err) console.log(err);
								res.redirect("/work/"+work.id+"/"+work.name);
							});
						});
					}
					else if ( req.body.reqType == "need" ) {
						var html = md(req.body.need)
						fs.writeFile("./WorkPage/"+work.name+"/need.html", html, function(err){
							if(err) console.log(err);
							work.updateAttributes({
								needs: "./WorkPage" + work.name + "/need.html"
							}).then(function(work, err){
								if(err) console.log(err);
								res.redirect("/work/"+work.id+"/"+work.name);
							});
						});
					}
				});
			}
		});
	});

app.route("/user/:userNick")
	.get(auth.inspect, function(req, res){
		dbusers.searchByNickname(req.params.userNick, function(user, err){
			if(err) console.error(err);
			else{
				if(req.authState) {
					if( req.params.userNick == req.user.nickname ){
						res.render('userpage.ejs', {
							host: set.host,
							port: ((set.main)?'':':'+set.port),
							pageTitle: '너의 정보',
							login: req.authState,
							user: user
						});
					}else{
						res.render('userpage.ejs', {
							host: set.host,
							port: ((set.main)?'':':'+set.port),
							pageTitle: '얘의 정보',
							user: user
						});
					}
				}else{
					res.redirect('/');
				}

			}
		});
	})
	.post(function(req, res){
		// edit user information
	});

// sockets
io.on('connection', function (socket) {
	socketMod.setSocketAndAsync(socket, async);
	socketMod.setDBs(dbnotices, dbusers, dbdislikes, dbjoins, dbworks, dbowns);
	socket.emit('news', {});
	socket.on('namecheck', socketMod.nameCheck);
	socket.on('titlecheck', socketMod.titleCheck);
	socket.on('clientUpdateDislike', socketMod.updateDislike);
	socket.on('clientUpdateJoin', socketMod.updateJoin);
	// socket.on('');
});

// handle 404
app.use(function(req, res) {
	res.status(404).sendFile( __dirname+"/public/status/404NF.html");
});

// handle 500
// app.use(function(error, req, res, next) {
// 	res.status(500).send('500: Internal Server Error\n'+error);
// });

server.listen(set.port || 8080);
console.log((set.host+":"+(set.port || 8080)).cyan+"에서 서버 시작".green);<commit_msg>complete bug fix<commit_after>/// <reference path="typings/node/node.d.ts"/>
var express = require("express");
var app = express();

// fucking dependencies
var server = require('http').Server(app)
var io = require('socket.io')(server);
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var session = require('express-session');
var path = require('path');
var async = require('async');
var md = require("node-markdown").Markdown;
var fs = require("fs");

require('colors');	// for fantastic debug

// setting app -> too dizzy to fuck with
app.use(cookieParser());
app.use(session({ secret: "secret" }));

var set = require('./setting.json');

var options = process.argv;
for( var num in options){
	if(options[num] == "--port" || options[num] == "-p"){
		set.port = options[Number(num)+1];
	}
	if(options[num] == "--quiet" || options[num] == "-q"){
		console.log = function(){};
	}
}

app.set("view engine", "ejs");
app.set("views", __dirname+"/app/views");
app.use( express.static( __dirname + "/public" ));
app.use(bodyParser.urlencoded({ extended: false }));

// homemade modules
var dbnotices = require("./dbmodules/dbnotices.js");
var dbusers = require("./dbmodules/dbusers.js");
var dbdislikes = require("./dbmodules/dbdislikes.js");
var dbjoins = require("./dbmodules/dbjoins.js");
var dbworks = require("./dbmodules/dbworks.js");
var dbowns = require("./dbmodules/dbowns.js");

var socketMod = require("./socketMod.js");
var systemMod = require("./systemMod.js");

var auth = require("./auth.js");
auth.init(app);
var passport = auth.getPassport();

require('./database.js')();

// fucking routing
app.get('/auth/fb', passport.authenticate('facebook'));

app.get('/auth/fb/callback',
    passport.authenticate('facebook', {
		successRedirect: '/join',
        failureRedirect: '/loginFail'
	})
);

app.get('/loginSuccess', auth.checkAuthState, function(req, res){
	console.log("로그인성공");
    res.send(req.user);
});
app.get('/logout', function(req, res){
    req.logout();
    res.redirect('/');
});

app.route("/")
	.get(auth.inspect, function(req, res) {
		systemMod.checkBrowser(req.headers['user-agent'],function(browserName){
			// && browserVersion <= 9
			if (browserName == 'IE') {
				res.write("<script>window.open('http://www.opera.com/ko/computer');</script>");
				res.write("<script>window.open('https://www.mozilla.org/ko/firefox/new/');</script>");
				res.end("<script>location.href='https://www.google.com/chrome/browser/desktop/index.html';</script>");
			}
		});

		async.parallel([
			function(callback) {
				Works.findAll({
					order: ['dislikes', 'DESC']
				}).then(function(works, err) {
		            if(err) callback(err, null);
		            else {
						console.log(works);
						callback(null, works);
		            }
		        });
			},
			function(callback) {
				Dislikes.findAll().then(function(dislikes, err){
					if(err)	callback(err, null);
					else{
						console.log(dislikes);
						callback(null, dislikes);
					}
				});
			},
			function(callback) {
				Joins.findAll().then(function(joins, err){
					if(err) callback(err, null);
					else{
						console.log(joins);
						callback(null, joins);
					}
				});
			}
		], function(err, results) {
			if(err) console.error(err);
			else{
				var works = results[0];
				var dislikes = results[1];
				var joins = results[2];
				dbdislikes.getWorksDislikesNum(works, function(arrWorksDislikesNum) {
					res.render("frontpage.ejs", {
						works: works,
						login: req.authState,
						user: req.user,
						dislikes: dislikes,
						numDislikes: arrWorksDislikesNum,
						joins: joins,
						host: set.host,
						port: ((set.main)?'':':'+set.port)
					});
				});
			}
		});
	});

app.route("/makework")
	.get(auth.checkAuthState, function(req, res){
			res.render('makework.ejs', {
				host: set.host,
				login: true,
				port: ((set.main)?'':':'+set.port),
				userId: req.user.id,
				user: req.user,
				pageTitle: '공작 모의'
			});
	})
	.post(auth.checkAuthState, function(req, res){
		async.waterfall([
			function(cb){
				dbworks.createWork( req.body.name, req.body.desc, function(work, err) {
					if(err) console.error(err);
					else {
						cb( null, work );
					}
				});
			},
			function(work, cb){
				async.parallel([
					function(callback){
						dbowns.createOwn(req.user.id, work.id, function(own, err){
							if(err) console.error(err);
							else{
								console.log("공작 생성 :".cyan, work.name);
								fs.mkdir("./public/workpage/"+work.name, function(err){
									if(err) console.error(err);
						        	else{
										callback(null, {});
									}
								});
							}
						});
					},
					function(callback){
						var data = {
							workId: work.id,
							userId: req.user.id
						};
						dbjoins.toggleTuple( null, data, function(){
							callback(null, {});
						});
					}
				],
				function(err, result){
					cb( null, work );
				});
			},
			function( work, cb){
				async.parallel([
					function(callback) {
						fs.writeFile("./public/workpage/" + work.name + "/front.html", md(req.body.readme), function(err) {
							if(err) callback(err, null);
							else callback(null);
						});
					},
					function(callback) {
						fs.writeFile("./public/workpage/" + work.name + "/needs.html", md(req.body.needs), function(err) {
							if(err) callback(err, null);
							else callback(null);
						});
					}
				], function(err, results) {
					if(err) console.error(err);
					else {
						console.log("공작 생성 리스폰스");
						cb( err, results, work );
					}
				});
			}
		], function(err, result, work){
			res.send({code: 201, url: '/work/'+encodeURIComponent(work.name)});
		});
	});

app.route("/join")
	.get(auth.checkAuthState, function(req, res) {
		console.log("REQ", req.user)
		dbusers.searchByFbid(req.user.fbId, function(user, err) {
			console.log(user);
			if(err) console.error("ERROR".red, err);
			else if(user) {
				if(user.nickname == null)
					res.render('join.ejs', {
						pageTitle: '가입',
						name: req.user.name,
						login: false, //예외사항: 항시 거짓
						picture: req.user.picture,
						host: set.host,
						port: ((set.main)?'':':'+set.port)
					});
				else res.redirect('/'); //닉네임 이미 등록됨.
			} else {
				res.redirect('/'); //잘못된 접근: 세션은 인증되어 있는데 해당하는 정보가 DB에 없음
			}
		})
	})
	.post(auth.checkAuthState, function(req, res) {
		if(req.body.nickname) {
			dbusers.searchByNickname(req.body.nickname, function(user, err) {
				if(err) console.error(err);
				else if(!user) { // 가능한 닉네임
					dbusers.searchByFbid(req.user.fbId, function(user, err) {
						if(err) console.error(err);
						else if(!user){ // 그 세션의 uid에 해당하는 게 등록 안되어있음 (이상한 케이스)
							res.redirect('/');
						} else {
							dbusers.changeNickname(user, req.body.nickname, function(user, err) {
								if(err) {
									console.error(err);
									res.send("500").end();
								}
								else {
									console.log("유저 생성 :".cyan, user.name);
									res.send("201").end();
								}
							});
						}
					});
				} else {
					// 이미 존재하는 닉네임
					res.send("409").end();
				}
			})
		} else res.send("400").end();
	});

app.route("/work/:workName")
	.get(auth.inspect, function(req, res){
		Works.findOne({
			where: {
				name: req.params.workName
			}
		}).then(function(work, err) {
			if(err) console.error(err);
			else {
				dbdislikes.searchWorksDislikes(work.id, function(result){
					var numDislikes = result.length;
					res.render("workpage.ejs", {
						work: work,
						numDislikes: numDislikes,
						login: req.authState,
						host: set.host,
						port: ((set.main)?'':':'+set.port),
						user: (req.authState)?req.user:null
					});
				});
			}
		});
	})
	.post(function(req, res){
		var workId = req.params.workId;
		Works.findOne({
			where: {
				id: workId
			}
		}).then(function(work, err) {
			if(err) console.error(err);
			else {
				fs.mkdir("./WorkPage/"+work.name, function(err){
					console.log(err);
					if (req.body.reqType == "md") {
						var html = md(req.body.md);
						fs.writeFile("./WorkPage/"+work.name+"/front.html", html, function(err){
							if(err) console.log(err);
							work.updateAttributes({
								frontboard: "./WorkPage" + work.name + "/front.html"
							}).then(function(work, err){
								if(err) console.log(err);
								res.redirect("/work/"+work.id+"/"+work.name);
							});
						});
					}
					else if ( req.body.reqType == "need" ) {
						var html = md(req.body.need)
						fs.writeFile("./WorkPage/"+work.name+"/need.html", html, function(err){
							if(err) console.log(err);
							work.updateAttributes({
								needs: "./WorkPage" + work.name + "/need.html"
							}).then(function(work, err){
								if(err) console.log(err);
								res.redirect("/work/"+work.id+"/"+work.name);
							});
						});
					}
				});
			}
		});
	});

app.route("/user/:userNick")
	.get(auth.inspect, function(req, res){
		dbusers.searchByNickname(req.params.userNick, function(user, err){
			if(err) console.error(err);
			else{
				if(req.authState) {
					if( req.params.userNick == req.user.nickname ){
						res.render('userpage.ejs', {
							host: set.host,
							port: ((set.main)?'':':'+set.port),
							pageTitle: '너의 정보',
							login: req.authState,
							user: user
						});
					}else{
						res.render('userpage.ejs', {
							host: set.host,
							port: ((set.main)?'':':'+set.port),
							pageTitle: '얘의 정보',
							user: user
						});
					}
				}else{
					res.redirect('/');
				}

			}
		});
	})
	.post(function(req, res){
		// edit user information
	});

// sockets
io.on('connection', function (socket) {
	socketMod.setSocketAndAsync(socket, async);
	socketMod.setDBs(dbnotices, dbusers, dbdislikes, dbjoins, dbworks, dbowns);
	socket.emit('news', {});
	socket.on('namecheck', socketMod.nameCheck);
	socket.on('titlecheck', socketMod.titleCheck);
	socket.on('clientUpdateDislike', socketMod.updateDislike);
	socket.on('clientUpdateJoin', socketMod.updateJoin);
	// socket.on('');
});

// handle 404
app.use(function(req, res) {
	res.status(404).sendFile( __dirname+"/public/status/404NF.html");
});

// handle 500
// app.use(function(error, req, res, next) {
// 	res.status(500).send('500: Internal Server Error\n'+error);
// });

server.listen(set.port || 8080);
console.log((set.host+":"+(set.port || 8080)).cyan+"에서 서버 시작".green);<|endoftext|>