Skip to content

Commit

Permalink
working chat
Browse files Browse the repository at this point in the history
  • Loading branch information
muganwas committed Mar 2, 2020
1 parent 6a5c58c commit 3019102
Show file tree
Hide file tree
Showing 10 changed files with 292 additions and 98 deletions.
34 changes: 17 additions & 17 deletions public/app/bundle.js

Large diffs are not rendered by default.

79 changes: 59 additions & 20 deletions src/app/components/Header/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
fetchFriendsRequests
} from 'reduxFiles/dispatchers/userDispatchers';
import {
fetchedUsersOnline
fetchedUsersOnline,
dispatchRecievedMessage,
//dispatchSentMessage
} from 'reduxFiles/dispatchers/chatDispatchers';
import {
logout,
Expand All @@ -21,9 +23,10 @@ import {
alertSocketError,
socketConnected,
socket,
checkLoginStatus,
confirmToken
} from 'reduxFiles/dispatchers/authDispatchers';
// import { setChatId } from '../../misc/functions';
import { RECONNECT_TIMER } from 'misc/constants';

class Header extends Component {
constructor(){
Expand All @@ -42,6 +45,7 @@ class Header extends Component {
friendAction: false,
onlineUsers: null
}
this.reconnectTimer = null;
}

componentDidMount(){
Expand All @@ -50,13 +54,15 @@ class Header extends Component {
genInfo,
updateGenInfo,
confirmLoggedIn,
loginInfo: { socketOpen, unAuthorizedConnection },
loginInfo,
friendsInfo: { inComingRequests, fetchedFriends },
dispatchSocketConnected,
openSocket
} = this.props;
let { info: { avURL, uid, chatkitUser: { token } }, fetched } = genInfo;
let { notificationClass } = this.state;
const { socketOpen, unAuthorizedConnection } = loginInfo;
const { info: { avURL, uid, chatkitUser: { token } }, fetched } = genInfo;
const { notificationClass } = this.state;

//dispatch local storage genInfo to props
if (!loggedIn) {
let storedInfo = localStorage.getItem('genInfo');
Expand Down Expand Up @@ -97,9 +103,10 @@ class Header extends Component {
});

socket.on('unauthorized', reason => {
const { dispatchSocketError } = this.props;
console.log('Unauthorized:', reason);
const { dispatchSocketError, signOut } = this.props;
// console.log('Unauthorized:', reason);
dispatchSocketError(reason);
signOut();
});

socket.on('disconnect', reason => {
Expand All @@ -114,10 +121,16 @@ class Header extends Component {
socket.on("join-alert", data => {
const { dispatchUsersOnline } = this.props;
dispatchUsersOnline(data);
console.log('You connected');
});

socket.on("chat-message", data =>{
const { name, message } = data;
socket.on("chat-message", data => {
const { chatInfo: { messages }, storeRecievedMessages } = this.props;
const { sender } = data;
let newMessages = {...messages};
if (newMessages[sender]) newMessages[sender].push(data);
else newMessages[sender] = [data];
storeRecievedMessages(newMessages);
//do something when message recieved
});

Expand All @@ -128,7 +141,8 @@ class Header extends Component {
});

socket.on("user-connected", data => {
//do something when user connects
const { dispatchUsersOnline } = this.props;
dispatchUsersOnline(data);
});
if (!socketOpen && !unAuthorizedConnection && token && uid) openSocket(this.props);
}
Expand All @@ -143,7 +157,7 @@ class Header extends Component {
getUsers,
getFriends,
getFriendsRequests,
uploadUsersInfoToFB
uploadUsersInfoToFB,
} = this.props;
let { uid, avURL } = info;
if (!fetched) getUsers();
Expand All @@ -167,11 +181,17 @@ class Header extends Component {
// show nofication icon if there are incoming requests
if (fetchedFriends && inComingRequests.length > 0 && notificationClass.includes('hidden')) this.setState({notificationClass:"fas fa-circle alert"});
else if (fetchFriends && inComingRequests.length === 0 && !notificationClass.includes('hidden')) this.setState({notificationClass:"fas fa-circle alert hidden"});

if (!socketOpen && !unAuthorizedConnection && token && uid) openSocket(this.props);
if (loggedIn && !socketOpen && !unAuthorizedConnection) {
clearInterval(this.reconnectTimer);
this.reconnectTimer = setInterval(() => {
console.log('trying to reconnect...');
openSocket(this.props);
}, RECONNECT_TIMER);
}
else clearInterval(this.reconnectTimer);
}

showMenu = ()=>{
showMenu = () => {
var menu = this.state.dropDownStyle;
if ( menu !== "visible"){
this.setState({
Expand Down Expand Up @@ -212,10 +232,10 @@ class Header extends Component {
"/";
return (
<div className="mainNav">
{ loggedIn?
{ loggedIn ?
<ProfileImage dname={ dname } userId = { uid } />:
null }
{ loggedIn?
{ loggedIn ?
<div className="nav">
<span className={ homeStyle } onClick={ () => this.goTo("/home") }></span>
<span className={ friendsStyle } onClick={ () => this.goTo("/friends") }>
Expand All @@ -234,7 +254,7 @@ class Header extends Component {
</ul>
</div>
</span>
</div>:
</div> :
<div>
<span className={ loginStyle } onClick={ () => this.goTo(notFoundPath) }></span>
</div> }
Expand All @@ -247,18 +267,31 @@ Header.propTypes = {
genInfo: PropTypes.object,
info: PropTypes.object,
loginInfo: PropTypes.object,
friendsInfo: PropTypes.object,
chatInfo: PropTypes.object,
confirmLoggedIn: PropTypes.func.isRequired,
updateGenInfo: PropTypes.func.isRequired,
signOut: PropTypes.func.isRequired,
dispatchUsersOnline: PropTypes.func.isRequired
dispatchUsersOnline: PropTypes.func.isRequired,
getUsers: PropTypes.func,
openSocket: PropTypes.func,
closeSocket: PropTypes.func,
confirmUserToken: PropTypes,
logingStatusConfirmation: PropTypes.func,
dispatchSocketConnected: PropTypes.func,
dispatchSocketError: PropTypes.func,
getFriends: PropTypes.func,
getFriendsRequests: PropTypes.func,
uploadUsersInfoToFB: PropTypes.func,
}

const mapStateToProps = state => {
return {
genInfo: state.genInfo,
info: state.genInfo.info,
loginInfo: state.loginInfo,
friendsInfo: state.friendsInfo
friendsInfo: state.friendsInfo,
chatInfo: state.chatInfo
}
}

Expand All @@ -276,11 +309,14 @@ const mapDispatchToProps = dispatch => {
confirmUserToken: userToken => {
dispatch(confirmToken(userToken));
},
logingStatusConfirmation: (confirmLoggedIn, loginInfo, genInfo) => {
dispatch(checkLoginStatus(confirmLoggedIn, loginInfo, genInfo));
},
dispatchSocketConnected: () => {
dispatch(socketConnected());
},
dispatchSocketError: error => {
dispatch(alertSocketError(error))
dispatch(alertSocketError(error));
},
getFriends: info => {
dispatch(fetchFriends(info));
Expand All @@ -302,6 +338,9 @@ const mapDispatchToProps = dispatch => {
},
dispatchUsersOnline: users => {
dispatch(fetchedUsersOnline(users));
},
storeRecievedMessages: message => {
dispatch(dispatchRecievedMessage(message));
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/app/components/MainComponent/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ class App extends Component {
false : localStorage.getItem("exists");

/**Determine page to redirect to */

if (uid) {
console.log(genInfo)
//console.log(genInfo)
if (genInfo) this.props.sendGenInfo(genInfo);
//check if user session is still valid
if (sessionToken) checkSessionValidity(sessionToken);
Expand Down
131 changes: 104 additions & 27 deletions src/app/components/Messaging/ChatComponent.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,110 @@
import React, { useEffect } from 'react';
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Text, View, TextInput, TouchableOpacity } from 'react-native';
import {
logout,
loginConfirmed,
connectToChatServer,
socket
} from 'reduxFiles/dispatchers/authDispatchers';
import {
// dispatchRecievedMessage,
dispatchSentMessage
} from 'reduxFiles/dispatchers/chatDispatchers';
import { TextInput, TouchableOpacity, Text, View, ScrollView } from 'react-native';
import styles from './localStyles/mainStyles';

const ChatComponent = ({chatInfo: { selectedUser }, friendsInfo: { users }}) => {
useEffect(() => {
//console.log(chatInfo)
}, [])
return (
<View style={styles.chatContainer}>
<View style={styles.userInfo}>
<Text style={styles.userName}>
{ users.map(user => {
if (user.uid === selectedUser ) return user.dname
})}
</Text>
</View>
<View style={styles.messages}>
<Text></Text>
class ChatComponent extends React.Component {
state = {
message: ''
}

tempStoreMessage = e => {
const message = e.target.value;
this.setState({message});
}

sendMessage = () => {
const { storeSentMessages, chatInfo: { selectedUser, messages }, genInfo: { info: { uid } } } = this.props;
const message = this.state.message;
const messageObj = {message, recipient: selectedUser, sender: uid};
if (message.length) {
let newMessages = {...messages};
if (newMessages[selectedUser]) newMessages[selectedUser].push(messageObj);
else newMessages[selectedUser] = [messageObj];
storeSentMessages(newMessages)
socket.emit('sent-message', messageObj);
this.setState({message:''});
}
else console.log('empty message')
}
render(){
const { chatInfo: { selectedUser, messages }, friendsInfo: { users }, genInfo: { info: { uid } } } = this.props;
const enabledSend = (this.state.message).length;

const displayMessages = () => {
return <View style={styles.messagesSubContainer}>
{
Object.keys(messages).map(key => {
const usersMessages = messages[key]
if (String(key) === String(selectedUser)) {
return <View key={key} style={ styles.messagesSubContainer }>
{
Object.keys(usersMessages).map(key => {
const sender = usersMessages[key].sender;
const message = usersMessages[key].message;
if ( sender === selectedUser) {
return <View key={key} style={styles.recievedContainer}>
<Text style={styles.recievedMsg}>{ message }</Text>
</View>
}
else if (String(sender) === String(uid)) {
return <View key={key} style={styles.sentContainer}>
<Text style={styles.sentMsg}>{ message }</Text>
</View>
}
else return;
})
}
</View>
}
})
}
</View>
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
placeholder="type message..."
/>
<TouchableOpacity style={styles.button} >
<Text style={styles.buttonText}>Send</Text>
</TouchableOpacity>
}

return (
<View style={styles.chatContainer}>
<View style={styles.userInfo}>
<Text style={styles.userName}>
{ users.map(user => {
if (user.uid === selectedUser ) return user.dname
})}
</Text>
</View>
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={() => {
this.scrollView.scrollToEnd({animated: true});
}}
style={styles.messagesContainer}
>
{displayMessages()}
</ScrollView>
<View style={styles.inputContainer}>
<TextInput
value={this.state.message}
onChange={this.tempStoreMessage}
style={styles.input}
placeholder="type message..."
/>
<TouchableOpacity disabled={!enabledSend} onPress={this.sendMessage} style={enabledSend ? styles.button : styles.disabledButton} >
<Text style={styles.buttonText}>Send</Text>
</TouchableOpacity>
</View>
</View>
</View>
)
)
}
}

ChatComponent.propTypes = {
Expand Down Expand Up @@ -70,6 +144,9 @@ const mapDispatchToProps = dispatch => {
},
updateGenInfo: genInfo => {
dispatch(dispatchedGenInfo(genInfo));
},
storeSentMessages: message => {
dispatch(dispatchSentMessage(message))
}
}
}
Expand Down
Loading

0 comments on commit 3019102

Please sign in to comment.