Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

working chat with new message indicator, user profile, and real time feeds #5

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules/
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
# project_superchat
Build a realtime multi-room chat application. Make it super.

Richard Bell

To run, clone repo
Install Redis
npm start
77 changes: 77 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

const dataMgr = require('./bin/dataMgr');
// dispatcher for IO requests from client_sockets
io.on('connection', client => {
console.log("New connection!")

client.on('addRoom', (roomName) => {
dataMgr.addRoom(roomName).then(function(){
io.emit('newRoom', roomName);
});
});

client.on('getMessages', (roomName) => {
dataMgr.getMessages(roomName).then(function(data){
client.emit('messageList', data);
})
});

client.on('sendMessage', (message) => {
dataMgr.sendMessage(message.room, message.user, message.text).then(function(data){
io.emit('newMessage', {room: message.room, user: message.user, text: message.text});
})
});
});

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

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

app.use('/', index);
app.use('/users', users);

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

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = {app: app, server: server};
153 changes: 153 additions & 0 deletions bin/dataMgr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
const redisClient = require("redis").createClient();
const debug = require('debug')('dataMgr');
const ROOMKEY = "rooms";
const USERKEY = "users";

// uncomment for clean-up
// redisClient.flushall();

// promise returns 1 for room add 0 for duplicate room
function addRoom(room) {
debug(`requesting add room "${room}"`);
return new Promise(function(resolve, reject) {
redisClient.sadd(ROOMKEY, room, function(err, data) {
if (err) reject(err);
debug(`room added "${room}"`);
resolve(data);
});
});
}

// promise returns array with list of rooms
function listRooms() {
debug(`requesting room list`);
return new Promise(function(resolve, reject) {
redisClient.smembers(ROOMKEY, function(err, data) {
if (err) reject(err);
debug('returning room list');
resolve(data);
});
});
}

function addUser(userName, userProfile) {
debug(`adding new user "${userName}" with profile ${userProfile}`);
return new Promise(function(resolve, reject) {
redisClient.hset(USERKEY, userName, JSON.stringify(userProfile), function(err, data) {
if (err) reject(err);
debug(`user added "${userName}"`);
resolve(data);
});
});
}

// promise returns object containing the profile associated with userName or Null object if doesn't exist
function getUser(userName) {
debug(`requesting user "${userName}"`);
return new Promise(function(resolve, reject) {
redisClient.hget(USERKEY, userName, function( err, data) {
if (err) reject(err);
debug(`user "${userName}" returned with profile ${data}`);
resolve(JSON.parse(data));
});
});
}

// promise returns 1 if user exists and 0 otherwise
function isUser(userName) {
debug(`checking user exists "${userName}"`);
return new Promise(function(resolve, reject) {
redisClient.hexists(USERKEY, userName, function (err, data) {
if (err) reject(err);
debug(`user "${userName}" hexist with response ${data}`);
resolve(data);
})
});
}

// promise resolves to number for message added where number is count of messages in room
function sendMessage(roomName, userName, msgText) {
debug(`sending message "${msgText}" to room "${roomName}" from user "${userName}"`);
return new Promise(function(resolve, reject) {
let message = {text: msgText,
sender: userName,
sentTime: Date.now() };
redisClient.rpush(roomName, JSON.stringify(message), function (err, data) {
if (err) reject(err);
debug(`sent "${msgText}" to "${roomName}" from "${userName}"`);
resolve(data);
})
});
}

// promise resolves to array containing message objects
function getMessages(roomName) {
debug(`requesting messages for "${roomName}"`);
return new Promise(function(resolve, reject) {
redisClient.lrange(roomName, 0, -1, function(err,data) {
if (err) reject(err);
debug(`messages for room "${roomName}" are "${data}"`);
let msgList = [];
data.forEach(function(message) {
msgList.push(JSON.parse(message));
});
resolve(msgList);
})
});
}

module.exports = {
addRoom,
listRooms,
addUser,
getUser,
isUser,
sendMessage,
getMessages
};


/*
sendMessage('test room', 'fred', 'hello world').then(function(data){
console.log(data);
});
sendMessage('test room', 'george', 'Goodbye cruel world').then(function(data){
console.log(data);
});
getMessages('test room').then(function(data){
console.log(data);
});

addUser('fred', {fullname: 'Fred Smith', createDate: Date.now()}).then(function(data){
console.log(data);
});

getUser('fred').then(function(data){
console.log(data);
});

getUser('george').then(function(data){
console.log(data);
});

isUser('fred').then(function(data){
console.log(data);
});
isUser('george').then(function(data){
console.log(data);
});

addRoom("test").then(function(data){
console.log(data);
});
addRoom("test1").then(function(data){
console.log(data);
});
addRoom("test1").then(function(data){
console.log(data);
});
listRooms().then(function(data){
console.log(data);
process.exit();
});
*/
90 changes: 90 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app').app;
var debug = require('debug')('project-superchat:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

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

/**
* Create HTTP server.
*/

var server = require('../app').server;

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "project-superchat",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "^2.6.6",
"express": "^4.15.2",
"hbs": "~4.0.1",
"morgan": "~1.8.1",
"redis": "^2.7.1",
"serve-favicon": "~2.4.2",
"socket.io": "^2.0.1",
"socket.io-client": "^2.0.1"
}
}
Loading