Преглед изворни кода

refactored getfiles and moved getCollectionLatestFile to collection service

Abhinav-grd пре 4 година
родитељ
комит
95fc146657

+ 1 - 1
src/pages/gallery/components/PreviewCard.tsx

@@ -57,7 +57,7 @@ export default function PreviewCard(props: IProps) {
     }, [data]);
     }, [data]);
 
 
     const handleClick = () => {
     const handleClick = () => {
-        if (data.msrc || imgSrc) {
+        if (data?.msrc || imgSrc) {
             onClick();
             onClick();
         }
         }
     }
     }

+ 2 - 7
src/pages/gallery/index.tsx

@@ -4,10 +4,8 @@ import Spinner from 'react-bootstrap/Spinner';
 import { getKey, SESSION_KEYS } from 'utils/storage/sessionStorage';
 import { getKey, SESSION_KEYS } from 'utils/storage/sessionStorage';
 import {
 import {
     file,
     file,
-    getCollectionLatestFile,
     getFile,
     getFile,
     getPreview,
     getPreview,
-    collectionLatestFile,
     fetchData,
     fetchData,
 } from 'services/fileService';
 } from 'services/fileService';
 import { getData, LS_KEYS } from 'utils/storage/localStorage';
 import { getData, LS_KEYS } from 'utils/storage/localStorage';
@@ -21,7 +19,7 @@ import { VariableSizeList as List } from 'react-window';
 import Collections from './components/Collections';
 import Collections from './components/Collections';
 import SadFace from 'components/SadFace';
 import SadFace from 'components/SadFace';
 import Upload from './components/Upload';
 import Upload from './components/Upload';
-import { collection, fetchCollections } from 'services/collectionService';
+import { collection, fetchCollections, collectionLatestFile, getCollectionLatestFile } from 'services/collectionService';
 
 
 enum ITEM_TYPE {
 enum ITEM_TYPE {
     TIME = 'TIME',
     TIME = 'TIME',
@@ -125,10 +123,7 @@ export default function Gallery(props) {
             setLoading(false);
             setLoading(false);
             setCollections(collections);
             setCollections(collections);
             setData(data);
             setData(data);
-            const collectionLatestFile = await getCollectionLatestFile(
-                collections,
-                data
-            );
+            const collectionLatestFile = await getCollectionLatestFile(collections, token);
             setCollectionLatestFile(collectionLatestFile);
             setCollectionLatestFile(collectionLatestFile);
         };
         };
         main();
         main();

+ 25 - 1
src/services/collectionService.ts

@@ -1,6 +1,8 @@
 import { getEndpoint } from "utils/common/apiUtil";
 import { getEndpoint } from "utils/common/apiUtil";
 import { getData, LS_KEYS } from "utils/storage/localStorage";
 import { getData, LS_KEYS } from "utils/storage/localStorage";
-import { user } from "./fileService";
+import { file, user, getFiles } from "./fileService";
+import localForage from 'localforage';
+
 import HTTPService from "./HTTPService";
 import HTTPService from "./HTTPService";
 import * as Comlink from 'comlink';
 import * as Comlink from 'comlink';
 import { keyEncryptionResult } from "./uploadService";
 import { keyEncryptionResult } from "./uploadService";
@@ -37,6 +39,12 @@ interface collectionAttributes {
     pathDecryptionNonce?: string
     pathDecryptionNonce?: string
 };
 };
 
 
