Browse Source

Added a consistent route implementation. Made our single RethinkDB connection global. Renamed utils.js to global.js to make it more generic. Added a EventEmitter setup to coreHandler so that it can talk back to socketHandler without needing to require it.

Cameron Kline 8 years ago
parent
commit
3ce45ff3ff
7 changed files with 131 additions and 101 deletions
  1. 5 11
      app.js
  2. 58 41
      logic/coreHandler.js
  3. 26 8
      logic/expressHandler.js
  4. 1 0
      logic/global.js
  5. 28 26
      logic/socketHandler.js
  6. 12 14
      logic/stations.js
  7. 1 1
      public/js/app.js

+ 5 - 11
app.js

@@ -14,8 +14,9 @@ const express    = require('express'),
       r          = require('rethinkdb');
 
 // custom modules
-const coreHandler = require('./logic/coreHandler'),
-      socketHandler = require('./logic/socketHandler'),
+const global         = require('./logic/global'),
+      coreHandler    = require('./logic/coreHandler'),
+      socketHandler  = require('./logic/socketHandler'),
       expressHandler = require('./logic/expressHandler');
 
 // setup express and socket.io
@@ -24,23 +25,16 @@ const server = app.listen(80);
 const io = require('socket.io')(server);
 
 // connect to our database before doing anything else
