-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHome copy.js
1912 lines (1714 loc) · 59.9 KB
/
Home copy.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
import { StatusBar } from "expo-status-bar";
import * as React from "react";
import {
View,
Text,
Image,
TouchableOpacity,
useWindowDimensions,
ActivityIndicator,
FlatList,
ScrollView,
Modal,
Alert,
} from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import * as ImagePicker from "expo-image-picker";
import {
addDoc,
doc,
collection,
getFirestore,
getDocs,
query,
deleteDoc,
orderBy,
startAfter,
limit,
startAt,
endBefore,
updateDoc,
setDoc,
getDoc,
where,
increment,
} from "firebase/firestore/";
import { signOut, getAuth } from "firebase/auth";
import {
Menu,
MenuOptions,
MenuOption,
MenuTrigger,
MenuProvider,
} from "react-native-popup-menu";
var aesjs = require("aes-js");
import Spinner from "react-native-loading-spinner-overlay";
const axios = require("axios").default;
import * as Progress from "react-native-progress";
/*import { TreewalkCarSplitter } from "carbites/treewalk";
import { CarReader } from "@ipld/car";
import { CarWriter } from "@ipld/car/lib/writer-browser";
import { pack } from "ipfs-car/dist/esm/pack";
import { packToBlob } from "ipfs-car/dist/esm/pack/blob";
import { MemoryBlockStore } from "ipfs-car/dist/esm/blockstore/memory";
import { NFTStorage } from "nft.storage";
import { Blockstore } from "nft.storage/src/platform";
import { BlockstoreCarReader } from "nft.storage/src/bs-car-reader";
import { transform } from "streaming-iterables";*/
import { FloatingMenu } from "react-native-floating-action-menu";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import config from "./config";
import { Web3Storage, File } from 'web3.storage/dist/bundle.esm.min.js'
import copy from "copy-to-clipboard";
import { LogBox } from 'react-native';
LogBox.ignoreLogs(['Setting a timer']);
import * as DocumentPicker from 'expo-document-picker';
let mutexFoto = false;
let controllerFetch = new AbortController();
let controllerFetchDownload = new AbortController();
//ho modificato il costruttore in modo da accettare l'abort controller per poter annullare il caricamento
let web3s = new Web3Storage({
token: config.Web3StorageToken,
abortController: controllerFetch,
});
const Home = ({ route, navigation }) => {
//per dimensioni finestra in real time
const winSize = useWindowDimensions();
//inizializzo databse e autenticazione firebase
const db = getFirestore();
const auth = getAuth();
//state con array di immagini da caricare
let [images, setImages] = React.useState([]);
//state con array di cartelle da caricare
let [folders, setFolders] = React.useState([]);
//state per gestire cartelle
let [stackDir, setStackDir] = React.useState(["Photos"]);
//state per gestire barra caricamento
let [progressValue, setProgressValue] = React.useState({
value: 0,
total: 100,
});
//inizializzo overlay caricamento
let [spinnerVisible, setSpinnerVisibile] = React.useState(false);
//per non mostrare pulsante durante reload e primo caricamento
let [reload, setReload] = React.useState(false);
//state apertura menu
let [menuOpen, setMenuOpen] = React.useState(false);
//numero file da caricare
let [numFile, setNumFile] = React.useState({ current: 0, total: 0 });
//per gestire poi il modal del menu del file o cartella
let [elementoSelezionato, setElementoSelezionato] = React.useState({});
//per selezionare il modal da mostrare 1=file 2 =folders 0=niente
let [valueModal, setValueModal] = React.useState(0);
let aggiornaFoto = function (newPhotoId) {
return new Promise(async (resolve, reject) => {
if (!mutexFoto) {
mutexFoto = true;
//prendo i cid da firebase prendo il zip dall url ipfs + cid lo unzippo e creo il blob per mostrarlo
let emailDOT = route.params.email;
//replace all '.' from email to 'DOT'
emailDOT = emailDOT.replace(/\./g, "DOT");
let data = await getDocs(
query(
collection(
db,
"Utenti",
emailDOT,
"Photos"
),
orderBy("data", "desc"),
where("dir", "==", stackDir)
)
);
//carico cartelle
setFolders([]);
let listFold = await getDocs(
query(
collection(
db,
"Utenti",
emailDOT,
"folders"
),
where("dir", "==", stackDir)
)
);
//carico nome cartelle nello state
for (let j = 0; j < listFold.docs.length; j++) {
setFolders((oldFolders) => [
...oldFolders,
{
id: listFold.docs[j].id,
name: listFold.docs[j].data().name,
data: listFold.docs[j].data().data,
},
]);
}
//uso questa i per sbloccare il mutex solo quando il fetch ha finito e sono state caricate
//tutte le foto
let i = 0;
//sblocco il mutex se se è vuota la lista
if (data.docs.length == 0) resolve();
for (i; i < data.docs.length; i++) {
//controllo se non è già presente nello state altrimenti ogni volta ad esempio che carichi un nuova foto
//ricarica tutto
if (
!images.includes(
images.filter((obj) => obj.id === data.docs[i].id)[0]
)
) {
let item = {
cid: data.docs[i].data().cid,
data: data.docs[i].data().data,
id: data.docs[i].id,
name: data.docs[i].data().name,
type: data.docs[i].data().type,
size: data.docs[i].data().size,
//Assegno un altezza a caso per il rendering
ranHeightImage:
Math.random() < 0.5
? undefined
: winSize.width < 900
? hp("20%")
: hp("25%"),
};
try {
item.notPrivate = data.docs[i].data().notPrivate;
} catch (err) {}
//se viene aggiunta una nuova immagine la metto all'inizio dellarray e poi esco dal for
//in modo che carico solo le nuove immagini e non ripeteo il caricamento delle altre gia presenti
if (data.docs[i].id == newPhotoId) {
setImages((oldArray) => [item, ...oldArray]);
i = data.docs.length;
} else {
setImages((oldArray) => [...oldArray, item]);
}
//sblocco il mutex se sono state caricate tutte le foto
if (data.docs.length - 1 == i) {
resolve();
}
} else {
//se è gia presente l'immagine
//sblocco il mutex se sono state caricate tutte le foto
if (data.docs.length - 1 == i) {
resolve();
}
}
}
}
resolve();
});
};
//Eseguito Appena si apre la pagina e quando premo pulsante reload
React.useEffect(async () => {
if (images.length == 0) {
setSpinnerVisibile(true);
setReload(true);
aggiornaFoto().then(() => {
mutexFoto = false;
setSpinnerVisibile(false);
setReload(false);
});
}
}, [images]);
//eseguito quando cambia elemento selezionato
React.useEffect(() => {
//per gestire il click diretto sul file o sulla cartella, senza passare per il modal
if (elementoSelezionato.modalita == "diretta") {
if (elementoSelezionato.size != undefined) menuSelection(1);
else menuSelectionFolder(3);
}
}, [elementoSelezionato]);
//picker immagini
// let openImagePickerAsync = async (selectedResult) => {
// //alert per scelta upload files pubblici o privati
// // let response = confirm(
// // "Do you want upload private (encrypted) or public (not encrypted) files? ('OK' for private, 'Cancel' for public)"
// // );
// let response = true;
// //per alert conferma caricamento tutti i file
// let errorLoading = false;
// for (let i = 0; i < selectedResult.length; i++) {
// //metto rotellina
// setReload(true);
// //metto overlay caricamneto
// setSpinnerVisibile(true);
// //per segnare durante il caricamento quale file si sta caricando
// setNumFile({ current: i + 1, total: selectedResult.length });
// //se è privato lo cifro altrimenti non lo cifro
// let filebuffer;
// if (response) {
// let enc = new TextEncoder();
// //allungo la password inserendo k perchè deve essere almeno essere lunga 16 per generare la chiave
// let passwordKey = route.params.password;
// while (passwordKey.length < 16) passwordKey += "k";
// //genero key con la password
// let key = await window.crypto.subtle.importKey(
// "raw",
// enc.encode(passwordKey),
// "AES-GCM",
// false,
// ["encrypt", "decrypt"]
// );
// //cifro il file
// filebuffer = await window.crypto.subtle.encrypt(
// { name: "AES-GCM", iv: enc.encode(passwordKey) },
// key,
// await selectedResult[i].arrayBuffer()
// );
// } else {
// filebuffer = await selectedResult[i].arrayBuffer();
// }
// //levo rotellina
// setReload(false);
// //resetto la progress bar
// setProgressValue({ value: 0, total: 100 });
// //id file per il catch
// let idFile;
// try {
// /*let json;
// if ((selectedResult[i].size / 1000000).toFixed(2) < 100) {
// json = await axios.request({
// url: "https://api.web3.storage/upload",
// method: "POST",
// signal: controllerFetch.signal,
// headers: {
// Authorization: "Bearer " + config.Web3StorageToken,
// },
// data: cifrato,
// onUploadProgress: (prog) => {
// setProgressValue({ value: prog.loaded, total: prog.total });
// },
// });
// } else {
// /* let BlobCifrato = new Blob([cifrato]);
// const blockstore = new Blockstore();
// const { root: cid } = await pack({
// input: [{ path: "blob", content: BlobCifrato.stream() }],
// blockstore: blockstore,
// wrapWithDirectory: false,
// });
// const car = new BlockstoreCarReader(1, [cid], blockstore);
// const targetSize = 1024 * 1024 * 10;
// const splitter =
// car instanceof Blob
// ? await TreewalkCarSplitter.fromBlob(car, targetSize)
// : new TreewalkCarSplitter(car, targetSize);
// //li uso per la barra di caricamento
// let counterCars = 0;
// for await (const cid of splitter.cars()) {
// counterCars++;
// }
// let caricati = 0;
// const upload = transform(3, async function (car) {
// const carParts = [];
// for await (const part of car) {
// carParts.push(part);
// }
// const carFile = new Blob(carParts, { type: "application/car" });
// const response = await axios.request({
// onUploadProgress: (event) => {
// setProgressValue({
// value: event.loaded,
// total: event.total,
// });
// },
// url: /*"https://api.nft.storage/upload"*/
// /* "https://api.web3.storage/car",
// method: "POST",
// signal: controllerFetch.signal,
// headers: {
// "content-Type": "application/car",
// Authorization:*/
// /*"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDgyNTY0MzFEQUYwMjU4MEFENTU5NDU2NDc0OURhQWJCZTY5NWUzRjkiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY0Mjg3NjE3NTM0OCwibmFtZSI6ImRzdG9yYWdlIn0.TeG3_YYxhZeWtzpPPNxoietTB0yezr_Pqvq30yjao5w",*/
// /* "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDg3RTZiZDFhYTUyOUNmYWRmOURhMGY0NTNiMEE4ZDlGRDM3MjM2ZUIiLCJpc3MiOiJ3ZWIzLXN0b3JhZ2UiLCJpYXQiOjE2NDU0NTQ1NTcyNjUsIm5hbWUiOiJEUGhvdG8ifQ.WM4zuZ9UuGwODetDm37xMmpPLkCXXai-wAxw9Opf7Yk",
// },
// data: carFile,
// });
// return response.data.value.cid;
// });
// let root;
// for await (const cid of upload(splitter.cars())) {
// //aggiorno progresso caricamento
// caricati = caricati + 1;
// setProgressValue({ value: caricati, total: counterCars });
// root = cid;
// }
// json = cid.toString();*/
// /* let BlobCifrato = new Blob([cifrato]);
// const blockstore = new Blockstore();
// const { root: cid, out: iterable } = await pack({
// input: [{ path: "blob", content: BlobCifrato.stream() }],
// blockstore: blockstore,
// wrapWithDirectory: false,
// });
// const car = await CarReader.fromIterable(iterable);
// const targetSize = 100000000;
// const splitter = new TreewalkCarSplitter(car, targetSize);
// //li uso per la barra di caricamento
// let counterCars = Math.floor(BlobCifrato.size / targetSize);
// let caricati = 0;
// console.log(counterCars);
// const upload = transform(3, async function (smallCar) {
// const carParts = [];
// for await (const part of smallCar) {
// carParts.push(part);
// }
// const carFile = new Blob(carParts, { type: "application/car" });
// const response = await axios.request({
// url: "https://api.web3.storage/car",
// method: "POST",
// signal: controllerFetch.signal,
// headers: {
// "content-Type": "application/car",
// Authorization: "Bearer " + config.Web3StorageToken,
// },
// data: carFile,
// });
// });
// for await (const cid of upload(splitter.cars())) {
// //aggiorno progresso caricamento
// caricati = caricati + 1;
// setProgressValue({ value: caricati, total: counterCars });
// }
// json = cid.toString();
// }*/
// //carico file su web3.storage
// let caricato = 0;
// const file = new File([filebuffer], "file");
// const json = await web3s.put([file], {
// wrapWithDirectory: false,
// onStoredChunk: (size) => {
// //aggiorno lo stato del caricamento
// caricato = Math.floor(caricato + size);
// if (caricato > file.size)
// setProgressValue({ value: file.size, total: file.size });
// else setProgressValue({ value: caricato, total: file.size });
// },
// controllerFetch,
// });
// //aggiungo cid a firebase
// let emailDOT = route.params.email;
// //replace all '.' from email to 'DOT'
// emailDOT = emailDOT.replace(/\./g, "DOT");
// let el = await addDoc(
// collection(
// db,
// "Utenti",
// emailDOT,
// "Photos"
// ),
// {
// cid:
// /*cid.ipnft*/ json.data == undefined
// ? json
// : json.data /*.value*/.cid,
// data: Date.now(),
// name: selectedResult[i].name,
// type:
// selectedResult[i].name.substring(
// selectedResult[i].name.lastIndexOf(".") + 1
// ) == "rar" ||
// selectedResult[i].name.substring(
// selectedResult[i].name.lastIndexOf(".") + 1
// ) == "zip"
// ? "application/zip"
// : selectedResult[i].type,
// size: selectedResult[i].size,
// dir: stackDir,
// notPrivate: !response,
// }
// );
// idFile = el.id;
// await aggiornaFoto(el.id)
// .then(() => {
// mutexFoto = false;
// setSpinnerVisibile(false);
// setReload(false);
// })
// .catch((err) => {
// mutexFoto = false;
// alert("Loading file cancelled");
// //tolgo overlay caricamneto
// setSpinnerVisibile(false);
// //annullo tutti i caricamenti in coda
// i = selectedResult.length;
// });
// } catch (err) {
// //cosi annullo tutti i caricamenti in coda
// i = selectedResult.length;
// errorLoading = true;
// try {
// //elimino da firebase
// //aggiungo cid a firebase
// let emailDOT = route.params.email;
// //replace all '.' from email to 'DOT'
// emailDOT = emailDOT.replace(/\./g, "DOT");
// await deleteDoc(
// doc(
// db,
// "Utenti",
// emailDOT,
// "Photos",
// idFile
// )
// );
// } catch (ert) {}
// controllerFetch = new AbortController();
// web3s = new Web3Storage({
// token: config.Web3StorageToken,
// abortController: controllerFetch,
// });
// console.log(err);
// alert("Loading failed");
// //tolgo overlay caricamneto
// setSpinnerVisibile(false);
// setReload(false);
// }
// }
// if (!errorLoading) alert("All files have been uploaded successfully");
// };
let openImagePickerAsync = async (selectedResult) => {
//alert per scelta upload files pubblici o privati
// let response = confirm(
// "Do you want upload private (encrypted) or public (not encrypted) files? ('OK' for private, 'Cancel' for public)"
// );
let response = false;
//per alert conferma caricamento tutti i file
let errorLoading = false;
for (let i = 0; i < 1; i++) {
//metto rotellina
setReload(true);
//metto overlay caricamneto
setSpinnerVisibile(true);
//per segnare durante il caricamento quale file si sta caricando
setNumFile({ current: i + 1, total: 100 });
//se è privato lo cifro altrimenti non lo cifro
let filebuffer, filebuffer1, filebuffer2, filebuffer3, filebuffer4;
if (response) {
let enc = new TextEncoder();
//allungo la password inserendo k perchè deve essere almeno essere lunga 16 per generare la chiave
let passwordKey = route.params.password;
while (passwordKey.length < 16) passwordKey += "k";
//genero key con la password
let key = await window.crypto.subtle.importKey(
"raw",
enc.encode(passwordKey),
"AES-GCM",
false,
["encrypt", "decrypt"]
);
//cifro il file
filebuffer = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv: enc.encode(passwordKey) },
key,
await selectedResult.output[i].arrayBuffer()
);
} else {
filebuffer = await selectedResult.output[i].arrayBuffer();
console.log(filebuffer);
//filebuffer = await selectedResult.file.arrayBuffer();
}
//levo rotellina
setReload(false);
//resetto la progress bar
setProgressValue({ value: 0, total: 100 });
//id file per il catch
let idFile;
try {
/*let json;
if ((selectedResult[i].size / 1000000).toFixed(2) < 100) {
json = await axios.request({
url: "https://api.web3.storage/upload",
method: "POST",
signal: controllerFetch.signal,
headers: {
Authorization: "Bearer " + config.Web3StorageToken,
},
data: cifrato,
onUploadProgress: (prog) => {
setProgressValue({ value: prog.loaded, total: prog.total });
},
});
} else {
/* let BlobCifrato = new Blob([cifrato]);
const blockstore = new Blockstore();
const { root: cid } = await pack({
input: [{ path: "blob", content: BlobCifrato.stream() }],
blockstore: blockstore,
wrapWithDirectory: false,
});
const car = new BlockstoreCarReader(1, [cid], blockstore);
const targetSize = 1024 * 1024 * 10;
const splitter =
car instanceof Blob
? await TreewalkCarSplitter.fromBlob(car, targetSize)
: new TreewalkCarSplitter(car, targetSize);
//li uso per la barra di caricamento
let counterCars = 0;
for await (const cid of splitter.cars()) {
counterCars++;
}
let caricati = 0;
const upload = transform(3, async function (car) {
const carParts = [];
for await (const part of car) {
carParts.push(part);
}
const carFile = new Blob(carParts, { type: "application/car" });
const response = await axios.request({
onUploadProgress: (event) => {
setProgressValue({
value: event.loaded,
total: event.total,
});
},
url: /*"https://api.nft.storage/upload"*/
/* "https://api.web3.storage/car",
method: "POST",
signal: controllerFetch.signal,
headers: {
"content-Type": "application/car",
Authorization:*/
/*"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDgyNTY0MzFEQUYwMjU4MEFENTU5NDU2NDc0OURhQWJCZTY5NWUzRjkiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY0Mjg3NjE3NTM0OCwibmFtZSI6ImRzdG9yYWdlIn0.TeG3_YYxhZeWtzpPPNxoietTB0yezr_Pqvq30yjao5w",*/
/* "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDg3RTZiZDFhYTUyOUNmYWRmOURhMGY0NTNiMEE4ZDlGRDM3MjM2ZUIiLCJpc3MiOiJ3ZWIzLXN0b3JhZ2UiLCJpYXQiOjE2NDU0NTQ1NTcyNjUsIm5hbWUiOiJEUGhvdG8ifQ.WM4zuZ9UuGwODetDm37xMmpPLkCXXai-wAxw9Opf7Yk",
},
data: carFile,
});
return response.data.value.cid;
});
let root;
for await (const cid of upload(splitter.cars())) {
//aggiorno progresso caricamento
caricati = caricati + 1;
setProgressValue({ value: caricati, total: counterCars });
root = cid;
}
json = cid.toString();*/
/* let BlobCifrato = new Blob([cifrato]);
const blockstore = new Blockstore();
const { root: cid, out: iterable } = await pack({
input: [{ path: "blob", content: BlobCifrato.stream() }],
blockstore: blockstore,
wrapWithDirectory: false,
});
const car = await CarReader.fromIterable(iterable);
const targetSize = 100000000;
const splitter = new TreewalkCarSplitter(car, targetSize);
//li uso per la barra di caricamento
let counterCars = Math.floor(BlobCifrato.size / targetSize);
let caricati = 0;
console.log(counterCars);
const upload = transform(3, async function (smallCar) {
const carParts = [];
for await (const part of smallCar) {
carParts.push(part);
}
const carFile = new Blob(carParts, { type: "application/car" });
const response = await axios.request({
url: "https://api.web3.storage/car",
method: "POST",
signal: controllerFetch.signal,
headers: {
"content-Type": "application/car",
Authorization: "Bearer " + config.Web3StorageToken,
},
data: carFile,
});
});
for await (const cid of upload(splitter.cars())) {
//aggiorno progresso caricamento
caricati = caricati + 1;
setProgressValue({ value: caricati, total: counterCars });
}
json = cid.toString();
}*/
//carico file su web3.storage
let caricato = 0;
const file = new File([filebuffer], "file");
console.log(file);
const json = await web3s.put([file], {
wrapWithDirectory: false,
onStoredChunk: (size) => {
//aggiorno lo stato del caricamento
caricato = Math.floor(caricato + size);
if (caricato > file.size)
setProgressValue({ value: file.size, total: file.size });
else setProgressValue({ value: caricato, total: file.size });
},
controllerFetch,
});
//aggiungo cid a firebase
let emailDOT = route.params.email;
//replace all '.' from email to 'DOT'
emailDOT = emailDOT.replace(/\./g, "DOT");
let el = await addDoc(
collection(
db,
"Utenti",
emailDOT,
"Photos"
),
{
cid:
/*cid.ipnft*/ json.data == undefined
? json
: json.data /*.value*/.cid,
data: Date.now(),
//poner el output[i]
name: selectedResult.output[i].name,
type:
selectedResult.output[i].name.substring(
selectedResult.output[i].name.lastIndexOf(".") + 1
) == "rar" ||
selectedResult.output[i].name.substring(
selectedResult.output[i].name.lastIndexOf(".") + 1
) == "zip"
? "application/zip"
: selectedResult.output[i].type,
size: selectedResult.output[i].size,
dir: stackDir,
notPrivate: !response,
}
);
idFile = el.id;
await aggiornaFoto(el.id)
.then(() => {
mutexFoto = false;
setSpinnerVisibile(false);
setReload(false);
})
.catch((err) => {
mutexFoto = false;
alert("Loading file cancelled");
//tolgo overlay caricamneto
setSpinnerVisibile(false);
//annullo tutti i caricamenti in coda
i = selectedResult.length;
});
} catch (err) {
//cosi annullo tutti i caricamenti in coda
i = selectedResult.length;
errorLoading = true;
try {
//elimino da firebase
//aggiungo cid a firebase
let emailDOT = route.params.email;
//replace all '.' from email to 'DOT'
emailDOT = emailDOT.replace(/\./g, "DOT");
await deleteDoc(
doc(
db,
"Utenti",
emailDOT,
"Photos",
idFile
)
);
} catch (ert) {}
controllerFetch = new AbortController();
web3s = new Web3Storage({
token: config.Web3StorageToken,
abortController: controllerFetch,
});
console.log(err);
alert("Loading failed");
//tolgo overlay caricamneto
setSpinnerVisibile(false);
setReload(false);
}
}
if (!errorLoading) alert("All files have been uploaded successfully");
};
let createFolder = async () => {
let nameFolder = window.prompt("Enter the name of the folder");
if (nameFolder != null && nameFolder != "") {
//aggiungo cid a firebase
let emailDOT = route.params.email;
//replace all '.' from email to 'DOT'
emailDOT = emailDOT.replace(/\./g, "DOT");
await addDoc(
collection(
db,
"Utenti",
emailDOT,
"folders"
),
{
name: nameFolder,
data: Date.now(),
dir: stackDir,
}
);
setSpinnerVisibile(true);
setReload(true);
await aggiornaFoto().then(() => {
mutexFoto = false;
setSpinnerVisibile(false);
setReload(false);
});
}
};
//menu al click della foto
let menuSelection = async (value) => {
//copy link per file pubblici
if (value == 5) {
copy("https://" + elementoSelezionato.cid + ".ipfs.dweb.link");
alert("Link copied to clipboard");
}
//info file
if (value == 4) {
navigation.push("FileInfo", {
email: route.params.email,
name: elementoSelezionato.name,
size: elementoSelezionato.size,
data: elementoSelezionato.data,
cid: elementoSelezionato.cid,
});
}
//Elimina foto
if (value == 2) {
//elimino da firebase
//aggiungo cid a firebase
let emailDOT = route.params.email;
//replace all '.' from email to 'DOT'
emailDOT = emailDOT.replace(/\./g, "DOT");
await deleteDoc(
doc(
db,
"Utenti",
emailDOT,
"Photos",
elementoSelezionato.id
)
);
//elimino dallo state
let newImages = Object.assign([], images); //si fa così per creare una copia dell'array nello stato
newImages.splice(
newImages.indexOf(
newImages.filter((obj) => obj.id === elementoSelezionato.id)[0]
),
1
);
setImages(newImages);
}
//Download foto
if (value == 1) {
if (!elementoSelezionato.notPrivate) {
let win;
if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent))
win = window;
else win = window.open();
win.window.document.write(
"<html> <head> <style> html, body { height: 100%; width: 100%; } .container { align-items: center; display: flex; justify-content: center; height: 100%; width: 100%; } </style> </head> <body style='background-color: #191919; overflow: hidden'> <div class='container'> <img src='https://darchive5.web.app/static/media/logo.a7ce87a3.png' style='width: 250px' /> <div class='content'> <p id='textDownload' style='color: white; font-family: Arial, Helvetica, sans-serif' > Download of " +
elementoSelezionato.name +
" in progress... </p> </div> </div> </body></html>"
);
//se chiudo la finestra eseguo abort del download
win.window.addEventListener("beforeunload", (ev) => {
controllerFetchDownload.abort();
controllerFetchDownload = new AbortController();
});
axios
.get(
/* "https://ipfs.io/ipfs/" + elementoSelezionato.cid */ "https://" +
elementoSelezionato.cid +
".ipfs.dweb.link",
{
signal: controllerFetchDownload.signal,
responseType: "arraybuffer",
onDownloadProgress: (event) => {
win.document.getElementById("textDownload").innerHTML =
"Download of " +
elementoSelezionato.name +
" in progress..." +
" " +
event.loaded +
"/" +
event.total;
},
}
)
.then(async (arrayBuffer) => {
let enc = new TextEncoder();
//allungo la password inserendo k perchè deve essere almeno essere lunga 16 per generare la chiave
let passwordKey = route.params.password;
while (passwordKey.length < 16) passwordKey += "k";
//genero key con la password
let key = await window.crypto.subtle.importKey(
"raw",
enc.encode(passwordKey),
"AES-GCM",
false,
["encrypt", "decrypt"]
);
//decifro il file
let decifrato = await window.crypto.subtle.decrypt(
{ name: "AES-GCM", iv: enc.encode(passwordKey) },
key,
arrayBuffer.data
);
//se è un immagine o un video lo faccio visualizzare
//altrimenti lo scarico dandogli il nome del file giusto
if (
elementoSelezionato.type.includes("image") ||
elementoSelezionato.type.includes("video")
) {
let blob = new Blob([decifrato], {
type: elementoSelezionato.type,
});
let url = URL.createObjectURL(blob);
win.location.href = url;