+export interface collectionLatestFile {
+    collection: collection
+    file: file;
+}
+
+
 const getCollectionKey = async (collection: collection, masterKey: string) => {
 const getCollectionKey = async (collection: collection, masterKey: string) => {
     const worker = await new CryptoWorker();
     const worker = await new CryptoWorker();
     const userID = getData(LS_KEYS.USER).id;
     const userID = getData(LS_KEYS.USER).id;
@@ -87,6 +95,22 @@ export const fetchCollections = async (token: string, key: string) => {
     return getCollections(token, '0', key);
     return getCollections(token, '0', key);
 };
 };
 
 
+export const getCollectionLatestFile = async (
+    collections: collection[],
+    token
+): Promise<collectionLatestFile[]> => {
+    return Promise.all(
+        collections.map(async collection => {
+            const sinceTime: string = (Number(await localForage.getItem<string>(`${collection.id}-time`)) - 1).toString();
+            const file: file[] = await getFiles([collection], sinceTime, "100", token);
+            console.log(file);
+            return {
+                file: file[0],
+                collection,
+            }
+        }))
+};
+
 export const createAlbum = async (albumName: string, key: string, token: string) => {
 export const createAlbum = async (albumName: string, key: string, token: string) => {
     const worker = await new CryptoWorker();
     const worker = await new CryptoWorker();
     const collectionKey: Uint8Array = await worker.generateMasterKey();
     const collectionKey: Uint8Array = await worker.generateMasterKey();

+ 24 - 51
src/services/fileService.ts

@@ -48,17 +48,11 @@ export interface file {
     dataIndex: number;
     dataIndex: number;
 }
 }
 
 
-export interface collectionLatestFile {
-    collection: collection
-    file: file;
-}
 
 
 
 
 export const fetchData = async (token, collections) => {
 export const fetchData = async (token, collections) => {
-    const resp = await getFiles(
-        '0',
+    const resp = await fetchFiles(
         token,
         token,
-        '100',
         collections
         collections
     );
     );
 
 
@@ -71,14 +65,25 @@ export const fetchData = async (token, collections) => {
     );
     );
 }
 }
 
 
-export const getFiles = async (
-    sinceTime: string,
+export const fetchFiles = async (
     token: string,
     token: string,
-    limit: string,
     collections: collection[]
     collections: collection[]
 ) => {
 ) => {
-    const worker = await new CryptoWorker();
     let files: Array<file> = (await localForage.getItem<file[]>('files')) || [];
     let files: Array<file> = (await localForage.getItem<file[]>('files')) || [];
+    const fetchedFiles = await getFiles(collections, null, "100", token);
+
+    console.log(fetchedFiles);
+    files.push(...fetchedFiles);
+    files = files.sort(
+        (a, b) => b.metadata.creationTime - a.metadata.creationTime
+    );
+    await localForage.setItem('files', files);
+    return files;
+};
+
+export const getFiles = async (collections: collection[], sinceTime: string, limit: string, token: string): Promise<file[]> => {
+    const worker = await new CryptoWorker();
+
     for (const index in collections) {
     for (const index in collections) {
         const collection = collections[index];
         const collection = collections[index];
         if (collection.isDeleted) {
         if (collection.isDeleted) {
@@ -86,8 +91,8 @@ export const getFiles = async (
             continue;
             continue;
         }
         }
         let time =
         let time =
-            (await localForage.getItem<string>(`${collection.id}-time`)) || sinceTime;
-        let resp;
+            sinceTime || (await localForage.getItem<string>(`${collection.id}-time`)) || "0";
+        let resp, promises: Promise<file>[] = [];
         do {
         do {
             resp = await HTTPService.get(`${ENDPOINT}/collections/diff`, {
             resp = await HTTPService.get(`${ENDPOINT}/collections/diff`, {
                 collectionID: collection.id,
                 collectionID: collection.id,
@@ -95,9 +100,8 @@ export const getFiles = async (
                 token,
                 token,
                 limit,
                 limit,
             });
             });
-            const promises: Promise<file>[] = resp.data.diff.filter(file => !file.isDeleted).map(
+            promises.push(...resp.data.diff.filter(file => !file.isDeleted).map(
                 async (file: file) => {
                 async (file: file) => {
-                    console.log(file);
                     file.key = await worker.decryptB64(
                     file.key = await worker.decryptB64(
                         file.encryptedKey,
                         file.encryptedKey,
                         file.keyDecryptionNonce,
                         file.keyDecryptionNonce,
@@ -106,21 +110,17 @@ export const getFiles = async (
                     file.metadata = await worker.decryptMetadata(file);
                     file.metadata = await worker.decryptMetadata(file);
                     return file;
                     return file;
                 }
                 }
-            );
-            files.push(...(await Promise.all(promises)));
-            files = files.sort(
-                (a, b) => b.metadata.creationTime - a.metadata.creationTime
-            );
+            ));
+
             if (resp.data.diff.length) {
             if (resp.data.diff.length) {
                 time = resp.data.diff.slice(-1)[0].updationTime.toString();
                 time = resp.data.diff.slice(-1)[0].updationTime.toString();
             }
             }
         } while (resp.data.diff.length);
         } while (resp.data.diff.length);
         await localForage.setItem(`${collection.id}-time`, time);
         await localForage.setItem(`${collection.id}-time`, time);
-    }
-    await localForage.setItem('files', files);
-    return files;
-};
 
 
+        return Promise.all(promises);
+    }
+}
 export const getPreview = async (token: string, file: file) => {
 export const getPreview = async (token: string, file: file) => {
     const cache = await caches.open('thumbs');
     const cache = await caches.open('thumbs');
     const cacheResp: Response = await cache.match(file.id.toString());
     const cacheResp: Response = await cache.match(file.id.toString());
@@ -163,30 +163,3 @@ export const getFile = async (token: string, file: file) => {
     return URL.createObjectURL(new Blob([decrypted]));
     return URL.createObjectURL(new Blob([decrypted]));
 };
 };
 
 
-export const getCollectionLatestFile = async (
-    collections: collection[],
-    data: file[]
-): Promise<collectionLatestFile[]> => {
-    let collectionIdSet = new Set<number>();
-    let collectionMap = new Map<number, collection>();
-    collections.forEach((collection) => {
-        collectionMap.set(Number(collection.id), collection);
-        collectionIdSet.add(Number(collection.id))
-    });
-    return Promise.all(
-        data
-            .filter((item) => {
-                if (collectionIdSet.size !== 0 && collectionIdSet.has(item.collectionID)) {
-                    collectionIdSet.delete(item.collectionID);
-                    return true;
-                }
-                return false;
-            })
-            .map(async (item) => {
-                return {
-                    file: item,
-                    collection: collectionMap.get(item.collectionID),
-                };
-            })
-    );
-};