-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
246 lines (227 loc) · 6.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// @flow
import React, { Component } from 'react';
import { View, Platform } from 'react-native';
import { connect } from 'react-redux';
import config from 'react-native-config';
import SocketIOClient from 'socket.io-client';
import {
GiftedChat,
Composer,
InputToolbar,
Bubble,
} from 'react-native-gifted-chat';
import styles from './styles';
import { showSpinner, hideSpinner } from '../../actions/chat';
import BackgroundImage from '../../components/common/BackgroundImage';
import FakeNavigationBar from '../../components/common/FakeNavigationBar';
import Loading from '../../components/common/Loading';
import { resolveNation } from '../../utils/nations';
import createGiftedChatMessageObject from '../../utils/chat';
import type { NationIdType, NationType } from '../../types/Nation';
import type { Navigator } from '../../types/ReactNativeNavigation';
import elizabot from '../../../vendor/elizabot';
import { getCurrentAccount } from '../../reducers/accounts';
type Props = {
/**
* @desc React Native Navigation navigator object
*/
navigator: Navigator,
/**
* @desc A boolean prop to indicate whether the channel is a bot or not
*/
isBot: boolean,
/**
* @desc List of nations
*/
nations: Array<NationType>,
/**
* @desc Id of the selected nation
*/
nationId: NationIdType,
/**
* @desc Current user object
*/
user: any,
/**
* @desc Flag that indicates the loading status
*/
isFetching: boolean,
/**
* @desc Function to show spinner
*/
showSpinner: () => void,
/**
* @desc Function to hide spinner
*/
hideSpinner: () => void
};
type State = {
/**
* @desc List of messages
*/
messages: Array<any>,
/**
* @desc Flag that indicates whether the socket connection is established
*/
joined: boolean
};
class ChatScreen extends Component<Props, State> {
constructor(props: Props) {
super(props);
if (props.isBot !== true) {
const selectedNation = resolveNation(props.nations || [], props.nationId);
if (selectedNation === null) {
props.navigator.pop();
return;
}
this.nationId = selectedNation.idInSmartContract;
// Creating the socket-client instance will automatically connect to the server.
this.connection = SocketIOClient(config.CHAT_URL, {
transports: ['websocket'],
upgrade: false,
query: `token=${config.AUTH_TOKEN}`,
});
this.connection.on('connect', () => {
this.connection.emit('room:join', {
nation_id: this.nationId,
});
});
this.state = {
messages: [],
joined: false,
};
} else {
// add initial bot message
this.state = {
messages: [
{
_id: 1,
text: elizabot.start(),
createdAt: new Date(),
user: {
_id: 2,
name: 'Dr. FreudBot',
},
// Any additional custom parameters are passed through
},
],
joined: false,
};
}
}
componentDidMount() {
if (this.props.isBot !== true && this.connection) {
this.props.showSpinner();
// load initial messages
const URL = `${config.CHAT_URL}/messages/${this.nationId}?auth_token=${config.AUTH_TOKEN}`;
fetch(URL)
.then(response => response.json())
.then(
(json) => {
const messages = createGiftedChatMessageObject(json.reverse());
this.props.hideSpinner();
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}));
},
() => {
this.props.hideSpinner();
},
);
// add socket listener
this.connection.on('room:joined', (data) => {
if (data.nation_id >= 0) {
this.setState({ joined: true });
this.connection.on('msg', (messageData) => {
const messages = createGiftedChatMessageObject([messageData]);
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}));
});
}
});
}
}
componentWillUnmount() {
if (this.connection !== null && this.connection !== undefined) {
this.connection.disconnect();
}
}
onSend(messages: Array<any> = []) {
if (this.props.isBot === true) {
const m = [
{
_id: this.state.messages.length + 1,
text: elizabot.reply(messages[0].text),
createdAt: new Date(),
user: {
_id: 2,
name: 'Dr. FreudBot',
},
},
];
// Add user's message
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}));
// Add Eliza's response
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, m),
}));
} else if (this.state.joined === true) {
const newMessage = {
nation_id: this.nationId,
msg: messages[0].text,
from: this.props.user ? this.props.user.name : 'anonymous',
userId: this.props.user ? this.props.user.id : 'anonymous',
};
this.connection.emit('room:msg', newMessage);
}
}
nationId: number;
connection: any;
render() {
const sendingUser = {
_id: this.props.user ? this.props.user.id : 'anonymous',
name: this.props.user ? this.props.user.name : 'anonymous',
};
return (
<View style={styles.container}>
<BackgroundImage />
<FakeNavigationBar navBarHidden={false} />
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={sendingUser}
bottomOffset={Platform.OS === 'ios' ? 48.5 : 0}
renderComposer={props => (
<Composer {...props} textInputStyle={styles.composer} />
)}
renderInputToolbar={props => (
<InputToolbar {...props} containerStyle={styles.inputToolbar} />
)}
renderBubble={props => (
<Bubble
{...props}
customTextStyle={styles.customTextStyle}
wrapperStyle={{ left: styles.leftBubbleWrapper, right: styles.rightBubbleWrapper }}
textStyle={{ left: styles.leftTextStyle, right: styles.rightTextStyle }}
/>
)}
/>
{this.props.isFetching && <Loading />}
</View>
);
}
}
const mapStateToProps = state => ({
nations: state.nations.nations,
nationId: state.nations.openedNationId,
user: getCurrentAccount(state.accounts),
isFetching: state.chat.isFetching,
});
const mapDispatchToProps = dispatch => ({
showSpinner: () => dispatch(showSpinner()),
hideSpinner: () => dispatch(hideSpinner()),
});
export default connect(mapStateToProps, mapDispatchToProps)(ChatScreen);