-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
App.tsx
380 lines (341 loc) · 11.8 KB
/
App.tsx
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import 'react-native-get-random-values'; // react native moment
import {Component as ReactComponent, useContext, useState} from 'react';
import {StatusBar, StyleSheet, View} from 'react-native';
import {ErrorBoundary} from 'react-error-boundary';
// import ConfirmHcaptcha from '@hcaptcha/react-native-hcaptcha';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {Channel, Server} from 'revolt.js';
import {client, app, randomizeRemark} from './src/Generic';
import {setFunction} from './src/Generic';
import {SideMenuHandler} from './src/SideMenu';
import {Modals} from './src/Modals';
import {ErrorMessage} from '@rvmob/components/ErrorMessage';
import {NetworkIndicator} from './src/components/NetworkIndicator';
import {Notification} from './src/components/Notification';
import {loginWithSavedToken} from './src/lib/auth';
import {
createChannel,
sendNotifeeNotification,
setUpNotifeeListener,
} from '@rvmob/lib/notifications';
import {sleep} from '@rvmob/lib/utils';
import {LoginViews} from '@rvmob/pages/LoginViews';
import {themes, Theme, ThemeContext} from '@rvmob/lib/themes';
import {LoadingScreen} from '@rvmob/components/views/LoadingScreen';
async function openLastChannel() {
try {
const lastServer = await AsyncStorage.getItem('lastServer');
if (lastServer) {
app.openServer(client.servers.get(lastServer));
try {
const channelData = await AsyncStorage.getItem('serverLastChannels');
let serverLastChannels = JSON.parse(channelData || '{}') || {};
let lastChannel = serverLastChannels[lastServer];
if (lastChannel) {
let fetchedLastChannel = client.channels.get(lastChannel);
if (fetchedLastChannel) {
app.openChannel(fetchedLastChannel);
}
}
} catch (channelErr) {
console.log(`[APP] Error getting last channel: ${channelErr}`);
}
}
} catch (serverErr) {
console.log(`[APP] Error getting last server: ${serverErr}`);
}
}
async function checkLastVersion() {
const lastVersion = app.settings.get('app.lastVersion');
console.log(app.version, lastVersion);
if (!lastVersion || lastVersion === '') {
console.log(
`[APP] lastVersion is null (${lastVersion}), setting to app.version (${app.version})`,
);
await app.settings.set('app.lastVersion', app.version);
} else {
app.version === lastVersion
? console.log(
`[APP] lastVersion (${lastVersion}) is equal to app.version (${app.version})`,
)
: console.log(
`[APP] lastVersion (${lastVersion}) is different from app.version (${app.version})`,
);
}
}
function LoggedInViews({state, setChannel}: {state: any; setChannel: any}) {
return (
<>
<SideMenuHandler
coreObject={state}
currentChannel={state.state.currentChannel}
setChannel={setChannel}
/>
<Modals />
<NetworkIndicator client={client} />
<View style={{position: 'absolute', top: 20, left: 0, width: '100%'}}>
<Notification
message={state.state.notificationMessage}
dismiss={() =>
state.setState({
notificationMessage: null,
})
}
openChannel={() =>
state.setState({
notificationMessage: null,
currentChannel: state.state.notificationMessage.channel,
})
}
/>
</View>
</>
);
}
function AppViews({state, setChannel}: {state: any; setChannel: any}) {
const {currentTheme} = useContext(ThemeContext);
const localStyles = generateAppViewStyles(currentTheme);
return (
<>
<StatusBar
animated={true}
backgroundColor={
state.state.status !== 'loggedIn'
? currentTheme.backgroundPrimary
: currentTheme.backgroundSecondary
}
barStyle={`${currentTheme.contentType}-content`}
/>
<View style={localStyles.app}>
{state.state.status === 'loggedIn' ? (
<LoggedInViews state={state} setChannel={setChannel} />
) : state.state.status === 'loggedOut' ? (
<LoginViews
markAsLoggedIn={() => state.setState({status: 'loggedIn'})}
/>
) : (
<LoadingScreen
header={'app.loading.unknown_state'}
body={'app.loading.unknown_state_body'}
bodyParams={{state: state.state.status}}
/>
)}
</View>
</>
);
}
class MainView extends ReactComponent {
constructor(props) {
super(props);
this.state = {
status: 'loggedOut',
currentChannel: null,
notificationMessage: null,
orderedServers: [],
serverNotifications: null,
channelNotifications: null,
};
setFunction('openChannel', async c => {
// if (!this.state.currentChannel || this.state.currentChannel?.server?._id != c.server?._id) c.server?.fetchMembers()
this.setState({currentChannel: c});
app.openLeftMenu(false);
});
setFunction('joinInvite', async (i: string) => {
await client.joinInvite(i);
});
setFunction('logOut', async () => {
console.log(
`[AUTH] Logging out of current session... (user: ${client.user?._id})`,
);
AsyncStorage.multiSet([
['token', ''],
['sessionID', ''],
]);
this.setState({status: 'loggedOut', currentChannel: null});
await client.logout();
app.setLoggedOutScreen('loginPage');
});
}
componentDidUpdate(_, prevState) {
if (prevState.status !== this.state.status) {
randomizeRemark();
}
}
async componentDidMount() {
console.log(`[APP] Mounted component (${new Date().getTime()})`);
let defaultNotif = await createChannel();
console.log(`[NOTIFEE] Created channel: ${defaultNotif}`);
await checkLastVersion();
client.on('connecting', () => {
app.setLoadingStage('connecting');
console.log(`[APP] Connecting to instance... (${new Date().getTime()})`);
});
client.on('connected', () => {
app.setLoadingStage('connected');
console.log(`[APP] Connected to instance (${new Date().getTime()})`);
});
client.on('ready', async () => {
let orderedServers,
server,
channel = null;
try {
const rawSettings = await client.syncFetchSettings([
'ordering',
'notifications',
]);
try {
orderedServers = JSON.parse(rawSettings.ordering[1]).servers;
({server, channel} = JSON.parse(rawSettings.notifications[1]));
} catch (err) {
console.log(`[APP] Error parsing fetched settings: ${err}`);
}
} catch (err) {
console.log(`[APP] Error fetching settings: ${err}`);
}
this.setState({
status: 'loggedIn',
network: 'ready',
orderedServers,
serverNotifications: server,
channelNotifications: channel,
});
console.log(`[APP] Client is ready (${new Date().getTime()})`);
setUpNotifeeListener(client, this.setState);
if (app.settings.get('app.reopenLastChannel')) {
await openLastChannel();
}
});
client.on('dropped', async () => {
this.setState({network: 'dropped'});
});
client.on('message', async msg => {
console.log(`[APP] Handling message ${msg._id}`);
let channelNotif = this.state.channelNotifications
? this.state.channelNotifications[msg.channel?._id]
: undefined;
let serverNotif = this.state.serverNotifications
? this.state.serverNotifications[msg.channel?.server?._id]
: undefined;
const isMuted =
(channelNotif && channelNotif === 'none') ||
channelNotif === 'muted' ||
(serverNotif && serverNotif === 'none') ||
serverNotif === 'muted';
const alwaysNotif =
channelNotif === 'all' || (!isMuted && serverNotif === 'all');
const mentionsUser =
(msg.mention_ids?.includes(client.user?._id!) &&
(app.settings.get('app.notifications.notifyOnSelfPing') ||
msg.author?._id !== client.user?._id)) ||
msg.channel?.channel_type === 'DirectMessage';
const shouldNotif =
(alwaysNotif &&
(app.settings.get('app.notifications.notifyOnSelfPing') ||
msg.author?._id !== client.user?._id)) ||
(!isMuted && mentionsUser);
console.log(
`[NOTIFICATIONS] Should notify for ${msg._id}: ${shouldNotif} (channel/server muted? ${isMuted}, notifications for all messages enabled? ${alwaysNotif}, message mentions the user? ${mentionsUser})`,
);
if (app.settings.get('app.notifications.enabled') && shouldNotif) {
console.log(
`[NOTIFICATIONS] Pushing notification for message ${msg._id}`,
);
if (this.state.currentChannel !== msg.channel) {
this.setState({notificationMessage: msg});
await sleep(5000);
this.setState({notificationMessage: null});
}
await sendNotifeeNotification(msg, client, defaultNotif);
}
});
client.on('packet', async p => {
if (p.type === 'UserSettingsUpdate') {
console.log('[WEBSOCKET] Synced settings updated');
try {
if ('ordering' in p.update) {
const orderedServers = JSON.parse(p.update.ordering[1]).servers;
this.setState({orderedServers});
}
if ('notifications' in p.update) {
const {server, channel} = JSON.parse(p.update.notifications[1]);
this.setState({
serverNotifications: server,
channelNotifications: channel,
});
}
} catch (err) {
console.log(`[APP] Error fetching settings: ${err}`);
}
}
});
client.on('server/delete', async s => {
const currentServer = app.getCurrentServer();
if (currentServer === s) {
app.openServer(undefined);
app.openChannel(null);
}
});
await loginWithSavedToken(this.state.status);
}
async setChannel(channel: string | Channel | null, server?: Server) {
this.setState({
currentChannel: channel,
messages: [],
});
app.openLeftMenu(false);
if (channel) {
await AsyncStorage.getItem('serverLastChannels', async (err, data) => {
if (!err) {
let parsedData = JSON.parse(data || '{}') || {};
parsedData[server?._id || 'DirectMessage'] =
typeof channel === 'string' ? channel : channel._id;
console.log(parsedData);
await AsyncStorage.setItem(
'serverLastChannels',
JSON.stringify(parsedData),
);
} else {
console.log(`[APP] Error getting last channel: ${err}`);
}
});
}
}
render() {
return <AppViews state={this} setChannel={this.setChannel.bind(this)} />;
}
}
export const App = () => {
const [theme, setTheme] = useState<Theme>(themes.Dark);
setFunction('setTheme', (themeName: string) => {
const newTheme = themes[themeName] ?? themes.Dark;
setTheme(newTheme);
});
const localStyles = generateLocalStyles(theme);
return (
<GestureHandlerRootView style={localStyles.outer}>
<ThemeContext.Provider
value={{currentTheme: theme, setCurrentTheme: setTheme}}>
<ErrorBoundary fallbackRender={ErrorMessage}>
<MainView />
</ErrorBoundary>
</ThemeContext.Provider>
</GestureHandlerRootView>
);
};
const generateLocalStyles = (currentTheme: Theme) => {
return StyleSheet.create({
outer: {
flex: 1,
backgroundColor: currentTheme.backgroundSecondary,
},
});
};
const generateAppViewStyles = (currentTheme: Theme) => {
return StyleSheet.create({
app: {
flex: 1,
backgroundColor: currentTheme.backgroundPrimary,
},
});
};