ente/src/services/collectionService.ts

502 lines
15 KiB
TypeScript
Raw Normal View History

2021-05-29 06:27:52 +00:00
import {getEndpoint} from 'utils/common/apiUtil';
import {getData, LS_KEYS} from 'utils/storage/localStorage';
2021-03-12 06:58:27 +00:00
import localForage from 'utils/storage/localForage';
2021-05-29 06:27:52 +00:00
import {getActualKey, getToken} from 'utils/common/key';
2021-04-03 04:36:15 +00:00
import CryptoWorker from 'utils/crypto';
2021-05-29 06:27:52 +00:00
import {SetDialogMessage} from 'components/MessageDialog';
import constants from 'utils/strings/constants';
2021-05-29 06:27:52 +00:00
import {getPublicKey, User} from './userService';
import {B64EncryptionResult} from './uploadService';
import HTTPService from './HTTPService';
import {File} from './fileService';
const ENDPOINT = getEndpoint();
2021-04-24 07:09:37 +00:00
export enum CollectionType {
folder = 'folder',
favorites = 'favorites',
album = 'album',
2021-01-13 12:43:46 +00:00
}
const COLLECTION_UPDATION_TIME = 'collection-updation-time';
const FAV_COLLECTION = 'fav-collection';
const COLLECTIONS = 'collections';
export interface Collection {
2021-02-08 07:33:46 +00:00
id: number;
owner: User;
key?: string;
name?: string;
encryptedName?: string;
nameDecryptionNonce?: string;
type: CollectionType;
attributes: collectionAttributes;
sharees: User[];
2021-01-13 12:43:46 +00:00
updationTime: number;
encryptedKey: string;
keyDecryptionNonce: string;
isDeleted: boolean;
}
interface collectionAttributes {
encryptedPath?: string;
pathDecryptionNonce?: string;
}
2021-01-13 12:43:46 +00:00
export interface CollectionAndItsLatestFile {
collection: Collection;
file: File;
}
const getCollectionWithSecrets = async (
collection: Collection,
2021-05-29 06:27:52 +00:00
masterKey: string,
) => {
const worker = await new CryptoWorker();
const userID = getData(LS_KEYS.USER).id;
let decryptedKey: string;
2021-05-29 06:27:52 +00:00
if (collection.owner.id === userID) {
decryptedKey = await worker.decryptB64(
collection.encryptedKey,
collection.keyDecryptionNonce,
2021-05-29 06:27:52 +00:00
masterKey,
);
} else {
const keyAttributes = getData(LS_KEYS.KEY_ATTRIBUTES);
const secretKey = await worker.decryptB64(
keyAttributes.encryptedSecretKey,
keyAttributes.secretKeyDecryptionNonce,
2021-05-29 06:27:52 +00:00
masterKey,
);
decryptedKey = await worker.boxSealOpen(
collection.encryptedKey,
keyAttributes.publicKey,
2021-05-29 06:27:52 +00:00
secretKey,
);
}
2021-05-29 06:27:52 +00:00
collection.name = collection.name ||
2021-02-16 11:43:21 +00:00
(await worker.decryptToUTF8(
collection.encryptedName,
collection.nameDecryptionNonce,
2021-05-29 06:27:52 +00:00
decryptedKey,
));
return {
...collection,
key: decryptedKey,
};
};
const getCollections = async (
token: string,
sinceTime: number,
2021-05-29 06:27:52 +00:00
key: string,
): Promise<Collection[]> => {
2021-01-25 07:05:45 +00:00
try {
const resp = await HTTPService.get(
`${ENDPOINT}/collections`,
{
2021-05-29 06:27:52 +00:00
sinceTime,
},
2021-05-29 06:27:52 +00:00
{'X-Auth-Token': token},
);
const promises: Promise<Collection>[] = resp.data.collections.map(
async (collection: Collection) => {
if (collection.isDeleted) {
return collection;
}
let collectionWithSecrets = collection;
try {
collectionWithSecrets = await getCollectionWithSecrets(
collection,
2021-05-29 06:27:52 +00:00
key,
);
2021-05-29 06:27:52 +00:00
return collectionWithSecrets;
} catch (e) {
console.error(
`decryption failed for collection with id=${collection.id}`,
2021-05-29 06:27:52 +00:00
e,
);
}
2021-05-29 06:27:52 +00:00
},
);
return await Promise.all(promises);
} catch (e) {
2021-03-29 09:35:05 +00:00
console.error('getCollections failed- ', e);
2021-05-24 13:11:08 +00:00
throw e;
2021-01-25 07:05:45 +00:00
}
};
export const getLocalCollections = async (): Promise<Collection[]> => {
2021-05-29 06:27:52 +00:00
const collections: Collection[] = (await localForage.getItem(COLLECTIONS)) ?? [];
return collections;
};
2021-05-29 06:27:52 +00:00
export const getCollectionUpdationTime = async (): Promise<number> => (await localForage.getItem<number>(COLLECTION_UPDATION_TIME)) ?? 0;
export const syncCollections = async () => {
const localCollections = await getLocalCollections();
const lastCollectionUpdationTime = await getCollectionUpdationTime();
2021-04-29 08:58:34 +00:00
const token = getToken();
2021-05-29 06:27:52 +00:00
const key = await getActualKey();
const updatedCollections = (await getCollections(token, lastCollectionUpdationTime, key)) ?? [];
if (updatedCollections.length === 0) {
return localCollections;
}
const allCollectionsInstances = [
...localCollections,
...updatedCollections,
];
2021-05-29 06:27:52 +00:00
const latestCollectionsInstances = new Map<number, Collection>();
allCollectionsInstances.forEach((collection) => {
if (
!latestCollectionsInstances.has(collection.id) ||
latestCollectionsInstances.get(collection.id).updationTime <
collection.updationTime
) {
latestCollectionsInstances.set(collection.id, collection);
}
});
2021-05-29 06:27:52 +00:00
const collections: Collection[] = [];
let updationTime = await localForage.getItem<number>(
COLLECTION_UPDATION_TIME,
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const [_, collection] of latestCollectionsInstances) {
if (!collection.isDeleted) {
2021-02-06 07:51:49 +00:00
collections.push(collection);
updationTime = Math.max(updationTime, collection.updationTime);
2021-02-08 07:33:46 +00:00
}
}
2021-02-16 12:41:27 +00:00
collections.sort((a, b) => b.updationTime - a.updationTime);
2021-03-24 11:01:57 +00:00
collections.sort((a, b) => (b.type === CollectionType.favorites ? 1 : 0));
await localForage.setItem(COLLECTION_UPDATION_TIME, updationTime);
await localForage.setItem(COLLECTIONS, collections);
return collections;
};
2021-01-13 12:43:46 +00:00
export const getCollectionsAndTheirLatestFile = (
collections: Collection[],
2021-05-29 06:27:52 +00:00
files: File[],
): CollectionAndItsLatestFile[] => {
const latestFile = new Map<number, File>();
files.forEach((file) => {
if (!latestFile.has(file.collectionID)) {
latestFile.set(file.collectionID, file);
}
});
2021-05-29 06:27:52 +00:00
const collectionsAndTheirLatestFile: CollectionAndItsLatestFile[] = [];
const userID = getData(LS_KEYS.USER)?.id;
for (const collection of collections) {
if (
2021-05-29 06:27:52 +00:00
collection.owner.id !== userID ||
collection.type === CollectionType.favorites
) {
continue;
}
collectionsAndTheirLatestFile.push({
collection,
file: latestFile.get(collection.id),
});
}
return collectionsAndTheirLatestFile;
};
export const getFavItemIds = async (files: File[]): Promise<Set<number>> => {
2021-05-29 06:27:52 +00:00
const favCollection = await getFavCollection();
if (!favCollection) return new Set();
2021-01-20 12:05:04 +00:00
return new Set(
files
2021-02-09 05:07:46 +00:00
.filter((file) => file.collectionID === favCollection.id)
2021-05-29 06:27:52 +00:00
.map((file): number => file.id),
);
};
2021-01-20 12:05:04 +00:00
2021-05-29 06:27:52 +00:00
export const createAlbum = async (albumName: string) => createCollection(albumName, CollectionType.album);
2021-01-15 11:11:06 +00:00
export const createCollection = async (
collectionName: string,
2021-05-29 06:27:52 +00:00
type: CollectionType,
): Promise<Collection> => {
try {
const existingCollections = await getLocalCollections();
2021-05-29 06:27:52 +00:00
for (const collection of existingCollections) {
if (collection.name === collectionName) {
return collection;
}
}
const worker = await new CryptoWorker();
const encryptionKey = await getActualKey();
const token = getToken();
const collectionKey: string = await worker.generateEncryptionKey();
const {
encryptedData: encryptedKey,
nonce: keyDecryptionNonce,
}: B64EncryptionResult = await worker.encryptToB64(
collectionKey,
2021-05-29 06:27:52 +00:00
encryptionKey,
);
const {
encryptedData: encryptedName,
nonce: nameDecryptionNonce,
}: B64EncryptionResult = await worker.encryptUTF8(
collectionName,
2021-05-29 06:27:52 +00:00
collectionKey,
);
const newCollection: Collection = {
id: null,
owner: null,
encryptedKey,
keyDecryptionNonce,
encryptedName,
nameDecryptionNonce,
type,
attributes: {},
sharees: null,
updationTime: null,
isDeleted: false,
};
let createdCollection: Collection = await postCollection(
newCollection,
2021-05-29 06:27:52 +00:00
token,
);
createdCollection = await getCollectionWithSecrets(
createdCollection,
2021-05-29 06:27:52 +00:00
encryptionKey,
);
return createdCollection;
} catch (e) {
2021-05-07 03:31:42 +00:00
console.error('create collection failed', e);
throw e;
}
};
2021-01-13 12:43:46 +00:00
const postCollection = async (
collectionData: Collection,
2021-05-29 06:27:52 +00:00
token: string,
): Promise<Collection> => {
2021-01-25 07:05:45 +00:00
try {
const response = await HTTPService.post(
`${ENDPOINT}/collections`,
collectionData,
null,
2021-05-29 06:27:52 +00:00
{'X-Auth-Token': token},
);
2021-01-25 07:05:45 +00:00
return response.data.collection;
} catch (e) {
2021-05-07 03:31:42 +00:00
console.error('post Collection failed ', e);
2021-01-25 07:05:45 +00:00
}
};
2021-01-15 11:11:06 +00:00
export const addToFavorites = async (file: File) => {
2021-04-24 07:09:37 +00:00
let favCollection = await getFavCollection();
2021-01-15 11:11:06 +00:00
if (!favCollection) {
favCollection = await createCollection(
'Favorites',
2021-05-29 06:27:52 +00:00
CollectionType.favorites,
);
await localForage.setItem(FAV_COLLECTION, favCollection);
2021-01-15 11:11:06 +00:00
}
2021-02-09 06:18:46 +00:00
await addToCollection(favCollection, [file]);
};
2021-01-15 11:11:06 +00:00
export const removeFromFavorites = async (file: File) => {
2021-05-29 06:27:52 +00:00
const favCollection = await getFavCollection();
await removeFromCollection(favCollection, [file]);
};
2021-01-20 13:04:27 +00:00
2021-04-27 11:59:10 +00:00
export const addToCollection = async (
collection: Collection,
2021-05-29 06:27:52 +00:00
files: File[],
2021-04-27 11:59:10 +00:00
) => {
2021-01-25 07:05:45 +00:00
try {
2021-05-29 06:27:52 +00:00
const params = {};
2021-01-25 07:05:45 +00:00
const worker = await new CryptoWorker();
const token = getToken();
2021-05-29 06:31:00 +00:00
params['collectionID'] = collection.id;
await Promise.all(
files.map(async (file) => {
2021-02-09 05:07:46 +00:00
file.collectionID = collection.id;
2021-05-29 06:27:52 +00:00
const newEncryptedKey: B64EncryptionResult = await worker.encryptToB64(file.key, collection.key);
file.encryptedKey = newEncryptedKey.encryptedData;
file.keyDecryptionNonce = newEncryptedKey.nonce;
2021-05-29 06:31:00 +00:00
if (params['files'] === undefined) {
params['files'] = [];
}
2021-05-29 06:31:00 +00:00
params['files'].push({
id: file.id,
encryptedKey: file.encryptedKey,
keyDecryptionNonce: file.keyDecryptionNonce,
});
return file;
2021-05-29 06:27:52 +00:00
}),
);
await HTTPService.post(
`${ENDPOINT}/collections/add-files`,
params,
null,
2021-05-29 06:27:52 +00:00
{'X-Auth-Token': token},
);
2021-01-25 07:05:45 +00:00
} catch (e) {
console.error('Add to collection Failed ', e);
2021-01-25 07:05:45 +00:00
}
};
const removeFromCollection = async (collection: Collection, files: File[]) => {
2021-01-25 07:05:45 +00:00
try {
2021-05-29 06:27:52 +00:00
const params = {};
2021-01-25 07:05:45 +00:00
const token = getToken();
2021-05-29 06:31:00 +00:00
params['collectionID'] = collection.id;
await Promise.all(
files.map(async (file) => {
2021-05-29 06:31:00 +00:00
if (params['fileIDs'] === undefined) {
params['fileIDs'] = [];
}
2021-05-29 06:31:00 +00:00
params['fileIDs'].push(file.id);
2021-05-29 06:27:52 +00:00
}),
);
await HTTPService.post(
`${ENDPOINT}/collections/remove-files`,
params,
null,
2021-05-29 06:27:52 +00:00
{'X-Auth-Token': token},
);
2021-01-25 07:05:45 +00:00
} catch (e) {
console.error('remove from collection failed ', e);
2021-01-25 07:05:45 +00:00
}
};
2021-01-20 13:04:27 +00:00
2021-04-24 07:09:37 +00:00
export const deleteCollection = async (
collectionID: number,
2021-04-28 09:56:57 +00:00
syncWithRemote: () => Promise<void>,
redirectToAll: () => void,
2021-05-29 06:27:52 +00:00
setDialogMessage: SetDialogMessage,
2021-04-24 07:09:37 +00:00
) => {
try {
const token = getToken();
await HTTPService.delete(
`${ENDPOINT}/collections/${collectionID}`,
null,
null,
2021-05-29 06:27:52 +00:00
{'X-Auth-Token': token},
2021-04-24 07:09:37 +00:00
);
2021-04-28 09:56:57 +00:00
await syncWithRemote();
redirectToAll();
2021-04-24 07:09:37 +00:00
} catch (e) {
console.error('delete collection failed ', e);
setDialogMessage({
title: constants.ERROR,
content: constants.DELETE_COLLECTION_FAILED,
2021-05-29 06:27:52 +00:00
close: {variant: 'danger'},
});
2021-02-09 05:07:46 +00:00
}
2021-04-24 07:09:37 +00:00
};
export const renameCollection = async (
collection: Collection,
2021-05-29 06:27:52 +00:00
newCollectionName: string,
) => {
const token = getToken();
const worker = await new CryptoWorker();
const {
encryptedData: encryptedName,
nonce: nameDecryptionNonce,
}: B64EncryptionResult = await worker.encryptUTF8(
newCollectionName,
2021-05-29 06:27:52 +00:00
collection.key,
);
const collectionRenameRequest = {
collectionID: collection.id,
encryptedName,
nameDecryptionNonce,
};
await HTTPService.post(
`${ENDPOINT}/collections/rename`,
collectionRenameRequest,
null,
{
'X-Auth-Token': token,
2021-05-29 06:27:52 +00:00
},
);
};
export const shareCollection = async (
collection: Collection,
2021-05-29 06:27:52 +00:00
withUserEmail: string,
) => {
try {
2021-04-28 08:00:15 +00:00
const worker = await new CryptoWorker();
const token = getToken();
2021-04-28 08:00:15 +00:00
const publicKey: string = await getPublicKey(withUserEmail);
2021-04-28 09:11:25 +00:00
const encryptedKey: string = await worker.boxSeal(
2021-04-28 08:00:15 +00:00
collection.key,
2021-05-29 06:27:52 +00:00
publicKey,
2021-04-28 08:00:15 +00:00
);
const shareCollectionRequest = {
collectionID: collection.id,
email: withUserEmail,
2021-05-29 06:27:52 +00:00
encryptedKey,
};
await HTTPService.post(
`${ENDPOINT}/collections/share`,
shareCollectionRequest,
null,
{
'X-Auth-Token': token,
2021-05-29 06:27:52 +00:00
},
);
} catch (e) {
console.error('share collection failed ', e);
throw e;
}
};
export const unshareCollection = async (
collection: Collection,
2021-05-29 06:27:52 +00:00
withUserEmail: string,
) => {
try {
const token = getToken();
const shareCollectionRequest = {
collectionID: collection.id,
email: withUserEmail,
};
await HTTPService.post(
`${ENDPOINT}/collections/unshare`,
shareCollectionRequest,
null,
{
'X-Auth-Token': token,
2021-05-29 06:27:52 +00:00
},
);
} catch (e) {
console.error('unshare collection failed ', e);
throw e;
}
};
2021-04-24 07:09:37 +00:00
export const getFavCollection = async () => {
const collections = await getLocalCollections();
2021-05-29 06:27:52 +00:00
for (const collection of collections) {
if (collection.type === CollectionType.favorites) {
2021-04-24 07:09:37 +00:00
return collection;
}
2021-02-09 05:07:46 +00:00
}
2021-04-24 07:09:37 +00:00
return null;
};
2021-03-15 17:30:49 +00:00
export const getNonEmptyCollections = (
collections: Collection[],
2021-05-29 06:27:52 +00:00
files: File[],
2021-03-15 17:30:49 +00:00
) => {
const nonEmptyCollectionsIds = new Set<number>();
2021-05-29 06:27:52 +00:00
for (const file of files) {
2021-03-15 17:30:49 +00:00
nonEmptyCollectionsIds.add(file.collectionID);
}
2021-05-29 06:27:52 +00:00
return collections.filter((collection) => nonEmptyCollectionsIds.has(collection.id));
2021-03-15 17:30:49 +00:00
};