Skip to content

Instantly share code, notes, and snippets.

@sanjeevbishnoi
Last active November 21, 2018 19:39
Show Gist options
  • Save sanjeevbishnoi/f0d95b6040d42484f95579bd7f716df1 to your computer and use it in GitHub Desktop.
Save sanjeevbishnoi/f0d95b6040d42484f95579bd7f716df1 to your computer and use it in GitHub Desktop.
Eventmatch Package.json
import React from 'react';
import ReactNative, {
Platform,
StyleSheet,
Text,
View,
TouchableOpacity,
AsyncStorage,
Alert,ActivityIndicator
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons'
import IconF from 'react-native-vector-icons/dist/FontAwesome';
import { GiftedChat, Actions, Bubble, SystemMessage } from 'react-native-gifted-chat';
import { Actions as NavigationActions } from "react-native-router-flux";
import { getSocketObject } from '../../Route.js';
import dictStyle from '../../constants/dictStyle';
import { connect } from 'react-redux';
import TextInputReset from 'react-native-text-input-reset';
import constants from '../../constants/index.js'
import moment from 'moment'
import * as User from '../../actions/user';
import * as Events from '../../actions/event';
import axios from '../../config/axios';
import StyleDict from '../../constants/dictStyle';
import BaseStyle from '../../constants/BaseStyle';
import {AppState} from 'react-native'
import { DeviceEventEmitter } from 'react-native';
// import Icon from "react-native-vector-icons/FontAwesome";
//import CustomActions from './CustomActions';
//import CustomView from './CustomView';
class GroupChat extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
loadEarlier: true,
typingText: null,
isLoadingEarlier: false,
group_id: props.id,
showMenu: false,
historyAppended: false,
remoteHistoryAppended: false,
lastMsgInRedux: '',
clearChat:(props.clearChat && props.clearChat==true)?props.clearChat:false,
isReportButtonClicked:false,
isLeaveButtonClicked:false,
isCloseButtonClicked:false,
event:props.event,
appState: AppState.currentState,
hasLoadedNewGroupData:false
};
this._isMounted = false;
this.onSend = this.onSend.bind(this);
this.renderBubble = this.renderBubble.bind(this);
this.renderSystemMessage = this.renderSystemMessage.bind(this);
this.onLoadEarlier = this.onLoadEarlier.bind(this);
this.renderLoading = this.renderLoading.bind(this);
this.onPressAvatar=this.onPressAvatar.bind(this);
this._isAlright = null;
this.socket = props.socket;
this.senderId = '';
this.senderName = '';
this.senderImage = '';
this.renderSend = this.renderSend.bind(this);
this.optionMenu=this.optionMenu.bind(this);
}
componentWillReceiveProps(newProps) {
if(newProps && newProps.id && newProps.id!==this.state.group_id){
this.setState({
group_id:newProps.id
},()=>{
this.initializeGroupData();
});
}else{
if (newProps.payload) {
let chatHistory = newProps.payload[this.state.group_id];
if(chatHistory){
this.setState({
messages: GiftedChat.append([],chatHistory),
historyAppended: true,
isLoadingEarlier: false,
lastMsgInRedux: (chatHistory && chatHistory.length > 0) ? chatHistory[0]._id : ''
},()=>{
//console.log("componentWillReceiveProps was called",this.state.lastMsgInRedux);
}
);
}
}
}
}
componentWillMount() {
this.initializeGroupData();
DeviceEventEmitter.addListener('ActivityStateChange',this.nativeEventListener);
}
initializeGroupData=()=>{
this.props.getHistory(this.state.group_id);
this.onLoadEarlier();
AsyncStorage.setItem("currentScreen", this.state.group_id);
AsyncStorage.getItem("@userdata").then((data) => {
if (data) {
let userdata = JSON.parse(data);
AsyncStorage.setItem("senderId", userdata.data._id);
this.senderId = userdata.data._id;
this.senderName = userdata.data.name ? userdata.data.name : 'No name found'
let profileImage = ''
if (userdata.data.Docs && userdata.data.Docs.length > 0) {
profileImage = userdata.data.Docs[0].path;
}
this.senderImage = profileImage ? profileImage : 'https://media-exp2.licdn.com/mpr/mpr/shrink_100_100/AAEAAQAAAAAAAATEAAAAJDRlNTU1OWZhLTFmMzAtNDlmOC05MDI1LWVhZDdlNDBiZjI0Yg.jpg'
this.socket.emit("user_msgCount",{userId: this.senderId,channelId:this.state.group_id,isOnline:true});
this.props.updateMessageCount(this.state.group_id,true);
//updateMessageCount:(connectionId)=>dispatch(Events.updateMessageCount(connectionId,false))
}
});
this._isMounted = true;
}
nativeEventListener=(e)=>{
if(e.event==='active'){
console.log(e.event);
this.socket.emit("user_msgCount",{userId: this.senderId,channelId:this.state.group_id,isOnline:true});
return;
}
if(e.event==='inactive' || e.event==='background'){
console.log(e.event);
this.socket.emit("user_msgCount",{userId: this.senderId,channelId:this.state.group_id,isOnline:false});
return;
}
}
componentDidMount() {
// if(BaseStyle.IS_ANDROID)
// AppState.addEventListener('change', nativeEventListener);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
this.socket.emit("user_msgCount",{userId: this.senderId,channelId:this.state.group_id,isOnline:true});
}else{
this.socket.emit("user_msgCount",{userId: this.senderId,channelId:this.state.group_id,isOnline:false});
}
this.setState({appState: nextAppState});
}
componentWillUnmount() {
this._isMounted = false;
DeviceEventEmitter.removeListener("ActivityStateChange",this.nativeEventListener);
// AppState.removeEventListener('change', this.nativeEventListener);
AsyncStorage.setItem("currentScreen", '');
this.socket.emit("user_msgCount",{userId: this.senderId,channelId:this.state.group_id,isOnline:false});
//this.props.getHistory(this.state.group_id);
}
// _renderRightButton = () => {
// return (
// <TouchableOpacity
// style={{ padding: 10 }}
// onPress={() => this._handleIconTouch()}
// >
// <Icon name='more-vert' size={26} color={"white"} />
// </TouchableOpacity>
// );
// };
_handleIconTouch = () => {
this.setState({ showMenu: !this.state.showMenu });
}
onLoadEarlier() {
console.log("on Load earlier was called");
this.setState({
isLoadingEarlier: true
},()=>{
AsyncStorage.getItem('@token').then((value) => axios.post('channels/getMessagesOnChannel',{ channelId: this.state.group_id, msgId: this.state.lastMsgInRedux }, {
headers: {
'token': value,
'Content-Type': 'application/json'
}
})
.then(response => {
// console.log("load earlier called");
this.props.setRemoteHistory(response.data.data,this.state.group_id);
})
.catch(error => {
//alert(JSON.stringify(error))
}));
}
);
//this.props.getRemoteHistory({ channelId: this.state.group_id, msgId: this.state.lastMsgInRedux });
}
onSend(messages = []) {
if (Platform.OS === 'android'){
TextInputReset.resetKeyboardInput(ReactNative.findNodeHandle(this._input.textInput));
}
let dataObject = { message: messages[0].text, channelId: this.state.group_id, from: this.senderId, type: 'channel', senderName: this.senderName, senderImage: this.senderImage,event:this.state.event,screenStatus:this.state.group_id,date:new Date()};
console.log('data_send_on_socket',dataObject);
this.socket.emit("chat_message", dataObject);
}
onReceive(text) {
}
renderBubble(props) {
let isLoggedUser=props.currentMessage.user._id==this.senderId;
if (props.isSameUser(props.currentMessage, props.previousMessage) && props.isSameDay(props.currentMessage, props.previousMessage)) {
return (
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: '#f0f0f0',
}
}}
/>
);
}
return (
<View style={{maxWidth:StyleDict.windowW}}>
<Text style={{padding:3,textAlign:isLoggedUser?'right':'left'}} >{isLoggedUser?'You':props.currentMessage.user.name}</Text>
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: '#f0f0f0',
}
}}
/>
</View>
);
}
renderSystemMessage(props) {
return (
<SystemMessage
{...props}
containerStyle={{
marginBottom: 15,
}}
textStyle={{
fontSize: 14,
}}
/>
);
}
renderLoading(){
return <ActivityIndicator style={{flex:1}} color={StyleDict.colorSet.accentColor} size={'large'} />
}
renderSend(props) {
return (
<TouchableOpacity onPress={() => props.onSend({ text: props.text }, true)}>
<Text>SEND</Text>
</TouchableOpacity>
);
}
privateEvent(){
Alert.alert(
'',
'Do you want to change your event to private?',
[
{text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
{text: 'YES', onPress: () => NavigationActions.eventdropdowns({isCloseButtonClicked:true,group_id:this.state.event._id})}
],
{ cancelable: false }
)
}
optionMenu(data){
NavigationActions.eventdropdowns(data);
}
onPressAvatar(user){
if(user._id===this.senderId){
NavigationActions.myprofile({title:"You",userId:user._id});
}else{
NavigationActions.userprofile({title:user.name,userId:user._id});
}
}
render() {
return (
<View style={{ flex: 1 }}>
<View style={
BaseStyle.IS_ANDROID?{ elevation: 4, backgroundColor: dictStyle.colorSet.appColor, flexDirection: 'row', width: dictStyle.windowW, height: 56, justifyContent: 'space-between', alignItems: 'center' }
:{ elevation: 4, backgroundColor: dictStyle.colorSet.appColor, flexDirection: 'row', width: dictStyle.windowW, height: 74, justifyContent: 'space-between', alignItems: 'center',paddingTop:18 }
}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}><TouchableOpacity onPress={() => NavigationActions.pop()}>
{
BaseStyle.IS_ANDROID?<Icon style={{ marginLeft: 10 }} name={'arrow-back'} color={'white'} size={24} />
:<IconF style={{ marginLeft: 10 }} name={'angle-left'} color={'white'} size={32} />
}
</TouchableOpacity><Text numberOfLines={1} style={{ marginLeft: 25, color: '#fff', fontSize: 20,maxWidth:200}}>{this.props.title}</Text></View>
<TouchableOpacity
style={{ padding: 10, alignItems: 'center'}}
onPress={() => this._handleIconTouch()}
>
<Icon name='more-vert' size={26} color={"white"} />
</TouchableOpacity>
</View>
{/* {this.state.historyAppended && */}
<GiftedChat
//renderSend={this.renderSend}
messages={this.state.messages.reverse()}
onSend={this.onSend}
loadEarlier={this.state.loadEarlier}
onLoadEarlier={this.onLoadEarlier}
isLoadingEarlier={this.state.isLoadingEarlier}
renderAvatarOnTop={true}
renderLoading={this.renderLoading}
onPressAvatar={(user)=>this.onPressAvatar(user)}
user={{
_id: this.senderId,
name: this.senderName,
avatar:this.senderImage
// sent messages should have same user._id
}}
ref={(c) => this._input = c}
// renderActions={this.renderCustomActions}
//renderBubble={this.renderBubble}
//renderSystemMessage={this.renderSystemMessage}
renderBubble={this.renderBubble}
showUserAvatar={true}
//renderCustomView={this.renderCustomView}
//renderFooter={this.renderFooter}
/>
{/* } */}
{ this.state.showMenu && <View style={{ position: 'absolute', top: 56, right: 0, backgroundColor: dictStyle.colorSet.accentColor, paddingLeft: 10, paddingRight: 10 }}>
<TouchableOpacity onPress={() => {
this.setState({ showMenu: false });
NavigationActions.groupmembers({ group_id: this.state.event._id });
}}>
<View style={styles.menutext}>
<Text style={styles.footerText}>
View Members
</Text>
</View>
</TouchableOpacity>
{(this.senderId!==this.state.event.userId) && <TouchableOpacity onPress={() => {NavigationActions.eventdropdowns({isLeaveButtonClicked:true,group_id:this.state.event._id})}}>
<View style={styles.menutext}>
<Text style={styles.footerText}>
Leave Event
</Text>
</View>
</TouchableOpacity>
}
{(this.senderId===this.state.event.userId) && <TouchableOpacity onPress={() => this.privateEvent()}
>
<View style={styles.menutext}>
<Text style={styles.footerText}>
Private Event
</Text>
</View>
</TouchableOpacity>
}
{(this.senderId!==this.state.event.userId) && <TouchableOpacity onPress={() => {NavigationActions.eventdropdowns({isReportButtonClicked:true,group_id:this.state.event._id})}}
>
<View style={styles.menutext}>
<Text style={styles.footerText}>
Report Event
</Text>
</View>
</TouchableOpacity>
}
{(this.senderId===this.state.event.userId) && <TouchableOpacity onPress={() => {NavigationActions.addmembers({group_id:this.state.event._id})}}
>
<View style={styles.menutext}>
<Text style={styles.footerText}>
Add Friends
</Text>
</View>
</TouchableOpacity> }
</View>
}
</View>
);
}
}
const styles = StyleSheet.create({
footerContainer: {
marginTop: 5,
marginLeft: 10,
marginRight: 10,
marginBottom: 10,
},
footerText: {
fontSize: 16,
color: '#fff'
},
menutext: {
padding: 5,
alignItems: 'center',
justifyContent: 'center'
}
});
const mapStateToProps = (state, ownProps) => {
//alert(state.connectionId);
return {
payload: state.userStore,
time: state.userStore.refreshTime,
}
}
const mapToDispatchProps = dispatch => {
return {
getHistory: (group_id) => dispatch({ type: 'CHAT_REFRESH', time: moment().valueOf(),group_id: group_id }),
setRemoteHistory: (data, group_id) => dispatch({ type: 'SET_REMOTE_HISTORY', time: moment().valueOf(), remoteData: data, group_id: group_id}),
//clearChat: (data, group_id) => dispatch({ type: 'CLEAR_CHAT', time: moment().valueOf(), remoteData: data, group_id: group_id}),
updateMessageCount:(connectionId,isZero)=>dispatch(Events.updateMessageCount(connectionId,isZero))
}
}
export default connect(mapStateToProps, mapToDispatchProps)(GroupChat);
{
"name": "eventmatch",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"storybook": "storybook start -p 7007"
},
"dependencies": {
"ajv": "^5.5.1",
"ajv-keywords": "^2.1.1",
"axios": "^0.17.1",
"clamp": "^1.0.1",
"faker": "^4.1.0",
"flickrapi": "^0.6.0",
"fs": "0.0.1-security",
"https": "^1.0.0",
"moment": "^2.19.3",
"native-base": "^2.3.4",
"react": "^16.2.0",
"react-native": "^0.51.0",
"react-native-button": "^2.2.0",
"react-native-camera-roll-picker": "^1.2.3",
"react-native-datepicker": "^1.6.0",
"react-native-device-info": "^0.21.5",
"react-native-drawer": "^2.5.0",
"react-native-fbsdk": "^0.7.0",
"react-native-fcm": "^11.3.1",
"react-native-gifted-chat": "^0.3.0",
"react-native-google-places": "^2.4.2",
"react-native-google-places-autocomplete": "^1.3.6",
"react-native-google-signin": "^0.12.0",
"react-native-image-crop-picker": "^0.19.0",
"react-native-infinite-scroll-view": "^0.4.3",
"react-native-keyboard-aware-scroll-view": "^0.4.4",
"react-native-linear-gradient": "^2.4.0",
"react-native-modal-datetime-picker": "^4.13.0",
"react-native-nav": "^2.0.2",
"react-native-router-flux": "^4.0.0-beta.27",
"react-native-splash-screen": "^3.1.1",
"react-native-text-input-reset": "^1.0.2",
"react-native-vector-icons": "^4.4.2",
"react-redux": "^5.0.6",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0",
"socket.io-client": "^2.0.4",
"url": "^0.11.0"
},
"devDependencies": {
"@storybook/addon-actions": "^3.3.11",
"@storybook/addon-links": "^3.3.11",
"@storybook/addons": "^3.3.11",
"@storybook/react-native": "^3.3.11",
"babel-core": "^6.26.0",
"babel-jest": "21.2.0",
"babel-preset-react-native": "4.0.0",
"jest": "21.2.1",
"prop-types": "^15.6.0",
"react-dom": "16.0.0",
"react-test-renderer": "16.0.0"
},
"jest": {
"preset": "react-native"
}
}
import { combineReducers } from 'redux';
import home from './home';
import user from './user';
import signUp from './signup';
import setting from './setting';
import events from './events';
import groupchat from './groupchat';
import routes from './routes'
export default combineReducers({
routes,
homeStore: home,
userStore: user,
storeSignup: signUp,
settingStore: setting,
events:events,
groupchat
});
import React from 'react'
import { connect } from 'react-redux';
import {
AsyncStorage, ImageBackground,
Text, TouchableOpacity, Image, View, StatusBar, Platform, Alert
} from 'react-native';
import { Router, Scene, Stack, NavigationBar, Title } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/dist/FontAwesome';
import { Actions, ActionConst } from 'react-native-router-flux';
import * as User from './actions/user';
import * as Events from './actions/event'
import LoginBackground from '../assets/images/splash.png'
import Logo from '../assets/images/logo.png'
import Landing from './containers/landing'
import Dashboard from './containers/dashboard'
import Event from './containers/event'
import ShowEvent from './containers/event/show'
import CreateEvent from './containers/event/create'
import Login from './components/login/index'
import Signup from './containers/signup'
import SignupStepOne from './containers/signup/stepOne'
import SignupStepTwo from './containers/signup/stepTwo'
import SignupStepThree from './containers/signup/stepThree'
import SignupStepFour from './containers/signup/stepFour'
import Forgot from './containers/signup/forgot'
import Reset from './containers/signup/reset'
import SideMenu from './SideMenu'
import Splash from './components/splash/Splash';
import LoginCustom from './components/login/logincustom'
import animations from './components/event/swipe';
import profile from './components/profile/profile';
import GroupChat from './components/chat/groupchat';
import friendlist from './components/friends/friendlist';
import groupMembers from './components/friends/groupmembers';
import userprofile from './components/profile/userprofile';
import moment from 'moment'
import constants from './constants/index.js'
import groupmembers from './components/friends/groupmembers';
import PeerToPeerChat from './components/chat/peertopeerchat';
import TermsAndConditions from './components/settings/termsandconditions';
import NotificationList from './components/notification/';
const RouterWithRedux = connect()(Router);
import FCM, { FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType } from "react-native-fcm";
import myevents from './components/event/myevents';
import Pixabay from './components/pixabay';
import eventdropdowns from './components/event/eventdropdowns';
import addmembers from './components/friends/addmembers';
import EditProfileStepOne from './components/profile/editStepOne';
import EditStepThree from './components/profile/editStepThree';
import EditDesc from './components/profile/editDesc';
import ChangePassword from './components/profile/changePassword';
import StyleDict from './constants/dictStyle';
import CustomToast from "./common/CustomToast.js"
//import SplashScreen from 'react-native-splash-screen'
//var data = {channelId:'5a6b4e4eba56d92adf82231c',senderId:'5a26ea98c7dd6f3ef200c68d',type:"channel"};
const mapStateToProps = (state) => {
return {
storeSignup: state.storeSignup,
userData: state.userStore.userdata
}
}
const mapToDispatchProps = (dispatch) => ({
setUser: data => dispatch(User.setUser(data)),
pushChatInRoom: data => dispatch(User.pushChatInRoom(data)),
changeStatus: (data) => dispatch(User.changeStatus(data)),
refreshEvents: () => dispatch(Events.refreshEvents()),
updateMessageCount: (connectionId) => dispatch(Events.updateMessageCount(connectionId, false)),
// clearGroupChat: (group_id) => dispatch({ type: 'CHAT_REFRESH', time: moment().valueOf(),group_id: group_id }),
})
const getDrawerIcon = (tintColor) => {
return (
<Icon name="bars" size={24} color={'white'}
/>
);
};
class Route extends React.Component {
constructor(props) {
super(props)
// this.socket=null;
this.socket = props.socket;
//console.warn(props.socket)
this.state = {
isSplash: true,
isLoggedIn: false,
isUserStatusLoaded: false
}
this.showLocalNoti = this.showLocalNoti.bind(this);
this._isMounted = false;
}
NotifyUser(notidata) {
AsyncStorage.getItem("currentScreen").then((data) => {
// console.log(data, notidata);
if (notidata.channelId === data) {
} else {
this.props.updateMessageCount(notidata.channelId, false);
this.showLocalNoti(notidata);
}
});
}
// componentWillReceiveProps(newProps) {
// if (newProps.userData) {
// Actions.drawer({ type: 'reset' });
// }
// else {
// Actions.login({ type: 'reset' });
// }
// }
async componentDidMount() {
//SplashScreen.hide();
//this.showLocalNotification();
//this.showLocalNotification(notif);
this._isMounted = true;
if (this.socket) {
// await this.socket.on('connect', () => {
// console.log('connected');
//
// });
// this.showLocalNotification({ event: JSON.parse(`{"channelsCreated":["5a9f1d482051c7479983c889","5a9f1e77001a375d54b4266b","5aa0139ae837556318a112a5","5aa0139ae837556318a112a5","5aa01516e837556318a112a9","5aa01516e837556318a112a9","5aa01516e837556318a112a9","5aa016d7e837556318a112ae","5aa016d7e837556318a112ae","5aa016d7e837556318a112ae","5aa01844e837556318a112b3","5aa01844e837556318a112b3","5aa01844e837556318a112b3","5aa02b82e837556318a112b8","5aa02b82e837556318a112b8","5aa02b82e837556318a112b8","5aa02e3fe837556318a112bd","5aa02e3fe837556318a112bd","5aa02e3fe837556318a112bd","5aa031b2e837556318a112c2","5aa031b2e837556318a112c2","5aa03292e837556318a112c6","5aa03292e837556318a112c6","5aa03292e837556318a112c6","5aa03598e837556318a112cb","5aa03598e837556318a112cb","5aa03598e837556318a112cb","5aa03ad9e837556318a112d0","5aa03ad9e837556318a112d0","5aa03ad9e837556318a112d0","5aa03d75e837556318a112d5","5aa03d75e837556318a112d5","5aa03d75e837556318a112d5","5aa04026e837556318a112da","5aa0405ee837556318a112dd","5aa040a7e837556318a112e0","5aa1ae85d93e8322db64b966","5aa2d674b402e36a7203b693","5aa2dcb9b402e36a7203b696","5aa2dd11b402e36a7203b699"],"role":"USER","gender":"male","description":"moga30","socialType":"web","deviceId":"","socketId":"WBJaWZYU-qIE1GeCAAAH","createdAt":"2018-03-05T20:01:58.237Z","socketStatus":1,"password":"1481cd886de9ee9d","__v":0,"member":"false","from":"5a9d89d3d531ff77462bc7e0","email":"moga30@yopmail.com","updatedAt":"2018-03-15T14:30:37.940Z","profile":"5a9da237d531ff77462bc7ec","deviceToken":"efMsCgKNIsU:APA91bE60nznQZTLayCDVsGGMTOz3H-we1Q_VVUtBFBprru0Hi5u7bXcn83PNiJTXhZSNpOGyTMIlLaOArKdv1wKj8yi3cjo96jt7hdeAAaeaVNRAp6D8I5fcJ3RrB5AsHBpaFbiglEf","dob":"2000-03-13T00:00:00.000Z","socialId":"","name":"moga ","geometry":{"coordinates":[30.7333148,76.7794179]},"location":"Panchkula, Haryana, India","_id":"5a9da236d531ff77462bc7eb","Docs":[{"createdAt":"2018-03-05T20:01:59.774Z","path":"http:\\/\\/s3.eu-central-1.amazonaws.com\\/eventmatchh\\/5a9da236d531ff77462bc7eb\\/1520280118000_1520280115943.jpeg","__v":0,"name":"","_id":"5a9da237d531ff77462bc7ec","type":".jpeg","userId":"5a9da236d531ff77462bc7eb","updatedAt":"2018-03-05T20:01:59.774Z"}],"to":"5a9da236d531ff77462bc7eb","status":"active"}`)});
this.props.changeStatus("online");
await this.socket.on('chat_message', (data) => {
// alert(JSON.stringify(data));
console.log("chat message on route is ",JSON.stringify(data));
this.props.pushChatInRoom(data);
this.NotifyUser(data);
});
} else {
//alert("comes here");
}
await FCM.requestPermissions();
FCM.getFCMToken().then(token => {
//console.log("TOKEN (getFCMToken)", token);
//alert(token);
AsyncStorage.setItem("deviceToken", token);
});
FCM.getInitialNotification().then(notif => {
if (notif && notif.opened_from_tray) {
}
this.redirectToPage(notif, true);
});
this.notificationListner = FCM.on(FCMEvent.Notification, notif => {
if (notif && notif.opened_from_tray) {
this.redirectToPage(notif, false);
}
//console.log("Notification", notif);
try {
if (Platform.OS === 'ios') {
switch (notif._notificationType) {
case NotificationType.Remote:
notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
break;
case NotificationType.NotificationResponse:
notif.finish();
break;
case NotificationType.WillPresent:
notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None
break;
}
}
// if (notif.opened_from_tray) {
// // setTimeout(() => {
// // Actions.landing({ type: 'replace', noti: true, targetScreen: notif.type, notidata: notif });
// // return;
// // }, 1);
//
// }
this.showLocalNotification(notif);
//FCM.cancelAllLocalNotifications();
} catch (e) {
console.log(e);
}
});
this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, token => {
//console.log("TOKEN (refreshUnsubscribe)", token);
});
this.socket.on('disconnect', () => {
// if(this.refs && this.refs.defaultToastBottom){
// //this.refs.defaultToastBottom.ShowToastFunction("No internet connection",2000);
// }
});
}
showLocalNotification(notif) {
// let id=Math.random();
// //console.log("comes here",notif);
// if(notif.type==='chat' || notif.type==='groupChat'){
// try{
// id =JSON.parse(notif.event).channelId?JSON.parse(notif.event).channelId:id;
// }catch(e){
// }
// }
// console.log(id);
FCM.presentLocalNotification({
// id:id,
// group:id,
title: notif.title,
body: notif.fcm.body,
priority: "high",
show_in_foreground: true,
local: true,
targetScreen: notif.type
});
}
onBackPress = () => {
return Actions.pop();
}
_handleIconTouch = () => {
Actions.eventlist();
};
_renderRightButton = () => {
//console.log("rendering......_renderRightButton");
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity
style={{ padding: 10 }}
onPress={() => this.props.refreshEvents()}
>
<Icon name="refresh" size={22} color={'white'}
/>
</TouchableOpacity>
<TouchableOpacity
style={{ padding: 10 }}
onPress={() => this._handleIconTouch()}
>
<Icon name="calendar" size={22} color={'white'}
/>
</TouchableOpacity>
</View>
);
};
// _renderEditProfile=()=>{
// console.log("rendering......_renderRightButton");
// return (
// <TouchableOpacity
// style={{ padding: 10 }}
// onPress={()=>this._handleIconTouch()}
// >
// <Icon name="edit" size={22} color={'white'}
// />
// </TouchableOpacity>
// );
// }
_renderRightButtonMyEvents = () => {
//console.log("render tight button called");
return (
<TouchableOpacity
style={{ padding: 10 }}
onPress={() => Actions.showEvent({ title: 'My Events' })}
>
<Icon name='user-circle-o' size={24} color={"white"} />
</TouchableOpacity>
);
};
_renderRightButtonGroupChat = () => {
// console.log("render tight button called");
return (
<TouchableOpacity
style={{ padding: 10 }}
onPress={() => Actions.groupmembers()}
>
<Icon name='group' size={26} color={"white"} />
</TouchableOpacity>
);
};
componentWillUnmount() {
this.notificationListner.remove();
this.refreshTokenListener.remove();
//this.socket.disconnect();
}
showLocalNoti(data) {
try{
var message = '';
if (data.type === 'user') {
message = data.user.name + " sent you a new message";
} else if (data.type === 'channel') {
message = data.user.name + " sent a new message in group";
}
this.refs.defaultToastBottom.ShowToastFunction(message, 2000);
}catch(e){
}
}
redirectToPage(notidata, fromStart) {
//this.props.logout(null);
AsyncStorage.getItem("@token").then(data => {
AsyncStorage.getItem("@")
//console.log("datata****",notidata)
if (data) {
if(notidata){
switch (notidata.type) {
case 'chat':
//Actions.drawer({ type: 'reset' });
if (fromStart) {
Actions.peertopeerchat({ title: JSON.parse(notidata.event).senderName, id: JSON.parse(notidata.event).connectionId, event: JSON.parse(notidata.event), to: JSON.parse(notidata.event)._id, clearChat: true });
} else {
if(Actions.currentScene=='peertopeerchat'){
Actions.refresh({ key: JSON.parse(notidata.event).connectionId, title: JSON.parse(notidata.event).senderName, id: JSON.parse(notidata.event).connectionId, event: JSON.parse(notidata.event), to: JSON.parse(notidata.event)._id, clearChat: true });
}else{
Actions.peertopeerchat({title: JSON.parse(notidata.event).senderName, id: JSON.parse(notidata.event).connectionId, event: JSON.parse(notidata.event), to: JSON.parse(notidata.event)._id, clearChat: true });
}
}
break;
case 'groupChat':
//this.props.clearGroupChat(JSON.parse(notidata.event).channelId);
if (fromStart) {
Actions.groupchat({ title: JSON.parse(notidata.event).title, id: JSON.parse(notidata.event).channelId, event: JSON.parse(notidata.event), clearChat: true });
} else {
//Actions.popTo({key:'drawer'});
// Actions.currentScene=
if(Actions.currentScene=='groupchat'){
Actions.refresh({ key: JSON.parse(notidata.event).connectionId, title: JSON.parse(notidata.event).title, id: JSON.parse(notidata.event).channelId, event: JSON.parse(notidata.event), clearChat: true });
}else{
Actions.groupchat({ title: JSON.parse(notidata.event).title, id: JSON.parse(notidata.event).channelId, event: JSON.parse(notidata.event), clearChat: true });
}
}
break;
case 'send_Friend_request':
//Actions.drawer({ type: 'reset' });
//alert(JSON.stringify(this.state.notidata.event));
//'Notification', { event: '{"channelsCreated":["5a9f1d482051c7479983c889","5a9f1e77001a375d54b4266b","5aa0139ae837556318a112a5","5aa0139ae837556318a112a5","5aa01516e837556318a112a9","5aa01516e837556318a112a9","5aa01516e837556318a112a9","5aa016d7e837556318a112ae","5aa016d7e837556318a112ae","5aa016d7e837556318a112ae","5aa01844e837556318a112b3","5aa01844e837556318a112b3","5aa01844e837556318a112b3","5aa02b82e837556318a112b8","5aa02b82e837556318a112b8","5aa02b82e837556318a112b8","5aa02e3fe837556318a112bd","5aa02e3fe837556318a112bd","5aa02e3fe837556318a112bd","5aa031b2e837556318a112c2","5aa031b2e837556318a112c2","5aa03292e837556318a112c6","5aa03292e837556318a112c6","5aa03292e837556318a112c6","5aa03598e837556318a112cb","5aa03598e837556318a112cb","5aa03598e837556318a112cb","5aa03ad9e837556318a112d0","5aa03ad9e837556318a112d0","5aa03ad9e837556318a112d0","5aa03d75e837556318a112d5","5aa03d75e837556318a112d5","5aa03d75e837556318a112d5","5aa04026e837556318a112da","5aa0405ee837556318a112dd","5aa040a7e837556318a112e0","5aa1ae85d93e8322db64b966","5aa2d674b402e36a7203b693","5aa2dcb9b402e36a7203b696","5aa2dd11b402e36a7203b699"],"role":"USER","gender":"male","description":"moga30","socialType":"web","deviceId":"","socketId":"WBJaWZYU-qIE1GeCAAAH","createdAt":"2018-03-05T20:01:58.237Z","socketStatus":1,"password":"1481cd886de9ee9d","__v":0,"member":"false","from":"5a9d89d3d531ff77462bc7e0","email":"moga30@yopmail.com","updatedAt":"2018-03-15T14:30:37.940Z","profile":"5a9da237d531ff77462bc7ec","deviceToken":"efMsCgKNIsU:APA91bE60nznQZTLayCDVsGGMTOz3H-we1Q_VVUtBFBprru0Hi5u7bXcn83PNiJTXhZSNpOGyTMIlLaOArKdv1wKj8yi3cjo96jt7hdeAAaeaVNRAp6D8I5fcJ3RrB5AsHBpaFbiglEf","dob":"2000-03-13T00:00:00.000Z","socialId":"","name":"moga ","geometry":{"coordinates":[30.7333148,76.7794179]},"location":"Panchkula, Haryana, India","_id":"5a9da236d531ff77462bc7eb","Docs":[{"createdAt":"2018-03-05T20:01:59.774Z","path":"http:\\/\\/s3.eu-central-1.amazonaws.com\\/eventmatchh\\/5a9da236d531ff77462bc7eb\\/1520280118000_1520280115943.jpeg","__v":0,"name":"","_id":"5a9da237d531ff77462bc7ec","type":".jpeg","userId":"5a9da236d531ff77462bc7eb","updatedAt":"2018-03-05T20:01:59.774Z"}],"to":"5a9da236d531ff77462bc7eb","status":"active"}',
if(Actions.currentScene=='userprofile'){
Actions.userprofile({ type: 'refresh',title: JSON.parse(notidata.event).name, userdata: JSON.parse(notidata.event), userId: JSON.parse(notidata.event)._id });
}else{
Actions.userprofile({ title: JSON.parse(notidata.event).name, userdata: JSON.parse(notidata.event), userId: JSON.parse(notidata.event)._id });
}
break;
default:
Actions.drawer({ type: 'reset' });
break;
}
} else {
Actions.drawer({ type: 'reset' });
}
}
else{
Actions.login({ type: 'reset' });
}
});
}
render() {
return (
<View style={{ flex: 1 }}>
<StatusBar
backgroundColor={StyleDict.colorSet.appColor}
barStyle="light-content"
/>
<RouterWithRedux
backAndroidHandler={this.onBackPress}
>
<Stack key="root" hideNavBar={true} >
<Scene key="landing"
component={Splash}
type={ActionConst.RESET}
titleStyle={{ color: 'white', fontWeight: '400' }}
/>
<Scene
key="logincustom"
component={LoginCustom}
title="Login"
titleStyle={{ color: 'white', fontWeight: '400' }}
headerBackTitle="back"
hideNavBar={true}
// initial={!this.state.isLoggedIn && this.state.isUserStatusLoaded }
/>
<Scene
key="login"
component={Login}
title="Login"
headerBackTitle="back"
titleStyle={{ color: 'white', fontWeight: '400' }}
hideNavBar={true}
/>
<Scene initial={true} hideNavBar={true} key="drawer" drawer drawerIcon={getDrawerIcon()} contentComponent={SideMenu} renderRightButton={this._renderRightButton()} type={ActionConst.RESET} >
<Scene key="eventmatch" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={animations} title="Eventmatch" socket={this.socket} />
{/* <Scene key="event" titleStyle={{ color: 'white' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={Event} type={ActionConst.REPLACE} title="EVENTS" />
<Scene key="createEvent" titleStyle={{ color: 'white' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={CreateEvent} type={ActionConst.REPLACE} title="Create Event" /> */}
</Scene>
<Scene
navigationBarStyle={{ backgroundColor: '#062f6f' }}
key="showEvent"
title="My Events"
hideNavBar={false}
navBarButtonColor='#fff'
titleStyle={{ color: 'white', fontWeight: '400' }}
component={myevents}
/>
<Scene key="createEvent" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={CreateEvent} title="Create Event" hideNavBar={false} navBarButtonColor='#fff' socket={this.socket} />
<Scene key="eventlist" hideNavBar={false} titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={Event} hideNavBar={false} title="Events" navBarButtonColor='#fff' />
<Scene key="myprofile" hideNavBar={true} titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={profile} title="My Profile" navBarButtonColor='#fff' />
<Scene key="editProfileStepOne" hideNavBar={true} titleStyle={{ color: 'white', fontWeight: '400' }} navBarButtonColor='#fff' navigationBarStyle={{ backgroundColor: '#062f6f' }} component={EditProfileStepOne} title="Edit Profile" />
<Scene key="editStepThree" hideNavBar={false} titleStyle={{ color: 'white', fontWeight: '400' }} navBarButtonColor='#fff' navigationBarStyle={{ backgroundColor: '#062f6f' }} component={EditStepThree} title="Edit Profile Photo" />
<Scene key="editDesc" hideNavBar={false} titleStyle={{ color: 'white', fontWeight: '400' }} navBarButtonColor='#fff' navigationBarStyle={{ backgroundColor: '#062f6f' }} component={EditDesc} title="Edit Description" />
<Scene key="changePassword" hideNavBar={false} titleStyle={{ color: 'white', fontWeight: '400' }} navBarButtonColor='#fff' navigationBarStyle={{ backgroundColor: '#062f6f' }} component={ChangePassword} title="Change Password" />
<Scene key="signupStepOne" titleStyle={{ color: 'white', fontWeight: '400' }} component={SignupStepOne} title="Step 1" />
<Scene key="signupStepTwo" titleStyle={{ color: 'white', fontWeight: '400' }} component={SignupStepTwo} title="Step 2" />
<Scene key="signupStepThree" titleStyle={{ color: 'white', fontWeight: '400' }} component={SignupStepThree} title="Step 3" />
<Scene key="signupStepFour" titleStyle={{ color: 'white', fontWeight: '400' }} component={SignupStepFour} title="Step 4" />
<Scene key="signup" titleStyle={{ color: 'white', fontWeight: '400' }} component={Signup} title="Signup" />
<Scene key="forgot" titleStyle={{ color: 'white', fontWeight: '400' }} component={Forgot} title="Reset Password" />
<Scene key="resetPassword" titleStyle={{ color: 'white', fontWeight: '400' }} component={Reset} title="Reset Password" />
<Scene key="groupchat" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={GroupChat} title="Group Chat" hideNavBar={true} navBarButtonColor='#fff' socket={this.socket} />
<Scene key="peertopeerchat" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={PeerToPeerChat} title="Peer to Peer Chat" hideNavBar={true} navBarButtonColor='#fff' socket={this.socket} />
<Scene key="friendlist" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={friendlist} title="My Friends" hideNavBar={false} navBarButtonColor='#fff' />
<Scene key="groupmembers" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={groupmembers} title="Members" hideNavBar={false} navBarButtonColor='#fff' />
<Scene key="userprofile" hideNavBar={true} titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={userprofile} title="My Profile" navBarButtonColor='#fff' />
<Scene key="tac" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={TermsAndConditions} title='Terms &amp; Conditions' hideNavBar={false} navBarButtonColor='#fff' />
<Scene key="notification" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={NotificationList} title='Notifications' hideNavBar={false} navBarButtonColor='#fff' />
<Scene key="pixabay" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={Pixabay} title='Flickr' hideNavBar={false} navBarButtonColor='#fff' />
<Scene key="eventdropdowns" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={eventdropdowns} title='Events' hideNavBar={false} navBarButtonColor='#fff' />
<Scene key="addmembers" titleStyle={{ color: 'white', fontWeight: '400' }} navigationBarStyle={{ backgroundColor: '#062f6f' }} component={addmembers} title='Add Friends' hideNavBar={true} navBarButtonColor='#fff' />
</Stack>
</RouterWithRedux>
<CustomToast ref="defaultToastBottom" position="bottom" backgroundColor={StyleDict.colorSet.accentColor} />
</View>
)
}
}
// export const getSocketObject=()=>{
// return Route.socket;
// }
export default connect(mapStateToProps, mapToDispatchProps)(Route)
import SocketIOClient from 'socket.io-client';
import constants from './constants/index.js'
export default class SocketManager {
static myInstance = null;
static getInstance() {
if (SocketManager.myInstance == null) {
SocketManager.myInstance = SocketIOClient(constants.SERVER_URL_SOCKET, {
transports: ['websocket'],
pingTimeout: 30000 // you need to explicitly tell it to use websockets
});
}
return SocketManager.myInstance;
}
}
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from '../reducers';
import {createLogger} from 'redux-logger';
// const store = createStore(
// reducers,
// {},
// compose(
// applyMiddleware(loggerMiddleware,thunk)
// )
// );
// export default store;
// import { createStore, applyMiddleware, compose } from 'redux';
// import reducers from '../reducers/index';
// import thunk from 'redux-thunk';
const loggerMiddleware = createLogger({ predicate: (getState, action) => __DEV__ })
export default function configureStore () {
const enhancer = compose(
applyMiddleware(loggerMiddleware,thunk)
)
const rootReducer = (state, action ) => {
//alert(JSON.stringify(action));
if(action.type==='LOGOUT_USER'){
state={};
}
return reducers(state, action)
}
const store = createStore(rootReducer, enhancer)
if (module.hot) {
module.hot.accept(() => {
const nextRootReducer = require('../reducers/index').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment