Skip to content

Commit

Permalink
Remove firebase storage dep from client apps
Browse files Browse the repository at this point in the history
  • Loading branch information
amitsingh-007 committed Feb 3, 2024
1 parent 170a45d commit 8dc011d
Show file tree
Hide file tree
Showing 59 changed files with 288 additions and 263 deletions.
3 changes: 2 additions & 1 deletion apps/extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"lint": "eslint ."
},
"dependencies": {
"@bypass/configs": "workspace:*",
"@bypass/shared": "workspace:*",
"@bypass/trpc": "workspace:*",
"@dnd-kit/core": "6.1.0",
Expand All @@ -34,12 +35,12 @@
"react-easy-crop": "5.0.4",
"react-icons": "5.0.1",
"react-router-dom": "6.21.1",
"wretch": "2.8.0",
"zod": "3.22.4",
"zustand": "4.4.7"
},
"devDependencies": {
"@babel/core": "7.23.7",
"@bypass/configs": "workspace:*",
"@playwright/test": "1.40.1",
"@prefresh/core": "1.5.2",
"@prefresh/webpack": "4.0.0",
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/src/BackgroundScript/bypass/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import { STORAGE_KEYS } from '@bypass/shared';
import { getBypassExecutor, getDecodedBypass } from './bypassUtils';

Expand All @@ -10,7 +10,7 @@ export const bypass = async (tabId: number, url: URL) => {
};

export const syncBypassToStorage = async () => {
const response = await api.firebaseData.bypassGet.query();
const response = await trpcApi.firebaseData.bypassGet.query();
const bypassData = getDecodedBypass(response);
await chrome.storage.local.set({ [STORAGE_KEYS.bypass]: bypassData });
};
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/src/BackgroundScript/redirect/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import { startHistoryWatch } from '@/utils/history';
import { STORAGE_KEYS } from '@bypass/shared';
import { getMappedRedirections } from '@helpers/fetchFromStorage';
Expand All @@ -14,7 +14,7 @@ export const redirect = async (tabId: number, url: URL) => {
};

export const syncRedirectionsToStorage = async () => {
const redirections = await api.firebaseData.redirectionsGet.query();
const redirections = await trpcApi.firebaseData.redirectionsGet.query();
await chrome.storage.local.set({ [STORAGE_KEYS.redirections]: redirections });
const mappedRedirections = mapRedirections(redirections);
await chrome.storage.local.set({
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/src/BackgroundScript/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { IExtensionState } from '@constants/index';
import { getExtensionState } from '@helpers/fetchFromStorage';
import { api } from '../../utils/api';
import { trpcApi } from '../../apis/trpcApi';
import { getIsExtensionActive } from '../../utils/common';

const restrictedProtocols = new Set([
Expand Down Expand Up @@ -55,7 +55,7 @@ export const setExtensionIcon = async ({
};

export const checkForUpdates = async () => {
const { version: latestVersion } = await api.extension.latest.query();
const { version: latestVersion } = await trpcApi.extension.latest.query();
const { version: currentVersion } = chrome.runtime.getManifest();
return latestVersion === currentVersion;
};
7 changes: 4 additions & 3 deletions apps/extension/src/BookmarksPanel/utils/bookmark.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AuthProgress } from '@/HomePopup/utils/authProgress';
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import {
CACHE_BUCKET_KEYS,
getCacheObj,
Expand All @@ -9,7 +9,7 @@ import {
import { getBookmarks } from '@helpers/fetchFromStorage';

export const syncBookmarksToStorage = async () => {
const bookmarks = await api.firebaseData.bookmarksGet.query();
const bookmarks = await trpcApi.firebaseData.bookmarksGet.query();
await chrome.storage.local.set({ [STORAGE_KEYS.bookmarks]: bookmarks });
};

Expand All @@ -22,7 +22,8 @@ export const syncBookmarksFirebaseWithStorage = async () => {
return;
}
console.log('Syncing bookmarks from storage to firebase', bookmarks);
const isSaveSuccess = await api.firebaseData.bookmarksPost.mutate(bookmarks);
const isSaveSuccess =
await trpcApi.firebaseData.bookmarksPost.mutate(bookmarks);
if (isSaveSuccess) {
await chrome.storage.local.remove('hasPendingBookmarks');
} else {
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/src/HomePopup/components/LastVisitedButton.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { syncLastVisitedToStorage } from '@/HomePopup/utils/lastVisited';
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import { getCurrentTab } from '@/utils/tabs';
import { ILastVisited } from '@bypass/shared';
import { getLastVisited } from '@helpers/fetchFromStorage';
Expand Down Expand Up @@ -51,7 +51,7 @@ const LastVisitedButton = memo(function LastVisitedButton() {
const { hostname } = new URL(currentTab.url);
lastVisitedObj[md5(hostname)] = Date.now();
const isSuccess =
await api.firebaseData.lastVisitedPost.mutate(lastVisitedObj);
await trpcApi.firebaseData.lastVisitedPost.mutate(lastVisitedObj);
if (isSuccess) {
await syncLastVisitedToStorage();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import { InputTOTP, STORAGE_KEYS } from '@bypass/shared';
import { getUserProfile } from '@helpers/fetchFromStorage';
import { Center, Modal } from '@mantine/core';
Expand Down Expand Up @@ -34,7 +34,7 @@ const TwoFactorAuthenticate = () => {
if (!user) {
return;
}
const { isVerified } = await api.twoFactorAuth.authenticate.query(totp);
const { isVerified } = await trpcApi.twoFactorAuth.authenticate.query(totp);
if (isVerified) {
user.isTOTPVerified = true;
await chrome.storage.local.set({ [STORAGE_KEYS.userProfile]: user });
Expand Down
4 changes: 2 additions & 2 deletions apps/extension/src/HomePopup/utils/lastVisited.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import { STORAGE_KEYS } from '@bypass/shared';

export const syncLastVisitedToStorage = async () => {
const lastVisited = await api.firebaseData.lastVisitedGet.query();
const lastVisited = await trpcApi.firebaseData.lastVisitedGet.query();
await chrome.storage.local.set({ [STORAGE_KEYS.lastVisited]: lastVisited });
};

Expand Down
4 changes: 2 additions & 2 deletions apps/extension/src/HomePopup/utils/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
resetSettings,
syncSettingsToStorage,
} from '@/SettingsPanel/utils/sync';
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import { sendRuntimeMessage } from '@/utils/sendRuntimeMessage';
import {
CACHE_BUCKET_KEYS,
Expand All @@ -37,7 +37,7 @@ import { AuthProgress } from './authProgress';

const syncAuthenticationToStorage = async (userProfile: UserInfo) => {
AuthProgress.start('Checking 2FA status');
const { is2FAEnabled } = await api.twoFactorAuth.status.query();
const { is2FAEnabled } = await trpcApi.twoFactorAuth.status.query();
userProfile.is2FAEnabled = is2FAEnabled;
userProfile.isTOTPVerified = false;
await chrome.storage.local.set({ [STORAGE_KEYS.userProfile]: userProfile });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { trpcApi } from '@/apis/trpcApi';
import { IPerson, usePerson, VoidFunction } from '@bypass/shared';
import { getImageFromFirebase } from '@helpers/firebase/storage';
import {
ActionIcon,
Avatar,
Expand Down Expand Up @@ -29,7 +29,6 @@ interface Props {
interface IForm {
uid?: string;
name: string;
imageRef?: string;
}

const AddOrEditPersonDialog = memo<Props>(function AddOrEditPersonDialog({
Expand All @@ -46,7 +45,6 @@ const AddOrEditPersonDialog = memo<Props>(function AddOrEditPersonDialog({
initialValues: {
uid: person?.uid,
name: person?.name ?? '',
imageRef: person?.imageRef,
},
validate: {
name: (value) => (value ? null : 'Required'),
Expand All @@ -70,27 +68,21 @@ const AddOrEditPersonDialog = memo<Props>(function AddOrEditPersonDialog({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initImageUrl, person]);

const fetchImage = async (ref: string) => {
const url = await getImageFromFirebase(ref);
const handleImageCropSave = async (fileName: string) => {
const url = await trpcApi.storage.getDownloadUrl.query(fileName);
setImageUrl(url);
};

const handleImageCropSave = async (imageFirebaseRef: string) => {
await fetchImage(imageFirebaseRef);
form.setFieldValue('imageRef', imageFirebaseRef);
};

const toggleImagePicker = () => setShowImagePicker(!showImagePicker);

const handleSave = (values: typeof form.values) => {
const { uid, name, imageRef } = values;
if (!uid || !imageRef) {
const { uid, name } = values;
if (!uid) {
return;
}
handleSaveClick({
uid,
name,
imageRef,
taggedUrls: person?.taggedUrls || [],
});
};
Expand Down
13 changes: 6 additions & 7 deletions apps/extension/src/PersonsPanel/components/ImagePicker.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { Header, VoidFunction } from '@bypass/shared';
import { FIREBASE_STORAGE_REF } from '@constants/index';
import { uploadImageToFirebase } from '@helpers/firebase/storage';
import { Header, VoidFunction, getPersonImageName } from '@bypass/shared';
import {
Box,
Button,
Expand All @@ -16,12 +14,13 @@ import Cropper from 'react-easy-crop';
import { Area } from 'react-easy-crop/types';
import { getCompressedImage } from '../utils/compressImage';
import getCroppedImg from '../utils/cropImage';
import { uploadFileToFirebase } from '../utils/uploadImage';

interface Props {
uid: string;
isOpen: boolean;
onDialogClose: VoidFunction;
handleImageSave: (imageRef: string) => void;
handleImageSave: (fileName: string) => void;
}

const ImagePicker = memo<Props>(function ImagePicker({
Expand Down Expand Up @@ -53,15 +52,15 @@ const ImagePicker = memo<Props>(function ImagePicker({
return;
}
try {
const imageRef = `${FIREBASE_STORAGE_REF.persons}/${uid}.jpeg`;
setIsUploadingImage(true);
const croppedImage = await getCroppedImg(
inputImageUrl,
croppedAreaPixels
);
const fileName = getPersonImageName(uid);
const compressedImage = await getCompressedImage(croppedImage);
await uploadImageToFirebase(compressedImage, imageRef);
handleImageSave(imageRef);
await uploadFileToFirebase(compressedImage, fileName);
handleImageSave(fileName);
onDialogClose();
} catch (error) {
console.error('Error while cropping the image', error);
Expand Down
8 changes: 4 additions & 4 deletions apps/extension/src/PersonsPanel/components/PersonsPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { trpcApi } from '@/apis/trpcApi';
import { MAX_PANEL_SIZE } from '@/constants';
import {
decryptionMapper,
getFilteredPersons,
getPersonImageName,
HEADER_HEIGHT,
IPerson,
IPersons,
Persons,
sortAlphabetically,
} from '@bypass/shared';
import { getPersons } from '@helpers/fetchFromStorage';
import { removeImageFromFirebase } from '@helpers/firebase/storage';
import { Box, Flex } from '@mantine/core';
import useHistoryStore from '@store/history';
import useToastStore from '@store/toast';
Expand Down Expand Up @@ -40,11 +41,10 @@ const PersonsPanel = () => {

const handleSave = async (_persons: IPerson[]) => {
const encryptedPersons = _persons.reduce<IPersons>(
(obj, { uid, name, imageRef, taggedUrls }) => {
(obj, { uid, name, taggedUrls }) => {
obj[uid] = {
uid,
name: btoa(name),
imageRef: btoa(encodeURIComponent(imageRef)),
taggedUrls,
};
return obj;
Expand Down Expand Up @@ -85,7 +85,7 @@ const PersonsPanel = () => {
const newPersons = [...persons];
newPersons.splice(pos, 1);
setPersons(newPersons);
await removeImageFromFirebase(person.imageRef);
await trpcApi.storage.removeFile.mutate(getPersonImageName(person.uid));
await handleSave(newPersons);
setIsFetching(false);
displayToast({ message: 'Person deleted successfully' });
Expand Down
1 change: 0 additions & 1 deletion apps/extension/src/PersonsPanel/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
persons : {
uid,
name,
imageRef,
taggedUrls : [urlHash1, urlHash2, ...]
}
```
22 changes: 9 additions & 13 deletions apps/extension/src/PersonsPanel/utils/sync.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { AuthProgress } from '@/HomePopup/utils/authProgress';
import { api } from '@/utils/api';
import { trpcApi } from '@/apis/trpcApi';
import {
addToCache,
CACHE_BUCKET_KEYS,
getCacheObj,
getPersonImageName,
IPerson,
PersonImageUrls,
STORAGE_KEYS,
} from '@bypass/shared';
import { getPersonImageUrls, getPersons } from '@helpers/fetchFromStorage';
import { getImageFromFirebase } from '@helpers/firebase/storage';
import { getAllDecodedPersons } from '.';

export const syncPersonsToStorage = async () => {
const persons = await api.firebaseData.personsGet.query();
const persons = await trpcApi.firebaseData.personsGet.query();
await chrome.storage.local.set({ [STORAGE_KEYS.persons]: persons });
};

Expand All @@ -24,7 +24,7 @@ export const syncPersonsFirebaseWithStorage = async () => {
if (!hasPendingPersons) {
return;
}
const isSaveSuccess = await api.firebaseData.personsPost.mutate(persons);
const isSaveSuccess = await trpcApi.firebaseData.personsPost.mutate(persons);
if (isSaveSuccess) {
await chrome.storage.local.remove('hasPendingPersons');
} else {
Expand All @@ -39,12 +39,9 @@ export const resetPersons = async () => {
]);
};

const resolveImageFromPerson = async ({
const resolveImageFromPerson = async (uid: string) => ({
uid,
imageRef,
}: Pick<IPerson, 'uid' | 'imageRef'>) => ({
uid,
imageUrl: await getImageFromFirebase(imageRef),
imageUrl: await trpcApi.storage.getDownloadUrl.query(getPersonImageName(uid)),
});

export const refreshPersonImageUrlsCache = async () => {
Expand All @@ -69,12 +66,12 @@ export const cachePersonImagesInStorage = async () => {
let totalResolved = 0;
const personImagesList = await Promise.all(
persons.map(async (person) => {
const url = await resolveImageFromPerson(person);
const urlData = await resolveImageFromPerson(person.uid);
totalResolved += 1;
AuthProgress.update(
`Caching person urls: ${totalResolved}/${persons.length}`
);
return url;
return urlData;
})
);
const personImageUrls = personImagesList.reduce<PersonImageUrls>(
Expand All @@ -87,7 +84,6 @@ export const cachePersonImagesInStorage = async () => {
await chrome.storage.local.set({
[STORAGE_KEYS.personImageUrls]: personImageUrls,
});
console.log('PersonImageUrls is set to', personImageUrls);
AuthProgress.finish('Cached person urls');
AuthProgress.start('Caching person images');
await cachePersonImages(personImageUrls);
Expand All @@ -97,7 +93,7 @@ export const cachePersonImagesInStorage = async () => {
export const updatePersonCacheAndImageUrls = async (person: IPerson) => {
// Update person image urls in storage
const personImageUrls = await getPersonImageUrls();
const { uid, imageUrl } = await resolveImageFromPerson(person);
const { uid, imageUrl } = await resolveImageFromPerson(person.uid);
personImageUrls[uid] = imageUrl;
await chrome.storage.local.set({
[STORAGE_KEYS.personImageUrls]: personImageUrls,
Expand Down
9 changes: 9 additions & 0 deletions apps/extension/src/PersonsPanel/utils/uploadImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { wretchApi } from '@/apis/wretchApi';

export const uploadFileToFirebase = async (blob: Blob, fileName: string) => {
const formData = new FormData();
formData.append('file', blob, fileName);

const wretch = await wretchApi();
await wretch.body(formData).post(null, '/upload-file').text();
};
Loading

0 comments on commit 8dc011d

Please sign in to comment.