Skip to content

Commit

Permalink
improved chat server connection
Browse files Browse the repository at this point in the history
  • Loading branch information
muganwas committed Feb 28, 2020
1 parent 01d8802 commit 6a5c58c
Show file tree
Hide file tree
Showing 10 changed files with 222 additions and 46 deletions.
12 changes: 12 additions & 0 deletions src/app/components/Header/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
alertSocketError,
socketConnected,
socket,
confirmToken
} from 'reduxFiles/dispatchers/authDispatchers';
// import { setChatId } from '../../misc/functions';

Expand Down Expand Up @@ -82,6 +83,17 @@ class Header extends Component {
});
dispatchSocketConnected();
}
else {
const storedGen = JSON.parse(localStorage.getItem('genInfo'));
const { uid, chatkitUser: { token } } = storedGen;
if ( token && uid ) {
socket.emit('authentication', {
token,
uid
});
dispatchSocketConnected();
}
}
});

socket.on('unauthorized', reason => {
Expand Down
77 changes: 77 additions & 0 deletions src/app/components/Messaging/ChatComponent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Text, View, TextInput, TouchableOpacity } 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>
</View>
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
placeholder="type message..."
/>
<TouchableOpacity style={styles.button} >
<Text style={styles.buttonText}>Send</Text>
</TouchableOpacity>
</View>
</View>
)
}

ChatComponent.propTypes = {
genInfo: PropTypes.object.isRequired,
chatInfo: PropTypes.object.isRequired,
friendsInfo: PropTypes.object.isRequired
}

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

const mapDispatchToProps = dispatch => {
return {
getUsers: () => {
dispatch(fetchUsers());
},
getFriends: info => {
dispatch(fetchFriends(info));
},
logingStatusConfirmation: (confirmLoggedIn, loginInfo) => {
dispatch(checkLoginStatus(confirmLoggedIn, loginInfo));
},
openSocket: props => {
dispatch(connectToChatServer(props));
},
confirmLoggedIn: () => {
dispatch(loginConfirmed());
},
signOut: genInfo => {
dispatch(logout(genInfo));
},
updateGenInfo: genInfo => {
dispatch(dispatchedGenInfo(genInfo));
}
}
}

export default connect(mapStateToProps, mapDispatchToProps)(ChatComponent);
43 changes: 28 additions & 15 deletions src/app/components/Messaging/Messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ import {
fetchUsers,
fetchFriends
} from 'reduxFiles/dispatchers/userDispatchers';
import { setUserToChat } from 'reduxFiles/dispatchers/chatDispatchers';
import {
Header,
Footer
} from 'components';
import './localStyles/main.css';
import ChatComponent from './ChatComponent';

