Last active
November 6, 2018 07:51
-
-
Save aditodkar/9694bf703e2ceb2cc7ef9605d9161c75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import './chat.css' | |
import io from "socket.io-client"; | |
import { connect } from 'react-redux'; | |
import { saveAuthor } from '../../store/actions/authorAction' | |
import { saveMessages } from '../../store/actions/messageAction' | |
import { deleteAuthor } from '../../store/actions/deleteAuthorAction' | |
import { fetchUsers } from '../../store/actions/userAction' | |
import { removeMessages } from '../../store/actions/removemessagesAction' | |
class Chat extends Component { | |
constructor(props){ | |
super(props); | |
this.state = { | |
message: '', | |
date: '', | |
author: '', | |
messages: [] | |
}; | |
this.sendMessage = this.sendMessage.bind(this); | |
this.addMessage = this.addMessage.bind(this); | |
this.socket = io('localhost:5000'); | |
this.socket.emit('LOGGEDIN_USER', { user1: this.props.match.params.user}); | |
} | |
componentDidMount() { | |
this.props.fetchUsers(); | |
this.socket.on('RECEIVE_MESSAGE', data => { | |
//console.log(data); | |
this.addMessage(data); | |
}); | |
this.socket.emit('LOGGEDIN_USER', { user1: this.props.match.params.user}); | |
} | |
sendMessage(event) { | |
event.preventDefault(); | |
if(this.state.message !== ''){ | |
this.socket.emit('SEND_MESSAGE', { | |
author: this.props.match.params.user, | |
message: this.state.message, | |
date: Date.now() | |
}); | |
} | |
}; | |
addMessage(data) { | |
console.log(data); | |
this.props.saveAuthor(this.props.match.params.user) | |
this.props.saveMessages(data[0].conversation) | |
this.setState({ | |
message: '' | |
}); | |
}; | |
handleClick = (userName) => { | |
console.log(userName) | |
this.props.removeMessages() | |
this.socket.emit('GET_USER', { user2: userName }); | |
} | |
render() { | |
return ( | |
<div> | |
<h2>Hello {this.props.match.params.user}</h2> | |
<div className="container"> | |
<div id="chat"> | |
<div className="card"> | |
<div id="messages" className="card-block"> | |
{ this.props.messages && this.props.messages.map((message, index) => { | |
if(message.author === this.props.match.params.user){ | |
return ( | |
<div key={index} className="msgBoxRight"><p className="msgTextRight">{message.message}</p></div> | |
) | |
}else{ | |
return ( | |
<div key={index} className="msgBoxLeft"><p className="msgTextLeft">{message.message}</p></div> | |
) | |
} | |
})} | |
</div> | |
<div id="feedback"></div> | |
<div className="row"> | |
<div className="column"> | |
<input id="inputmsg" type="text" placeholder="Enter Message...." | |
value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/> | |
</div> | |
<div className="column2"> | |
<button id="send" className="button" onClick={this.sendMessage}>Send</button> | |
</div> | |
<div className="upload"> | |
</div> | |
</div> | |
</div> | |
</div> | |
<div className="userlist"> | |
<div> | |
<h3>All users:</h3> | |
{this.props.match.params.user ? this.props.allusers.map((val,index) => { | |
if(this.props.match.params.user === val.username){ | |
return null | |
}else { | |
return <div className="usernameList" key={index}><button onClick={() => this.handleClick(val.username)} type="button">{val.username}</button></div> | |
} | |
}) : ""} | |
</div> | |
</div> | |
</div> | |
</div> | |
) | |
} | |
} | |
const mapStateToProps = state => ({ | |
author: state.chat.author, | |
messages: state.chat.messages, | |
allusers: state.allusers.items | |
}) | |
export default connect (mapStateToProps, { saveAuthor, saveMessages, removeMessages, deleteAuthor, fetchUsers })(Chat); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SAVE_AUTHOR, SAVE_MESSAGES, DELETE_AUTHOR, REMOVE_MESSAGES } from '../actions/types'; | |
const initialState = { | |
author: '', | |
message: '', | |
messages: [] | |
} | |
export default function (state = initialState, action) { | |
switch (action.type) { | |
case SAVE_MESSAGES: | |
return { | |
...state, | |
messages: [...state.messages, ...action.payload.messages] | |
}; | |
case REMOVE_MESSAGES: | |
return { | |
...state, | |
messages: [] | |
}; | |
case SAVE_AUTHOR: | |
return { | |
...state, | |
author: action.payload | |
}; | |
case DELETE_AUTHOR: | |
return { | |
...state, | |
author: '' | |
}; | |
default: | |
return state; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { REMOVE_MESSAGES } from './types'; | |
export const removeMessages = () => ({ | |
type: REMOVE_MESSAGES | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SAVE_MESSAGES } from './types'; | |
export const saveMessages = (messages) => ({ | |
type: SAVE_MESSAGES, | |
payload: { messages } | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const mongoose = require('mongoose'); | |
const bodyParser = require('body-parser'); | |
const socket = require('socket.io'); | |
const path = require('path'); | |
const message = require('./model/message'); | |
const Conversation = require('./model/conversation'); | |
const User = require('./model/user'); | |
const app = express(); | |
app.use(bodyParser.json()); | |
const mongoURI = require('./config/keys').mongoURI; | |
mongoose.connect(mongoURI, {useNewUrlParser: true}, function (err,res) { | |
if(err){ | |
console.log("There is error: " + err); | |
}else{ | |
console.log("Connected to mongo database") | |
} | |
}) | |
app.use(function(req, res, next) { | |
//to allow cross domain requests to send cookie information. | |
res.header('Access-Control-Allow-Credentials', true); | |
// origin can not be '*' when crendentials are enabled. so need to set it to the request origin | |
res.header('Access-Control-Allow-Origin', req.headers.origin); | |
// list of methods that are supported by the server | |
res.header('Access-Control-Allow-Methods','OPTIONS,GET,PUT,POST,DELETE'); | |
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, X-XSRF-TOKEN'); | |
next(); | |
}); | |
app.post('/api/users', (req, res) => { | |
const user = new User({ | |
_id: new mongoose.Types.ObjectId(), | |
firstName: req.body.firstName, | |
username: req.body.username, | |
email: req.body.email | |
}); | |
user.save().then( result => { | |
console.log(result); | |
}).catch( err => console.log(err)) | |
res.status(200).json({ | |
message: 'Handling POST req for users at api/users', | |
userCreated: user | |
}); | |
}) | |
app.get('/api/users', (req, res) => { | |
User.find({}).then(eachOne => { | |
res.json(eachOne); | |
}); | |
}) | |
let db = mongoose.connection; | |
db.once('open', function() { | |
console.log("Database is now connected"); | |
let io = socket(server); | |
io.on("connection", function(socket){ | |
console.log("Socket Connection Established with ID :"+ socket.id) | |
socket.on('disconnect', function(){ | |
console.log('User Disconnected'); | |
}); | |
// let chat = db.collection('chat'); | |
let conversation = db.collection('conversation'); | |
let user1,user2; | |
socket.on('LOGGEDIN_USER', function (data) { | |
// console.log(data); | |
user1 = data.user1; | |
}); | |
socket.on('GET_USER', function(data) { | |
// console.log(data); | |
user2 = data.user2; | |
console.log("This is user1 "+ user1) | |
console.log("This is user2 "+ user2) | |
conversation.find({ $and : [ { user1: user1 }, { user2: user2 } ] }).toArray(function (err, res) { | |
if(err){ | |
throw err; | |
} | |
console.log(res) | |
// Emit the messages | |
io.emit('RECEIVE_MESSAGE', res); | |
}) | |
}); | |
socket.on('SEND_MESSAGE', function(data){ | |
let author = data.author; | |
let message = data.message; | |
let date = data.date; | |
// Check for name and message | |
if(author !== '' || message !== '' || date !== ''){ | |
// Insert message | |
// chat.insert({author:author, message: message, date:date}, function(){ | |
// io.emit('RECEIVE_MESSAGE', [data]); | |
// }); | |
// conversation.findOneAndUpdate( | |
// { user1 : user1, user2: user2 }, | |
// { conversations : { $push : { author, message, date } } }, | |
// { upsert : true} | |
// ); | |
conversation.findOne({ $and :[{user1: user1}, {user2: user2}] }, function (err, existingConversation){ | |
if(existingConversation === null){ | |
conversation.insert({user1: user1, user2: user2, conversation: [{author: author, message: message, date:date}] }, function (){ | |
io.emit('RECEIVE_MESSAGE', [data]); | |
}) | |
}else{ | |
conversation.update({user1: user1, user2: user2}, | |
{$push: {conversation : { author : author ,message : message,date : date }} }) | |
} | |
}) | |
} | |
}); | |
// socket.on('TYPING', function(data){ | |
// socket.broadcast.emit('TYPING', data) | |
// }) | |
// chat.find().sort({_id:1}).toArray(function(err, res){ | |
// if(err){ | |
// throw err; | |
// } | |
// // Emit the messages | |
// io.emit('RECEIVE_MESSAGE', res); | |
// }); | |
// conversation.find({ $and : [ {user1: user1}, {user2: user2} ] }).toArray(function (err, res) { | |
// if(err){ | |
// throw err; | |
// } | |
// // Emit the messages | |
// io.emit('RECEIVE_MESSAGE', res); | |
// }) | |
}) | |
}); | |
const port = 5000; | |
let server = app.listen(5000, function(){ | |
console.log('server is running on port 5000') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment