forked from upryzing/clerotri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
702 lines (683 loc) · 24.9 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
import 'react-native-get-random-values'; // react native moment
import React from 'react';
import {
View,
TouchableOpacity,
TextInput,
StatusBar,
Dimensions,
StatusBarStyle,
} from 'react-native';
import {ErrorBoundary} from 'react-error-boundary';
import {withTranslation} from 'react-i18next';
// import ConfirmHcaptcha from '@hcaptcha/react-native-hcaptcha';
import notifee, {EventType} from '@notifee/react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Clipboard from '@react-native-clipboard/clipboard';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import SideMenuBase from '@rexovolt/react-native-side-menu';
import {Channel, Server} from 'revolt.js';
import {currentTheme, styles} from './src/Theme';
import {
client,
app,
selectedRemark,
randomizeRemark,
openUrl,
} from './src/Generic';
import {setFunction} from './src/Generic';
import {SideMenu} from './src/SideMenu';
import {Modals} from './src/Modals';
import {NetworkIndicator} from './src/components/NetworkIndicator';
import {BackButton, Button, Link, Text} from './src/components/common/atoms';
import {LoginSettingsPage} from './src/pages/auth/LoginSettingsPage';
import {ChannelView} from './src/components/views/ChannelView';
import {Notification} from './src/components/Notification';
import {
loginRegular,
loginWithSavedToken,
loginWithToken,
} from './src/lib/auth';
import {OFFICIAL_INSTANCE_SIGNUP_URL} from '@rvmob/lib/consts';
import {sleep} from './src/lib/utils';
async function createChannel() {
const channel = (await notifee.getChannel('rvmob'))
? 'rvmob'
: await notifee.createChannel({
id: 'rvmob',
name: 'RVMob',
});
return channel;
}
class MainView extends React.Component {
constructor(props) {
super(props);
this.state = {
status: 'tryingLogin',
loginType: '',
askForTFACode: false,
currentChannel: null,
currentText: '',
tokenInput: '',
emailInput: '',
passwordInput: '',
tfaInput: '',
tfaTicket: '',
leftMenuOpen: false,
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, leftMenuOpen: false});
});
setFunction('joinInvite', async (i: string) => {
await client.joinInvite(i);
});
setFunction('openLeftMenu', async (o: boolean) => {
console.log(`[APP] Setting left menu open state to ${o}`);
this.setState({leftMenuOpen: o});
});
setFunction('logOut', async () => {
console.log(
`[AUTH] Logging out of current session... (user: ${client.user?._id})`,
);
AsyncStorage.multiSet([
['token', ''],
['sessionID', ''],
]);
client.logout();
this.setState({status: 'awaitingLogin'});
});
}
componentDidUpdate(_, prevState) {
if (
prevState.status !== this.state.status &&
this.state.status === 'tryingLogin'
) {
randomizeRemark();
}
}
async componentDidMount() {
console.log(`[APP] Mounted component (${new Date().getTime()})`);
let defaultnotif = await createChannel();
console.log(`[NOTIFEE] Created channel: ${defaultnotif}`);
console.log(app.version, app.settings.get('app.lastVersion'));
const lastVersion = app.settings.get('app.lastVersion');
if (!lastVersion || lastVersion === '') {
console.log(
`[APP] lastVersion is null (${lastVersion}), setting to app.version (${app.version})`,
);
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})`,
);
}
client.on('connecting', () => {
console.log(`[APP] Connecting to instance... (${new Date().getTime()})`);
});
client.on('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',
]);
orderedServers = JSON.parse(rawSettings.ordering[1]).servers;
({server, channel} = JSON.parse(rawSettings.notifications[1]));
} 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()})`);
notifee.onBackgroundEvent(async ({type, detail}) => {
const {notification /*, pressAction */} = detail;
if (type === EventType.PRESS) {
console.log(
`[NOTIFEE] User pressed on ${notification?.data?.channel}/${notification?.data?.messageID}`,
);
const notifChannel = client.channels.get(
notification?.data?.channel as string,
);
this.setState({
currentChannel: notifChannel ?? null,
});
await notifee.cancelNotification(notification!.id!);
}
});
AsyncStorage.getItem('lastServer', async (err, lastServer) => {
if (!err) {
if (lastServer) {
app.openServer(client.servers.get(lastServer));
await AsyncStorage.getItem('serverLastChannels', (cerr, data) => {
if (!cerr) {
let serverLastChannels = JSON.parse(data || '{}') || {};
let lastChannel = serverLastChannels[lastServer];
if (lastChannel) {
let fetchedLastChannel = client.channels.get(lastChannel);
if (fetchedLastChannel) {
app.openChannel(fetchedLastChannel);
}
}
} else {
console.log(`[APP] Error getting last channel: ${err}`);
}
});
}
} else {
console.log(`[APP] Error getting last server: ${err}`);
}
});
});
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[msg.channel?._id];
let serverNotif =
this.state.serverNotifications[msg.channel?.server?._id];
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});
}
let notifs = (await notifee.getDisplayedNotifications()).filter(
n => n.id === msg.channel?._id,
);
const title = `${
msg.channel?.server?.name
? `#${msg.channel.name} (${msg.channel.server.name})`
: msg.channel?.channel_type === 'Group'
? `${msg.channel.name}`
: `@${msg.channel?.recipient?.username}`
}`;
try {
notifee.displayNotification({
title: title,
data: {
channel: msg.channel?._id ?? 'UNKNOWN',
messageID: msg._id,
},
body:
`<b>${msg.author?.username}</b>: ` +
msg.content
?.replaceAll(
'<@' + client.user?._id + '>',
'@' + client.user?.username,
)
.replaceAll('\\', '\\\\')
.replaceAll('<', '\\<')
.replaceAll('>', '\\>') +
'<br>' +
(msg.embeds
? msg.embeds.map(_e => '[Embed]').join('<br>') + '<br>'
: '') +
(msg.attachments
? msg.attachments.map(a => a.metadata.type).join('<br>') +
'<br>'
: '') +
(notifs.length > 0 && notifs[0]?.notification.body
? notifs[0].notification.body.split('<br>')?.length > 1
? ' <i><br>(and ' +
(Number.parseInt(
notifs[0]?.notification.body
?.split('<br>')[1]
.split(' ')[1] ?? '',
10,
) +
1) +
' more messages)</i>'
: ' <i><br>(and 1 more message)</i>'
: ''),
android: {
color: '#1AD4B2',
smallIcon: 'ic_launcher_monochrome',
largeIcon:
msg.channel?.server?.generateIconURL() ||
msg.author?.generateAvatarURL(),
pressAction: {
id: 'default',
launchActivity: 'site.endl.taiku.rvmob.MainActivity',
},
channelId: defaultnotif,
},
id: msg.channel?._id,
});
} catch (notifErr) {
console.log(`[NOTIFEE] Error sending notification: ${notifErr}`);
}
}
});
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);
}
async setChannel(channel: string | Channel, server?: Server) {
this.setState({
currentChannel: channel,
leftMenuOpen: false,
messages: [],
});
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() {
const {t} = this.props;
return (
<View style={styles.app}>
{this.state.status === 'loggedIn' ? (
<>
{Dimensions.get('window').width >
Dimensions.get('window').height ? (
<View style={{flex: 1, flexDirection: 'row'}}>
<View
style={{
width: '20%',
flexDirection: 'column',
}}>
<SideMenu
onChannelClick={this.setChannel.bind(this)}
currentChannel={this.state.currentChannel}
orderedServers={this.state.orderedServers}
/>
</View>
<ChannelView state={this} channel={this.state.currentChannel} />
</View>
) : (
<SideMenuBase
openMenuOffset={Dimensions.get('window').width - 50}
overlayColor={'#00000040'}
edgeHitWidth={Dimensions.get('window').width}
isOpen={this.state.leftMenuOpen}
onChange={open => this.setState({leftMenuOpen: open})}
menu={
<SideMenu
onChannelClick={this.setChannel.bind(this)}
currentChannel={this.state.currentChannel}
orderedServers={this.state.orderedServers}
/>
}
style={styles.app}
bounceBackOnOverdraw={false}>
<ChannelView state={this} channel={this.state.currentChannel} />
</SideMenuBase>
)}
<Modals />
<NetworkIndicator client={client} />
<View
style={{position: 'absolute', top: 20, left: 0, width: '100%'}}>
<Notification
message={this.state.notificationMessage}
dismiss={() =>
this.setState({
notificationMessage: null,
})
}
openChannel={() =>
this.setState({
notificationMessage: null,
currentChannel: this.state.notificationMessage.channel,
})
}
/>
</View>
</>
) : this.state.status === 'awaitingLogin' ||
this.state.status === 'tryingLogin' ? (
<>
{this.state.status === 'awaitingLogin' ? (
<>
<View
style={{
marginTop: 12,
marginStart: 8,
marginEnd: 4,
justifyContent: 'space-between',
alignItems: 'center',
flexDirection: 'row',
}}>
{this.state.loginType !== '' ? (
<BackButton
callback={() => {
this.setState({loginType: ''});
}}
/>
) : (
<View />
)}
<TouchableOpacity
onPress={() => this.setState({status: 'loginSettings'})}>
<MaterialIcon
name="more-vert"
size={30}
color={currentTheme.foregroundPrimary}
/>
</TouchableOpacity>
</View>
<View
style={{
alignItems: 'center',
justifyContent: 'center',
flex: 1,
}}>
<Text
style={{
fontFamily: 'Inter',
fontWeight: 'bold',
fontSize: 48,
}}>
RVMob
</Text>
{this.state.loginType === 'email' ? (
<>
<TextInput
placeholderTextColor={currentTheme.foregroundSecondary}
style={styles.loginInput}
placeholder={t('app.login.forms.email_placeholder')}
keyboardType={'email-address'}
autoComplete={'email'}
onChangeText={(text: string) => {
this.setState({emailInput: text});
}}
value={this.state.emailInput}
/>
<TextInput
placeholderTextColor={currentTheme.foregroundSecondary}
style={styles.loginInput}
secureTextEntry={true}
autoComplete={'password'}
placeholder={t('app.login.forms.password_placeholder')}
onChangeText={text => {
this.setState({passwordInput: text});
}}
value={this.state.passwordInput}
/>
{this.state.askForTFACode === true ? (
<>
<TextInput
placeholderTextColor={
currentTheme.foregroundSecondary
}
style={styles.loginInput}
placeholder={t('app.login.forms.mfa_placeholder')}
onChangeText={text => {
this.setState({tfaInput: text});
}}
value={this.state.tfaInput}
/>
</>
) : null}
<Button onPress={async () => await loginRegular(this)}>
<Text font={'Inter'}>Log in</Text>
</Button>
{this.state.logInError ? (
<Text>
{this.state.logInError.message ||
this.state.logInError.toString()}
</Text>
) : null}
</>
) : this.state.loginType === 'token' ? (
<>
<TextInput
placeholderTextColor={currentTheme.foregroundSecondary}
style={styles.loginInput}
placeholder={t(
'app.login.forms.session_token_placeholder',
)}
onChangeText={text => {
this.setState({tokenInput: text});
}}
value={this.state.tokenInput}
/>
<Link
link={
'https://infi.sh/posts/revolt-tokens?utm_source=rvmob'
}
label={t('app.login.token_info_label')}
style={{fontFamily: 'Inter', fontWeight: 'bold'}}
/>
<Button onPress={async () => await loginWithToken(this)}>
<Text font={'Inter'}>Log in</Text>
</Button>
{this.state.logInError ? (
<Text>
{this.state.logInError.message ??
this.state.logInError}
</Text>
) : null}
</>
) : (
<>
<Text
font={'Inter'}
style={{
marginVertical: 8,
fontSize: 18,
fontWeight: 'bold',
}}>
{t('app.login.subheader')}
</Text>
<Button
onPress={() => {
this.setState({loginType: 'email'});
}}
style={{alignItems: 'center', width: '80%'}}>
<Text
font={'Inter'}
style={{fontSize: 16, fontWeight: 'bold'}}>
{t('app.login.options.login_regular')}
</Text>
</Button>
<Button
onPress={() => {
this.setState({loginType: 'token'});
}}
style={{alignItems: 'center', width: '80%'}}>
<Text
font={'Inter'}
style={{fontSize: 16, fontWeight: 'bold'}}>
{t('app.login.options.login_session_token')}
</Text>
</Button>
<Button
onPress={() => {
openUrl(
client.configuration
? `${client.configuration.app}/login/create`
: OFFICIAL_INSTANCE_SIGNUP_URL,
);
}}
style={{width: '80%'}}>
<View style={{alignItems: 'center'}}>
<Text
font={'Inter'}
style={{fontSize: 16, fontWeight: 'bold'}}>
{t('app.login.options.signup')}
</Text>
<Text font={'Inter'}>
{t('app.login.options.signup_body')}
</Text>
</View>
</Button>
<Text
font={'Inter'}
colour={currentTheme.foregroundSecondary}>
{t('app.login.instance_notice', {
url: app.settings.get('app.instance'),
})}
</Text>
</>
)}
</View>
</>
) : (
<View style={styles.loggingInScreen}>
<Text style={{fontSize: 30, fontWeight: 'bold'}}>
{t('app.loading.connecting')}
</Text>
<Text style={styles.remark}>{selectedRemark || null}</Text>
</View>
)}
</>
) : this.state.status === 'loginSettings' ? (
<LoginSettingsPage state={this} />
) : (
<View style={styles.loggingInScreen}>
<Text style={{fontSize: 30, fontWeight: 'bold'}}>Uh oh...</Text>
<Text style={styles.remark}>
Please let the developers know that you saw this (value:{' '}
{this.state.status})
</Text>
</View>
)}
</View>
);
}
}
const MainViewi18n = withTranslation()(MainView);
function ErrorMessage({
error,
resetErrorBoundary,
}: {
error: any;
resetErrorBoundary: Function;
}) {
console.error(`[APP] Uncaught error: ${error}`);
return (
<View style={{flex: 1, padding: 16, justifyContent: 'center'}}>
<Text
style={{
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
}}>
<Text style={{fontSize: 30, fontWeight: 'bold'}}>
OOPSIE WOOPSIE!! {'UwU\n'}
</Text>
We made a fucky wucky!! A wittle fucko boingo! The code monkeys at our
headquarters are working VEWY HAWD to fix this! {'>w<\n\n'}
On a more serious note, please let us know that you experienced the
following error:
</Text>
<View
style={{
backgroundColor: currentTheme.background,
borderRadius: 8,
marginVertical: 16,
padding: 16,
}}>
<Text font={'JetBrains Mono'} colour={'#ff5555'}>
{error.toString()}
</Text>
</View>
<Button
onPress={() => {
Clipboard.setString(error.toString());
}}>
<Text>Copy error message</Text>
</Button>
<Button
onPress={() => {
resetErrorBoundary();
}}>
<Text>Reload app</Text>
</Button>
</View>
);
}
export const App = () => {
return (
<GestureHandlerRootView style={styles.outer}>
<StatusBar
animated={true}
backgroundColor={currentTheme.backgroundSecondary}
barStyle={(currentTheme.contentType + '-content') as StatusBarStyle}
/>
<ErrorBoundary fallbackRender={ErrorMessage}>
<MainViewi18n />
</ErrorBoundary>
</GestureHandlerRootView>
);
};