const override = css`
display: block;
Expand All @@ -33,20 +35,28 @@ class Messaging extends Component {
}
componentDidMount(){
const {
confirmLoggedIn,
genInfo,
confirmLoggedIn,
loginInfo,
logingStatusConfirmation,
openSocket
openSocket,
genInfo
} = this.props;
logingStatusConfirmation(confirmLoggedIn, loginInfo, genInfo);
const { socketOpen, unAuthorizedConnection } = loginInfo;
if (!socketOpen && !unAuthorizedConnection) openSocket(this.props);
}

displayChatComponent = e => {
e.stopPropagation();
const { selectUserToChat } = this.props;
const { id } = e.target;
selectUserToChat(id);
this.setState({messaging:true});
}

displayFriends = key => {
let { friendsInfo: { users, friendsFull }, chatInfo: { onlineUsers } } = this.props;
let online = onlineUsers[key] || false;
let online = onlineUsers && onlineUsers[key] ? true : false;
let badgeClass = online ? 'fas fa-circle online' : 'fas fa-circle offline';
if ( users.length > 0 ) {
return <div key={key}> {
Expand All @@ -55,13 +65,13 @@ class Messaging extends Component {
let { uid, avatar, dname, email } = obj;
// console.log(dname + ' ' + email)
return (
<div key={key} className="friend">
<div className="left">
<div className="roundPic membersAv-small">
<img alt={ uid } className="members" src = { avatar } />
<div key={key} id={key} onClick={this.displayChatComponent} className="friend">
<div id={key} className="left">
<div id={key} className="roundPic membersAv-small">
<img id={key} alt={ uid } className="members" src = { avatar } />
</div>
<i className={badgeClass}></i>
<div className="name">{ dname ? dname : email }</div>
<div id={key} className="name">{ dname ? dname : email }</div>
<div className="clear"></div>
</div>
</div>
Expand All @@ -86,7 +96,7 @@ class Messaging extends Component {
<h3><FormattedMessage id='friends.listTitle' /></h3>
{ fetchedFriends ?
friends && friends.length > 0 ?
friends.map(val => this.displayFriends(val)) :
friends.map(this.displayFriends) :
<div className='messages'>
<FormattedMessage id='message.noFriendsYet' />
</div> :
Expand All @@ -103,7 +113,7 @@ class Messaging extends Component {
<div id='conversation-container'>
{ !messaging ?
<span id='messaging-call-to-action'><FormattedMessage id={socketOpen ? 'friends.startConvo' : 'chat.noConnection'} /></span> :
<div></div> }
<ChatComponent /> }
</div>
</div>
</div>
Expand Down Expand Up @@ -136,21 +146,24 @@ const mapStateToProps = state => {

const mapDispatchToProps = dispatch => {
return {
getUsers: ()=>{
getUsers: () => {
dispatch(fetchUsers());
},
getFriends: info=>{
getFriends: info => {
dispatch(fetchFriends(info));
},
logingStatusConfirmation: (confirmLoggedIn, loginInfo, genInfo) => {
dispatch(checkLoginStatus(confirmLoggedIn, loginInfo, genInfo));
logingStatusConfirmation: (confirmLoggedIn, loginInfo, info) => {
dispatch(checkLoginStatus(confirmLoggedIn, loginInfo, info));
},
openSocket: props => {
dispatch(connectToChatServer(props));
},
confirmLoggedIn: () => {
dispatch(loginConfirmed());
},
selectUserToChat: userId => {
dispatch(setUserToChat(userId))
},
signOut: genInfo => {
dispatch(logout(genInfo));
},
Expand Down
47 changes: 47 additions & 0 deletions src/app/components/Messaging/localStyles/mainStyles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { StyleSheet } from 'react-native';

const styles = StyleSheet.create({
chatContainer: {
height: '100%',
display: 'flex',
flexDirection: 'column'
},
input: {
display: 'block',
flex: 8,
padding: 3,
borderWidth: 1.5,
borderColor: '#D4D4D4',
borderRadius: 3,
height: 50,
},
userInfo: {
flex: 1
},
userName: {
textTransform: 'capitalize'
},
messages: {
flex: 2,
minHeight: 50
},
inputContainer: {
display: 'flex',
flex: 1,
flexDirection: 'row'
},
button: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 3,
marginLeft: 10,
backgroundColor: '#16B5F2'
},
buttonText: {
alignText: 'center',
color: '#fff'
}
});

export default styles;
47 changes: 31 additions & 16 deletions src/app/redux/dispatchers/authDispatchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,12 +324,13 @@ export const eAuthenticate = (email, password)=>{
let len = states.length;
dispatch(dispatchedGenInfo(userInfo));
dispatch(fetchToken(currUser, userInfo));
for(var count=0;count<len; count++){
for (var count=0;count<len; count++) {
localStorage.setItem(statesS[count], states[count]);
}
dispatch(loginFulfilled(userInfo));
});
}else{
}
else {
dispatch(loginFailed("error.userEmailNotVerified"));
user.sendEmailVerification().then(()=>{
console.log("verfication email sent");
Expand All @@ -354,7 +355,7 @@ export const eSignup = (email, password)=>{
app.auth().createUserWithEmailAndPassword(email, password).then( response=>{
const { additionalUserInfo: { isNewUser }, user } = response;
const { emailVerified } = user;
if(isNewUser){
if (isNewUser) {
dispatch(signupFullfilled(response));
dispatch(signupMessageAlert("message.successfulSignup"));
!emailVerified? user.sendEmailVerification().then( () => {
Expand All @@ -364,7 +365,7 @@ export const eSignup = (email, password)=>{
}
console.log(emailVerified);
//after signup
}).catch((error)=>{
}).catch(error => {
//console.log(error);
let errorMessage;
let errorCode = error.code;
Expand Down Expand Up @@ -452,10 +453,9 @@ export const handleSignup = (email, password)=>{
export const confirmToken = tokeId => {
return dispatch => {
const url = confirmTokenURL + tokeId;
axios.post(url).then(result => {
if (tokeId) axios.post(url).then(result => {
let { data } = result;
let { error } = data;
console.log(result)
if ( error && error.code === "auth/argument-error") {
dispatch(loginErrorAlert("error.sessionExpired"));
dispatch(logout());
Expand Down Expand Up @@ -484,16 +484,28 @@ export const fetchToken = (currUser, userInfo)=>{
}
}

export const checkLoginStatus = (confirmLoggedIn, loginInfo)=>{
export const checkLoginStatus = (confirmLoggedIn, loginInfo, info)=>{
return dispatch => {
let { loggedIn } = loginInfo;
if(!loggedIn){
fetchGenInfoFromlocalStorage(confirmLoggedIn, loginInfo).then(res=>{
if(res === "not dispatched"){
dispatch(logout());
}
});
}
const { loggedIn } = loginInfo;
const genInfo = JSON.parse(localStorage.getItem('genInfo'));
if (!loggedIn) {
if (!info) {
alert('no info')
fetchGenInfoFromlocalStorage(confirmLoggedIn, loginInfo).then(res=>{
if (res === "not dispatched") {
dispatch(logout());
}
else {
const { chatkitUser: { token } } = genInfo;
dispatch(confirmToken(token));
}
});
}
else {
const { info: { chatkitUser: { token } } } = info;
dispatch(confirmToken(token));
}
}
}
}

Expand All @@ -515,7 +527,7 @@ export const connectToChatServer = props => {
//console.log(token)
// console.log(socketOpen)
if (token && !socketOpen) {
console.log('...opening socket')
console.log('opening socket...')
socket.open();
socket.emit("user-joined", dname);
dispatch(socketConnected());
Expand All @@ -534,6 +546,9 @@ export const alertSocketError = error => {
return dispatch => {
//socket.disconnect();
if (error.message && error.message === 'UNAUTHORIZED') dispatch(unAuthorizedAuthentication());
if (error.code === 'auth/id-token-expired') {
dispatch(logout());
}
dispatch(socketError(error));
}
}
12 changes: 7 additions & 5 deletions src/app/redux/dispatchers/chatDispatchers.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import {
FETCH_ONLINE_USERS_PENDING,
FETCH_ONLINE_USERS_FULFILLED,
FETCH_ONLINE_USERS_ERROR,
FETCH_MESSAGES_PENDING,
FETCH_MESSAGES_FULFILLED,
FETCH_MESSAGES_ERROR
SET_USER_TO_CHAT
} from '../types';

export const fetchedUsersOnline = users => {
return {
type: FETCH_ONLINE_USERS_FULFILLED,
payload: users
}
}
export const setUserToChat = userId => {
return {
type: SET_USER_TO_CHAT,
payload: userId
}
}
Loading

0 comments on commit 6a5c58c

Please sign in to comment.