-r.connect( { host: 'localhost', port: 28015, db: 'musare' }, (err, conn) => {
+r.connect( { host: 'localhost', port: 28015, db: 'musare' }, (err, rc) => {
 	if (err) {
 		console.log(err);
 	}
 	else {
 
-		app.use(session({
-			resave: true,
-			saveUninitialized: false,
-			secret: config.get("secret"),
-			cookie: { httpOnly: true, maxAge: 2419200000 }
-		}));
+		global.rc = rc;
 
 		app.use(express.static(__dirname + '/public'));
 
-		coreHandler.setup(conn);
-
 		socketHandler(coreHandler, io);
 		expressHandler(coreHandler, app);
 	}

+ 58 - 41
logic/coreHandler.js

@@ -1,9 +1,10 @@
 'use strict';
 
 // nodejs modules
-const path = require('path'),
-      fs   = require('fs'),
-      os   = require('os');
+const path   = require('path'),
+      fs     = require('fs'),
+      os     = require('os'),
+      events = require('events');
 
 // npm modules
 const config    = require('config'),
@@ -12,21 +13,26 @@ const config    = require('config'),
       r         = require('rethinkdb');
 
 // custom modules
-const utils = require('./utils');
+const global    = require('./global'),
+      stations = require('./stations');
 
-var dbConnection = null;
+var eventEmitter = new events.EventEmitter();
 
 module.exports = {
 
-	setup: function (dbConn) {
-		dbConnection = dbConn;
-	},
+	// module functions
 
-	disconnect: function () {//TODO Find out why we even need this.
+	on: function (name, cb) {
+		eventEmitter.on(name, cb);
+	},
 
+	emit: function (name, data) {
+		eventEmitter.emit(name, data);
 	},
 
-	login: function (user, cb) {
+	// core route handlers
+
+	'/users/login': function (user, cb) {
 
 		if (!user.username || !user.password) {
 			return cb({ status: 'error', message: 'Invalid login request' });
@@ -52,7 +58,7 @@ module.exports = {
 		});
 	},
 
-	register: function (user, cb) {
+	'/users/register': function (user, cb) {
 
 		if (!user.email || !user.username || !user.password) {
 			return cb({ status: 'error', message: 'Invalid register request' });
@@ -61,55 +67,66 @@ module.exports = {
 		// TODO: Implement register
 	},
 
-	rooms: function (cb) {
-		var _rooms = stations.map(function(result) {
+	'/stations': function (cb) {
+		cb(stations.getStations().map(function (result) {
 			return {
 				id: result.getId(),
 				displayName: result.getDisplayName(),
 				description: result.getDescription(),
 				users: result.getUsers()
 			}
-		});
-		cb(_rooms);
+		}));
 	},
 
-	joinRoom: function (id, cb) {//TODO Think of a better name than joinRoom
+	'/stations/join/:id': function (id, user, cb) {
 
-		var room = getStation(id);
-		socket.custom.roomId = id;
+		var station = stations.getStation(id);
 
-		var userInfo = {
-			username: socket.custom.user.username
-		};
+		if (station) {
 
-		// tell all the users in this room that someone is joining it
-		io.sockets.clients().forEach(function (otherSocket) {
-			if (otherSocket != socket && otherSocket.custom.roomId === id) {
-				otherSocket.emit('roomUserJoin', { user: userInfo });
-			}
-		});
-		//TODO Add errors.
-		return cb({
-			status: 'joined',
-			data: {
-				room: room
-			}
-		});
+			user.stationId = id;
+
+			this.emit('station-joined', {
+				user: {
+					id: user.id,
+					username: user.username
+				}
+			});
+
+			return cb({
+				status: 'joined',
+				data: {
+					displayName: station.getDisplayName(),
+					users: station.getUsers(),
+					currentSong: station.getCurrentSong()
+				}
+			});
+		}
+		else {
+			return cb({ status: 'error', message: 'Room with that ID does not exists' });
+		}
 	},
 
-	search: function (query, cb) {//TODO Replace search with a better name.
-		request('https://www.googleapis.com/youtube/v3/search?' + [
-				'part=snippet', `q=${encodeURIComponent(query)}`, `key=${config.get('apis.youtube.key')}`, 'type=video', 'maxResults=25'
-			].join('&'), (err, res, body) => {
+	'/stations/search/:query': function (query, cb) {
+
+		var params = [
+			'part=snippet',
+			`q=${encodeURIComponent(query)}`,
+			`key=${config.get('apis.youtube.key')}`,
+			'type=video',
+			'maxResults=25'
+		].join('&');
+
+		request(`https://www.googleapis.com/youtube/v3/search?${params}`, function (err, res, body) {
 			if (err) {
-				socket.emit('search', { status: 'error', message: 'Failed to make request' });
+				return cb({ status: 'error', message: 'Failed to make request' });
 			}
 			else {
 				try {
-					socket.emit('search', { status: 'success', body: JSON.parse(body) });
+					return cb({ status: 'success', body: JSON.parse(body) });
 				}
 				catch (e) {
-					socket.emit('search', { status: 'error', message: 'Non JSON response' });
+					return cb({ status: 'error', message: 'Non JSON response' });
 				}
 			}
 		});

+ 26 - 8
logic/expressHandler.js

@@ -2,26 +2,44 @@
 
 module.exports = function (core, app) {
 
-	app.post('/login', function (user) {
-		core.login(user, function (result) {
+	app.post('/users/login', function (req, res) {
+
+		// TODO: Give this a better error message
+		if (!req.body.user) {
+			return res.send(JSON.stringify({ 'status': 'error', 'message': 'invalid request' }));
+		}
+
+		core['/users/login'](req.body.user, function (result) {
+			res.send(JSON.stringify(result));
+		});
+	});
+
+	app.post('/users/register', function (req, res) {
+
+		// TODO: Give this a better error message
+		if (!req.body.user) {
+			return res.send(JSON.stringify({ 'status': 'error', 'message': 'invalid request' }));
+		}
+
+		core['/users/register'](req.body.user, function (result) {
 			res.send(JSON.stringify(result));
 		});
 	});
 
-	app.post('/register', function (user) {
-		core.register(user, function (result) {
+	app.get('/stations', function (req, res) {
+		core['/stations'](function (result) {
 			res.send(JSON.stringify(result));
 		});
 	});
 
-	app.get('/rooms', function () {
-		core.rooms(function (result) {
+	app.get('/stations/join/:id', function (req, res) {
+		core['/stations/join/:id'](req.params.id, function (result) {
 			res.send(JSON.stringify(result));
 		});
 	});
 
-	app.get('/search/:query', function () {//TODO Replace search with a better name.
-		core.search(query, function (result) {
+	app.get('/stations/search/:query', function (req, res) {
+		core['/stations/search/:query'](req.params.query, function (result) {
 			res.send(JSON.stringify(result));
 		});
 	});

+ 1 - 0
logic/utils.js → logic/global.js

@@ -30,6 +30,7 @@ function Timer(callback, delay, paused) {
 }
 
 module.exports = {
+	rc: null, // RethinkDB Connection, this gets set in app.js
 	htmlEntities: function(str) {
 		return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
 	},

+ 28 - 26
logic/socketHandler.js

@@ -1,51 +1,53 @@
 'use strict';
 
-module.exports = function (base, io) {
+module.exports = function (core, io) {
+
+	// tell all the users in this room that someone is joining it
+	core.on('station-joined', function (user) {
+		io.sockets.clients().forEach(function (socket) {
+			if (socket.request.user.id != user.user.id && socket.request.user.roomId === id) {
+				socket.emit('station-joined', user);
+			}
+		});
+	});
 
 	io.on('connection', function (socket) {
 
 		socket.on('disconnect', function () {
-			base.disconnect(function () {
-				console.log('User has disconnected');
-			});
+			console.log('User has disconnected');
 		});
 
-		socket.on('login', function (user, cb) {
-			base.login(user, function (result) {
-				cb(result);
+		socket.on('/users/login', function (user) {
+			core['/users/login'](user, function (result) {
+				socket.emit('/users/login', result);
 			});
 		});
 
-		socket.on('register', function (user, cb) {
-			base.register(user, function (result) {
-				cb(result);
+		socket.on('/users/register', function (user) {
+			core['/users/register'](user, function (result) {
+				socket.emit('/users/register', result);
 			});
 		});
 
-		socket.on('getRooms', function () {
-			base.rooms(function (result) {
-				socket.emit('rooms', result);
+		socket.on('/stations', function () {
+			core['/stations'](function (result) {
+				socket.emit('/stations', result);
 			});
 		});
 
-		socket.on('room', function (id, cb) {//TODO Replace 'room' with a better name.
-			base.room(id, function (result) {
-				var info = {
-					displayName: result.getDisplayName(),
-					users: result.getUsers(),
-					currentSong: result.getCurrentSong()
-				};
-				cb(info);
+		socket.on('/stations/join/:id', function (id) {
+			core['/stations/join/:id'](id, function (result) {
+				socket.emit('/stations/join/:id', result);
 			});
 		});
 
-		socket.on('search', function (query) {//TODO Replace search with a better name.
-			base.search(query, function (result) {
-				socket.emit('search', result);
+		socket.on('/stations/search/:query', function (query) {
+			core['/stations/search/:query'](query, function (result) {
+				socket.emit('/stations/search/:query', result);
 			});
 		});
 
-		socket.emit('ready');//TODO Remove this
-
+		// this lets the client socket know that they can start making request
+		socket.emit('ready');
 	});
 };

+ 12 - 14
logic/stations.js

@@ -1,8 +1,8 @@
 
 // custom modules
-const utils = require('./utils');
+const global = require('./global');
 
-function Station (id, data, dbConn) {
+function Station (id, data) {
 
 	var self = this;
 
@@ -17,7 +17,6 @@ function Station (id, data, dbConn) {
 	var displayName = data.displayName;
 	var description = data.description;
 	var timer;
-	var dbConnection = dbConn;
 
 	this.skipSong = function() {
 		if (playlist.length > 0) {
@@ -31,7 +30,7 @@ function Station (id, data, dbConn) {
 			}
 			skipVotes = 0;
 			currentSong = playlist[currentSongIndex];
-			timer = new utils.Timer(function() {
+			timer = new global.Timer(function() {
 				console.log("Skip!");
 				self.skipSong();
 			}, currentSong.duration, paused);
@@ -49,7 +48,7 @@ function Station (id, data, dbConn) {
 		//TODO Emit
 	};
 	this.retrievePlaylist = function() {
-		//TODO Use Rethink to get the Playlist for this room
+		//TODO Use Rethink to get the Playlist for this station
 	};
 	this.pause = function() {
 		if (!paused) {
@@ -118,15 +117,10 @@ function Station (id, data, dbConn) {
 module.exports = {
 
 	stations: [],
-	dbConnection: null,
-
-	setup: function (dbConn) {
-		this.dbConnection = dbConn;
-	},
 
 	initStation: function (id, data) {
 		if (!this.getStation(id)) {
-			var station = new Station(id, data, this.dbConnection);
+			var station = new Station(id, data);
 			this.stations.push(station);
 			return station;
 		}
@@ -143,6 +137,10 @@ module.exports = {
 		return s;
 	},
 
+	getStations: function () {
+		return this.stations;
+	},
+
 	// creates a brand new station
 	createStation: function (data) {
 		//TODO: add createStation functionality
@@ -150,9 +148,9 @@ module.exports = {
 	},
 
 	// loads a station from the database
-	loadStation: function (data) {
-		//TODO: Get this from RethinkDB
-		this.initStation({
+	loadStation: function (id) {
+		//TODO: Get the data from RethinkDB
+		this.initStation(id, {
 			playlist: [
 				{
 					mid: "3498fd83",

+ 1 - 1
public/js/app.js

@@ -133,7 +133,7 @@ window.onload = function () {
 			}
 		},
 		register: function () {
-			socket.emit('register', {
+			socket.emit('/users/register', {
 				email: data.modals.register.email,
 				username: data.modals.register.username,
 				password: data.modals.register.password,