This repository has been archived by the owner on Oct 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
3072 lines (2773 loc) · 120 KB
/
App.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
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
UniceNotes
Votre ENT. Dans votre poche.
Développé par Hugo Meleiro (@hugofnm) / MetrixMedia
MIT License
2022 - 2025
*/
// ---------------------------------------------
// IMPORTS
// ---------------------------------------------
// React components
import React, { useState, useEffect, useRef,
useMemo, createRef, useCallback
} from 'react';
import { Alert, View, StyleSheet,
AppState, ScrollView, RefreshControl,
Appearance, BackHandler, SafeAreaView,
SafeAreaProvider, Keyboard, Platform
} from 'react-native';
// Material Design 3 components (React Native Paper)
import { Avatar, Text, TextInput,
Button, Switch, Divider,
ActivityIndicator, ProgressBar, Chip,
DataTable, Card, Provider as PaperProvider,
IconButton, Appbar, Tooltip,
List, configureFonts, SegmentedButtons,
TouchableRipple, Menu, Searchbar
} from 'react-native-paper';
// Expo components
import { StatusBar } from 'expo-status-bar';
import * as LocalAuthentication from 'expo-local-authentication';
import * as SecureStore from 'expo-secure-store';
import * as WebBrowser from 'expo-web-browser';
import { Image } from 'expo-image';
import * as Haptics from 'expo-haptics';
import * as Network from 'expo-network';
import * as Linking from 'expo-linking';
import * as Font from 'expo-font';
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import Constants from "expo-constants";
import * as ImagePicker from 'expo-image-picker';
import * as StoreReview from 'expo-store-review';
import * as QuickActions from "expo-quick-actions";
// Third-party components
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NavigationContainer, CommonActions } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { CalendarBody, CalendarContainer, CalendarHeader } from '@howljs/calendar-kit';
import Animated, { event, log, set,
Easing, loop, useSharedValue,
useAnimatedStyle, withSpring, withRepeat,
withSequence
} from 'react-native-reanimated';
import Bugsnag from '@bugsnag/expo';
import LottieView from 'lottie-react-native';
import BottomSheet, { BottomSheetView, BottomSheetTextInput, BottomSheetBackdrop } from "@gorhom/bottom-sheet";
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { captureRef } from 'react-native-view-shot';
// Disable this when using Expo Go
import { setAppIcon } from "@hugofnm/expo-dynamic-app-icon";
// ---------------------------------------------
// VARIABLES GLOBALES
// ---------------------------------------------
// IMPORTANT !!!
var appVersion = '2.2.0';
var isBeta = false;
// IMPORTANT !!!
var initialQuickAction = null; // Quick action
var isConnected = false; // UniceAPI login
var dataIsLoaded = false; // JSONPDF loaded
var semesters = []; // User's all semesters
var semester = ''; // Selected semesters
var calendar = {}; // User's calendar
const servers = [
"https://api.unice.hugofnm.fr"
]; // UniceAPI servers
// Temporary variables - SecureStore
var username = SecureStore.getItemAsync("username").then((result) => {
if (result != null) {
username = result;
} else {
username = null;
}
}).catch((error) => {
haptics("error");
Alert.alert("Erreur", "Impossible de récupérer les données de connexion. EC=0xR");
deleteData(false);
}); // User's username
var password = SecureStore.getItemAsync("passkey").then((result) => {
if (result != null) {
password = result;
} else {
password = null;
}
}).catch((error) => {
haptics("error");
Alert.alert("Erreur", "Impossible de récupérer les données de connexion. EC=0xR");
deleteData(false);
}); // User's password
var adeid = SecureStore.getItemAsync("adeid").then((result) => {
if (result != null) {
adeid = result;
} else {
adeid = null;
}
}).catch((error) => {
haptics("error");
Alert.alert("Erreur", "Impossible de récupérer les données de connexion. EC=0xR");
deleteData(false);
}); // User's ADE Identifier (emploi du temps)
// Temporary variables - AsyncStorage
var name = AsyncStorage.getItem("name").then((result) => {
if (result != null) {
name = result.toString();
} else {
if (username != null) {
haptics("error");
Alert.alert("Erreur", "Données manquantes pour la bonne exécution de l'application. Veuillez vous connecter à nouveau. EC=0xR");
deleteData(false);
} else {
name = "Étudiant";
}
}
}).catch((error) => {
haptics("error");
Alert.alert("Erreur", "Impossible de récupérer les données de connexion. EC=0xR");
deleteData(false);
}); // User's name
var hapticsOn = AsyncStorage.getItem("haptics").then((result) => {
if (result != null) {
hapticsOn = (result === 'true');
} else {
hapticsOn = true;
}
}); // Haptics on/off
var selectedServer = AsyncStorage.getItem("server").then((result) => {
if (result != null) {
if (result.toString() == servers[0].toString()) {
selectedServer = servers[0].toString();
} else {
selectedServer = result.toString()
servers.push(selectedServer);
}
} else {
selectedServer = servers[0].toString();
}
}); // Serveur sélectionné
var userADEData = AsyncStorage.getItem("userADEData").then((result) => {
if (result != null) {
userADEData = JSON.parse(result);
} else {
userADEData = {
"cursus": "demo",
"uid": "demo"
};
}
}); // User's ADE data
var rememberMe = true; // Remember me
var grades = []; // User's grades
var average = ""; // User's average
var admission = ""; // User's admission
var position = ""; // User's position
var subjects = []; // User's subjects
// ---------------------------------------------
// FONCTIONS GLOBALES
// ---------------------------------------------
if (!__DEV__) {
Bugsnag.start({
onError: function (event) {
event.addMetadata('utilisateur', {
name: name,
username: username
})
}
})
}
// SecureStore API
async function saveSecure(key, value) {
await SecureStore.setItemAsync(key, value);
}
// AsyncStorage API
async function saveAsyncStore(key, value) {
await AsyncStorage.setItem(key, value);
}
// Fonction de suppression des données - GDPR friendly :)
async function deleteData(warnings = false, navigation = null) {
if (warnings) {
haptics("warning");
}
if(!__DEV__ && Platform.OS == "ios" && parseInt(Platform.Version, 10) >= 18){
setAppIcon("unicenotes");
}
// Suppression des données
await SecureStore.deleteItemAsync("username"); // Suppression du nom d'utilisateur
username = null;
await SecureStore.deleteItemAsync("passkey"); // Suppression du mot de passe
password = null;
await SecureStore.deleteItemAsync("adeid"); // Suppression de l'identifiant ADE
adeid = "";
await AsyncStorage.removeItem("name"); // Suppression du nom
name = "";
await AsyncStorage.removeItem("haptics"); // Suppression des paramètres retours haptiques
hapticsOn = true;
await saveJSONToFile({}); // Suppression du calendrier hors-ligne
calendar = {};
await AsyncStorage.removeItem("server"); // Suppression du serveur sélectionné
selectedServer = servers[0].toString();
await AsyncStorage.removeItem("userADEData"); // Suppression des données ADE utilisateur
userADEData = {
"cursus": "demo",
"uid": "demo"
};
await FileSystem.deleteAsync(FileSystem.documentDirectory + 'calendar.json'); // Suppression du calendrier hors-ligne
await FileSystem.deleteAsync(FileSystem.documentDirectory + 'profile.png'); // Suppression de la photo de profil
await Image.clearDiskCache();
await Image.clearMemoryCache();
await AsyncStorage.clear();
if (warnings) {
Alert.alert("Données supprimées", "Retour à la page de connexion.");
haptics("success");
}
if (navigation != null) {
logout(navigation);
}
}
// Ouverture de pages web dans le navigateur par défaut
const handleURL = async (url) => {
haptics("selection");
await WebBrowser.openBrowserAsync(url);
};
// Fonction de déconnexion (UniceAPI + app si "Se souvenir de moi" est désactivé)
function logout(navigation) {
haptics("heavy");
isConnected = false;
dataIsLoaded = false;
if (rememberMe == false) {
password = null;
}
fetch(selectedServer + '/logout');
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [
{ name: 'SplashScreen' }
],
})
);
}
// Fonction de retour haptique
function haptics(intensity) {
if(hapticsOn == true) {
switch(intensity) {
case "light":
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
break;
case "medium":
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
break;
case "heavy":
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy);
break;
case "error":
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
break;
case "success":
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
break;
case "warning":
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
break;
case "selection":
Haptics.selectionAsync();
break;
}
}
}
// Fonction navigate vers paramètres
function goToSettings(navigation) {
haptics("medium");
navigation.navigate('ShowSettings');
}
async function getPhotoFromLocal() {
var photo = "";
let options = { encoding: FileSystem.EncodingType.Base64 };
await FileSystem.readAsStringAsync((FileSystem.documentDirectory + "profile.png"), options)
.then((result) => {
photo = "data:image/png;base64," + result;
})
.catch(async (error) => {
await getPhotoFromENT();
});
return photo;
}
async function getPhotoFromENT() {
await FileSystem.downloadAsync(
selectedServer + "/avatar",
FileSystem.documentDirectory + 'profile.png'
)
return;
}
// ---------------------------------------------
// FONCTIONS API EMPLOI DU TEMPS
// ---------------------------------------------
const saveJSONToFile = async (data) => {
const fileUri = FileSystem.documentDirectory + 'calendar.json'; // Specify the file path and name
try {
await FileSystem.writeAsStringAsync(fileUri, JSON.stringify(data));
} catch (error) {
console.error('Error saving JSON file:', error);
}
};
const readJSONFromFile = async () => {
const fileUri = FileSystem.documentDirectory + 'calendar.json'; // Specify the file path and name
try {
const jsonContent = await FileSystem.readAsStringAsync(fileUri);
const parsedData = JSON.parse(jsonContent);
return parsedData;
} catch (error) {
Alert.alert("Erreur", "Veuillez télécharger le calendrier avant de l'utiliser en mode hors-ligne ! EC=0xR");
haptics("error");
return null;
}
};
// Lighten the color
const pSBC=(p,c0,c1,l)=>{
let r,g,b,P,f,t,h,i=parseInt,m=Math.round,a=typeof(c1)=="string";
if(typeof(p)!="number"||p<-1||p>1||typeof(c0)!="string"||(c0[0]!='r'&&c0[0]!='#')||(c1&&!a))return null;
if(!this.pSBCr)this.pSBCr=(d)=>{
let n=d.length,x={};
if(n>9){
[r,g,b,a]=d=d.split(","),n=d.length;
if(n<3||n>4)return null;
x.r=i(r[3]=="a"?r.slice(5):r.slice(4)),x.g=i(g),x.b=i(b),x.a=a?parseFloat(a):-1
}else{
if(n==8||n==6||n<4)return null;
if(n<6)d="#"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(n>4?d[4]+d[4]:"");
d=i(d.slice(1),16);
if(n==9||n==5)x.r=d>>24&255,x.g=d>>16&255,x.b=d>>8&255,x.a=m((d&255)/0.255)/1000;
else x.r=d>>16,x.g=d>>8&255,x.b=d&255,x.a=-1
}return x};
h=c0.length>9,h=a?c1.length>9?true:c1=="c"?!h:false:h,f=this.pSBCr(c0),P=p<0,t=c1&&c1!="c"?this.pSBCr(c1):P?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},p=P?p*-1:p,P=1-p;
if(!f||!t)return null;
if(l)r=m(P*f.r+p*t.r),g=m(P*f.g+p*t.g),b=m(P*f.b+p*t.b);
else r=m((P*f.r**2+p*t.r**2)**0.5),g=m((P*f.g**2+p*t.g**2)**0.5),b=m((P*f.b**2+p*t.b**2)**0.5);
a=f.a,t=t.a,f=a>=0||t>=0,a=f?a<0?t:t<0?a:a*P+t*p:0;
if(h)return"rgb"+(f?"a(":"(")+r+","+g+","+b+(f?","+m(a*1000)/1000:"")+")";
else return"#"+(4294967296+r*16777216+g*65536+b*256+(f?m(a*255):0)).toString(16).slice(1,f?undefined:-2)
}
// Convert a string to a color
var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return pSBC(0.25, colour);
}
// Récupération du calendrier de l'utilisateur depuis le cache
async function getCalendarFromCache() {
var cal = await readJSONFromFile();
formattedCal = [];
if(cal != null) {
cal.map((item) => {
formattedCal.push({
id : item.id,
start: { dateTime : item.start_time},
end: { dateTime : item.end_time},
title: item.summary,
subtitle: item.description,
description: item.location,
color: stringToColour(item.summary)
})
});
} else {
formattedCal = [];
}
calendar = formattedCal;
return formattedCal;
}
// Récupération du calendrier de l'utilisateur
async function getCalendar() {
haptics("medium");
var netInfos = (await Network.getNetworkStateAsync()).isInternetReachable;
if (adeid == null) {
haptics("error");
Alert.alert("Erreur", "Votre identifiant ADE est introuvable. Veuillez fermer de force l'application et réessayez.");
deleteData(false);
return;
}
if (netInfos == true) {
try{
var cal = await fetch(selectedServer + '/edt/' + adeid.toString(), {
method: 'POST',
headers: {
"Accept": "application/json",
"Charset": "utf-8"
}
})
} catch(e) {
haptics("error");
Alert.alert("Erreur", "Impossible de récupérer l'emploi du temps. EC=0xS");
return;
}
cal = await cal.json();
saveJSONToFile(cal);
formattedCal = [];
cal.map((item) => {
formattedCal.push({
id : item.id,
start: { dateTime : item.start_time},
end: { dateTime : item.end_time},
title: item.summary,
subtitle: item.description,
description: item.location,
color: stringToColour(item.summary)
})
});
return formattedCal;
} else {
formattedCal = await getCalendarFromCache();
return formattedCal;
}
}
// ---------------------------------------------
// FONCTIONS NOTIFICATION PUSH
// ---------------------------------------------
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
// ---------------------------------------------
// FONCTIONS VIEW (ECRANS DE L'APPLICATION)
// ---------------------------------------------
// Page de transition (splashscreen)
function SplashScreen({ navigation }) {
const [count, setCount] = useState(0);
const [isDataStored, setIsDataStored] = useState(false);
const [loading, setLoading] = useState(true);
const [ok, setOk] = useState(true);
const [titleInfo, setTitleInfo] = useState("Infos");
const [subtitleInfo, setSubtitleInfo] = useState("");
const [actionInfo, setActionInfo] = useState("");
const [titleError, setTitleError] = useState("Erreur");
const [subtitleError, setSubtitleError] = useState("");
const insets = useSafeAreaInsets();
const renderBackdrop = useCallback(
(props) => (
<BottomSheetBackdrop {...props}
opacity={0.5}
enableTouchThrough={false}
appearsOnIndex={0}
disappearsOnIndex={-1}
style={[{ backgroundColor: 'rgba(0, 0, 0, 1)' }, StyleSheet.absoluteFillObject]}
/>
),
[]
);
useEffect(() => {
if (count == 0) {
setLoading(true);
access();
setCount(1);
}
});
async function verifyLogin() {
// Vérification de la version de l'application en récupérant le json contenant la dernière version
var version, isAvailable, maintenance, banned
var res = true;
if ((await Network.getNetworkStateAsync()).isInternetReachable == false) {
setLoading(false);
showError("nointernet");
res = false;
}
if (selectedServer != servers[0].toString() && res) {
// check 200 ok
await fetch("https://toolbox.hugofnm.fr/redirect?redirectUrl=" + selectedServer)
.then((response) => {
if(response.status != 200) {
setLoading(false);
showError("customservercheck");
res = false;
}
})
};
if (!servers.includes(selectedServer)) {
selectedServer = servers[0];
}
if(res) {
await fetch(selectedServer + "/status")
.then((response) => response.json())
.then((json) => {
version = json.version;
if(version != null) {
version = version.toString().replace("v", "");
isAvailable = json.isAvailable;
maintenance = json.maintenance;
banned = json.banned;
} else {
setLoading(false);
showError("noserver");
res = false;
}
})
.catch((error) => {
setLoading(false);
showError("noserver");
res = false;
});
}
if (banned == true && res) {
setLoading(false);
showInfos("ipban");
res = false;
}
if(!isBeta && isAvailable == true && version != appVersion && res) {
setLoading(false);
showInfos("update");
res = false;
}
if (maintenance != "" && res) {
setLoading(false);
showInfos("maintenance", maintenance);
res = false;
}
return res;
}
async function access(force = false) {
var accessOK = await verifyLogin();
accessOK ? setOk(true) : setOk(false);
if(force == true) {
accessOK = true;
setOk(true);
}
// Vérification de la disponibilité des usernames et mots de passe enregistrés
if(!isDataStored) {
setUsername(await SecureStore.getItemAsync("username"));
setPassword(await SecureStore.getItemAsync("passkey"));
if (username != null && password != null && accessOK) {
setLoading(false);
navigation.navigate('HomeScreen');
} else {
username = null;
password = null;
setIsDataStored(false);
if(accessOK) {
setLoading(false);
navigation.navigate('OOBE');
}
}
}
}
function setUsername(text) {
username = text;
}
function setPassword(text) {
password = text;
}
function specialMode() {
if(isBeta) {
return (
<Text style={{ textAlign: 'center' }} variant="displaySmall">BETA</Text>
);
}
if(!ok) {
return (
<Button style={{ marginTop: 16 }} icon="calendar-sync-outline" mode="contained" onPress={ () => getMyCal(navigation) }>Emploi du temps (hors-ligne)</Button>
);
}
}
function showInfos(action, overrideSubtitle = null){
if(action == "update") {
setTitleInfo("Mise à jour disponible");
setSubtitleInfo("Une nouvelle version de l'application est disponible. Veuillez la mettre à jour pour continuer à utiliser UniceNotes.");
setActionInfo("update");
} else if(action == "maintenance") {
setTitleInfo("Maintenance");
setSubtitleInfo(overrideSubtitle);
setActionInfo("maintenance");
} else if(action == "ipban") {
setTitleInfo("IP Bannie");
setSubtitleInfo("Votre adresse IP ne peut pas utiliser UniceNotes. Cliquez sur ce bouton pour en savoir plus.");
setActionInfo("ipban");
}
if(bottomSheetInfo != null) {
bottomSheetInfo.expand()
}
}
function showError(action){
if(action == "nointernet") {
setTitleError("Internet indisponible");
setSubtitleError("Vous n'êtes pas connecté à Internet ! EC=0xT");
} else if(action == "noserver") {
setTitleError("Serveur indisponible");
setSubtitleError("Le serveur n'est pas accessible ! Essayez de changer de serveur dans les paramètres. EC=0xS");
} else if(action == "customservercheck") {
setTitleError("Serveur custom indisponible");
setSubtitleError("Il est possible que sa configuration soit mauvaise ou bien qu'il soit banni. Essayez de changer de serveur dans les paramètres. EC=0xS");
}
if(bottomSheetError != null) {
setTimeout(() => {
bottomSheetError.expand()
}, 1000);
}
}
async function getMyCal(navigation) {
if(bottomSheetInfo != null) {
bottomSheetInfo.close()
}
calendar = await getCalendarFromCache();
navigation.navigate('ShowEDT');
}
function refresh() {
if(bottomSheetInfo != null) {
bottomSheetInfo.close()
}
if(bottomSheetError != null) {
bottomSheetError.close()
}
setCount(0);
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: choosenTheme.colors.background }}>
<Image source={require('./assets/color.png')} style={{ width: 200, height: 200, marginBottom: 16 }} />
<Text style={{ textAlign: 'center' }} variant="displayLarge">UniceNotes</Text>
{specialMode()}
<View style={{ display: "flex", flexDirection: 'row', justifyContent:'center' }}>
<Tooltip title="Paramètres">
<IconButton style={{ marginTop: 16 }} icon="cog" mode="contained" onPress={ () => goToSettings(navigation) }/>
</Tooltip>
<Tooltip title="Rafraîchir">
<IconButton style={{ marginTop: 16 }} icon="refresh" mode="contained" onPress={ () => refresh() }/>
</Tooltip>
</View>
<BottomSheet ref={(sheet) => bottomSheetInfo = sheet} index={-1} enableDynamicSizing enablePanDownToClose contentHeight={64} bottomInset={ insets.bottom } detached={true} style={{ marginHorizontal: 24 }} backgroundStyle={{ backgroundColor: style.container.surfaceVariant }} handleIndicatorStyle={{ backgroundColor: choosenTheme.colors.onSurfaceVariant }} backdropComponent={renderBackdrop}>
<BottomSheetView style={{ paddingLeft: 25, paddingRight: 25 }}>
<Text style={{ textAlign: 'left', marginBottom: 8, marginTop: 8 }} variant="headlineSmall">{titleInfo}</Text>
<Text style={{ textAlign: 'left', marginBottom: 16 }} variant="titleMedium">{subtitleInfo}</Text>
{
actionInfo == "update" ? (
<Button style={{ marginBottom: 16 }} icon="download" mode="contained" onPress={() => handleURL("https://notes.metrixmedia.fr/get")}>Mettre à jour</Button>
) : ( null )
}
{
actionInfo == "maintenance" ? (
<Button style={{ marginBottom: 16 }} icon="chef-hat" mode="contained" onPress={() => access(true)}>Ok chef !</Button>
) : ( null )
}
{
actionInfo == "ipban" ? (
<Button style={{ marginBottom: 16 }} icon="information" mode="contained" onPress={() => handleURL("https://github.com/UniceApps/UniceNotes/blob/main/.docs/USAGE.md")}>En savoir plus</Button>
) : ( null )
}
</BottomSheetView>
</BottomSheet>
<BottomSheet ref={(sheet) => bottomSheetError = sheet} index={-1} enableDynamicSizing enablePanDownToClose contentHeight={64} bottomInset={ insets.bottom } detached={true} style={{ marginHorizontal: 24 }} backgroundStyle={{ backgroundColor: style.container.errorContainer }} handleIndicatorStyle={{ backgroundColor: choosenTheme.colors.onErrorContainer }} backdropComponent={renderBackdrop}>
<BottomSheetView style={{ paddingLeft: 25, paddingRight: 25 }}>
<Text style={{ textAlign: 'left', marginBottom: 8, marginTop: 8 }} variant="headlineSmall">{titleError}</Text>
<Text style={{ textAlign: 'left', marginBottom: 16 }} variant="titleMedium">{subtitleError}</Text>
<Button style={{ marginBottom: 16, backgroundColor: style.container.error }} icon="refresh" mode="contained" onPress={() => refresh()}>Rafraîchir</Button>
</BottomSheetView>
</BottomSheet>
<ActivityIndicator style={{ marginTop: 16 }} animating={loading} size="large" />
</View>
);
}
// Page OOBE (On-boarding experience)
function OOBE({ navigation }) {
const [secondCard, setSecondCard] = useState(false);
const [thirdCard, setThirdCard] = useState(false);
const [fourthCard, setFourthCard] = useState(false);
const insets = useSafeAreaInsets();
// ----------------
// Animation stuff
// ----------------
const rotation = useSharedValue(0);
// Configure the animation of the logo
const rotateConfig = {
damping: 2,
stiffness: 15,
};
// Define the rotation animation
rotation.value = withRepeat(
withSequence(
withSpring(0, rotateConfig),
withSpring(360, rotateConfig)
),
-1, // -1 means infinite loop
false // use false to indicate non-reversing rotation
);
// Create an animated style for the logo
const animatedStyleLogo = useAnimatedStyle(() => {
return {
transform: [{ rotate: `${rotation.value}deg` }],
};
});
// ----------------
// Login stuff
// ----------------
const [seePassword, setSeePassword] = useState(true);
const [editable, setEditable] = useState(true);
const [remember, setRemember] = useState(rememberMe);
const [ok, setOk] = useState(false);
const [appearance, setAppearance] = useState(Appearance.getColorScheme());
// Résultat du bouton "Se connecter"
function handleLogin(eula = false) {
if (username == null || password == null) {
haptics("warning");
Alert.alert("Erreur", "Veuillez entrer un nom d'utilisateur et un mot de passe.");
} else {
Keyboard.dismiss();
haptics("medium");
setEditable(false);
handleButtonPress();
ssoUnice(username, password, eula);
}
}
// Connexion au SSO de l'Université Nice Côte d'Azur et vérification des identifiants
async function ssoUnice(username, password, eula) {
if(!isConnected || !ok) {
let apiResp = await fetch(selectedServer + "/signup", {
method: 'POST',
body: JSON.stringify({
username: username,
password: password,
eula: eula
}),
headers: {
"Accept": "application/json",
"Content-type": "application/json",
"Charset": "utf-8"
}
})
if(apiResp.status == 429) {
deleteData(false);
AsyncStorage.clear();
haptics("error");
Alert.alert(
"Erreur",
"Vous effectuez trop de requêtes. L'application contient peut-être des données trop anciennes pour les traîter. \n\nL'application va redémarrer pour tenter de les supprimer.",
[{ text: "OK", onPress: () => { throw new Error('Data deletion forced') } }]
);
}
if(apiResp.status == 203) {
setEditable(true);
haptics("medium");
setFourthCard(true);
return;
}
if(!apiResp.ok){
setEditable(true);
haptics("error");
Alert.alert("Erreur", "Connexion au serveur impossible. EC=0xS");
setThirdCard(false);
}
let json = await apiResp.json();
if(json.success) {
// Sauvegarde des identifiants si "Se souvenir de moi" est activé
if(rememberMe) {
saveSecure("username", username);
saveSecure("passkey", password);
await getPhotoFromENT();
var token = await registerForPushNotificationsAsync();
if(token != null) {
await fetch(selectedServer + '/push', {
method: 'POST',
body: JSON.stringify({
username: username,
token: token
}),
headers: {
"Accept": "application/json",
"Content-type": "application/json",
"Charset": "utf-8"
}
})
}
}
userADEData = json.userADEData;
saveAsyncStore("userADEData", JSON.stringify(userADEData));
adeid = userADEData.uid;
saveSecure("adeid", adeid);
name = json.name;
if (name == null) {
name = "Étudiant";
}
saveAsyncStore("name", name);
semesters = json.semesters;
haptics("success");
setOk(true);
} else {
setEditable(true);
haptics("warning");
Alert.alert("Erreur", "Vos identifiants sont incorrects. EC=0xI");
setThirdCard(false);
}
}
};
useEffect(() => {
if(ok) {
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [
{ name: 'HomeScreen' }
],
})
);
}
}, [ok]);
function setUsername(text) {
username = text;
}
function setPassword(text) {
password = text;
}
function setRememberMe(bool) {
setRemember(bool);
rememberMe = bool;
}
const handleButtonPress = () => {
if(!secondCard && !thirdCard && !fourthCard) { // après bouton suivant sur le premier écran, on permute le deuxième écran
setSecondCard(true);
}
if(secondCard && !thirdCard && !fourthCard) { // après login, on bascule sur le loading login
setThirdCard(true);
}
if (secondCard && thirdCard && fourthCard) { // après acceptation EULA, on revient sur le loading login
setFourthCard(false);
}
};
function goToSettingsSpecial(navigation) {
haptics("medium");
navigation.goBack();
navigation.navigate('ShowSettings');
}
// ----------------
// Notifications stuff
// ----------------
async function registerForPushNotificationsAsync() {
let token;
try {
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
return;
}
token = await Notifications.getExpoPushTokenAsync({
projectId: Constants.expoConfig.extra.eas.projectId,
});
} else {
alert('Must use physical device for Push Notifications');
}
return token.data;
} catch (error) {
return;
}
}
return (
<View style={style.container}>