Skip to content

Commit

Permalink
Add remove cookie message
Browse files Browse the repository at this point in the history
  • Loading branch information
jackluson committed Oct 23, 2024
1 parent bb9a338 commit 32615e7
Show file tree
Hide file tree
Showing 9 changed files with 186 additions and 20 deletions.
4 changes: 2 additions & 2 deletions chrome-extension/lib/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ chrome.cookies.onChanged.addListener(async changeInfo => {
await pushMultipleDomainCookies(uploadDomainCookies);
changedDomainSet.clear();
}
}, 8000);
}, 15000);

if (!checkDelayTimer) {
checkDelayTimer = setTimeout(() => {
Expand All @@ -88,7 +88,7 @@ chrome.cookies.onChanged.addListener(async changeInfo => {
timeoutFlag = true;
}
checkDelayTimer = null;
}, 30000);
}, 60000);
}
});

Expand Down
35 changes: 30 additions & 5 deletions chrome-extension/lib/background/listen.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { Message, MessageType, pullAndSetCookies, pushCookies, SendResponse } from '@sync-your-cookie/shared';
import {
Message,
MessageType,
pullAndSetCookies,
pushCookies,
removeCookies,
SendResponse,
} from '@sync-your-cookie/shared';
import { cloudflareStorage, domainConfigStorage } from '@sync-your-cookie/storage';

const check = ({ isSilent = false } = {}) => {
Expand Down Expand Up @@ -57,11 +64,11 @@ const handlePush = async (domain: string, callback: HandleCallback) => {
}
};

const handlePull = async (activeTabUrl: string, domain: string, callback: HandleCallback) => {
const handlePull = async (activeTabUrl: string, domain: string, isReload: boolean, callback: HandleCallback) => {
try {
await check();
await domainConfigStorage.togglePullingState(domain, true);
const cookieMap = await pullAndSetCookies(activeTabUrl, domain);
const cookieMap = await pullAndSetCookies(activeTabUrl, domain, isReload);
callback({ isOk: true, msg: 'Pull success', result: cookieMap });
} catch (err) {
callback({ isOk: false, msg: (err as Error).message || 'pull fail, please try again ', result: err });
Expand All @@ -70,6 +77,22 @@ const handlePull = async (activeTabUrl: string, domain: string, callback: Handle
}
};

const handleRemove = async (domain: string, callback: HandleCallback) => {
try {
await check();
const res = await removeCookies(domain);
console.log(res);
if (res.success) {
callback({ isOk: true, msg: 'Removed success' });
} else {
console.log('json.errors[0]', res.errors[0]);
callback({ isOk: false, msg: 'Removed fail, please try again ', result: res });
}
} catch (err) {
callback({ isOk: false, msg: (err as Error).message || 'remove fail, please try again ', result: err });
}
};

export const initListen = async () => {
function handleMessage(
message: Message,
Expand All @@ -84,9 +107,11 @@ export const initListen = async () => {
case MessageType.PullCookie:
// eslint-disable-next-line no-case-declarations, @typescript-eslint/no-non-null-asserted-optional-chain
const activeTabUrl = message.payload.activeTabUrl || sender.tab?.url!;
handlePull(activeTabUrl!, message.payload.domain, callback);
handlePull(activeTabUrl!, message.payload.domain, message.payload.reload, callback);
break;
case MessageType.RemoveCookie:
handleRemove(message.payload.domain, callback);
break;

default:
break;
}
Expand Down
14 changes: 10 additions & 4 deletions packages/shared/lib/cookie/withStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ export const pullCookies = async (isInit = false): Promise<ICookiesMap> => {
}
};

export const pullAndSetCookies = async (activeTabUrl: string, domain: string): Promise<ICookiesMap> => {
export const pullAndSetCookies = async (
activeTabUrl: string,
domain: string,
isReload = true,
): Promise<ICookiesMap> => {
const cookieMap = await pullCookies();
const cookieDetails = cookieMap.domainCookieMap?.[domain]?.cookies || [];
if (cookieDetails.length === 0) {
Expand Down Expand Up @@ -76,7 +80,9 @@ export const pullAndSetCookies = async (activeTabUrl: string, domain: string): P
// setTimeout(resolve, 5000);
// });
await Promise.allSettled(cookiesPromiseList);
await chrome.tabs.reload();
if (isReload) {
await chrome.tabs.reload();
}
}
return cookieMap;
};
Expand Down Expand Up @@ -142,8 +148,8 @@ export const pushMultipleDomainCookies = async (
export const removeCookies = async (domain: string): Promise<WriteResponse> => {
const cloudflareInfo = await cloudflareStorage.get();
try {
const isPushing = await domainConfigStorage.get();
if (isPushing) return Promise.reject('the cookie is pushing');
const domainConfig = await domainConfigStorage.get();
if (domainConfig.pushing) return Promise.reject('the cookie is pushing');
await domainConfigStorage.update({
pushing: true,
});
Expand Down
48 changes: 41 additions & 7 deletions packages/shared/lib/hooks/useCookieAction.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { ErrorCode } from '@lib/cloudflare';
import { pullCookieUsingMessage, pushCookieUsingMessage } from '@lib/message';
import { pullCookieUsingMessage, pushCookieUsingMessage, removeCookieUsingMessage } from '@lib/message';
import { domainConfigStorage } from '@sync-your-cookie/storage';
import { toast as Toast } from 'sonner';
import { useStorageSuspense } from './index';

export const useCookieAction = (domain: string, toast: typeof Toast) => {
const domainConfig = useStorageSuspense(domainConfigStorage);

const handlePush = async () => {
pushCookieUsingMessage({
domain,
const handlePush = async (selectedDomain = domain) => {
return pushCookieUsingMessage({
domain: selectedDomain,
})
.then(res => {
if (res.isOk) {
Expand All @@ -36,12 +36,14 @@ export const useCookieAction = (domain: string, toast: typeof Toast) => {
});
};

const handlePull = async (activeTabUrl: string) => {
pullCookieUsingMessage({
const handlePull = async (activeTabUrl: string, selectedDomain = domain, reload = true) => {
return pullCookieUsingMessage({
activeTabUrl: activeTabUrl,
domain: domain,
domain: selectedDomain,
reload,
})
.then(res => {
console.log('res', res);
if (res.isOk) {
toast.success('Pull success');
} else {
Expand All @@ -65,6 +67,37 @@ export const useCookieAction = (domain: string, toast: typeof Toast) => {
});
};

const handleRemove = async (selectedDomain = domain) => {
return removeCookieUsingMessage({
domain: selectedDomain,
})
.then(async res => {
console.log('res', res);
if (res.isOk) {
toast.success(res.msg || 'success');
await domainConfigStorage.removeItem(domain);
} else {
toast.error(res.msg || 'Removed fail');
}
console.log('res', res);
})
.catch(err => {
if (err.result?.errors?.length && err.result.errors[0].code === ErrorCode.NotFoundRoute) {
toast.error('cloudflare account info is incorrect', {
action: {
label: 'go to settings',
onClick: () => {
chrome.runtime.openOptionsPage();
},
},
});
} else {
toast.error(err.msg || 'Removed fail');
}
console.log('err', err);
});
};

return {
// domainConfig: domainConfig as typeof domainConfig,
pulling: domainConfig.pulling,
Expand All @@ -79,5 +112,6 @@ export const useCookieAction = (domain: string, toast: typeof Toast) => {
togglePushingState: domainConfigStorage.togglePushingState,
handlePush,
handlePull,
handleRemove,
};
};
17 changes: 17 additions & 0 deletions packages/shared/lib/message/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
export enum MessageType {
PushCookie = 'PushCookie',
PullCookie = 'PullCookie',
RemoveCookie = 'RemoveCookie',
}

export type PushCookieMessagePayload = {
domain: string;
};

export type RemoveCookieMessagePayload = {
domain: string;
};

export type PullCookieMessagePayload = {
domain: string;
activeTabUrl: string;
reload: boolean;
};

export type MessageMap = {
[MessageType.PushCookie]: {
type: MessageType.PushCookie;
payload: PushCookieMessagePayload;
};
[MessageType.RemoveCookie]: {
type: MessageType.RemoveCookie;
payload: RemoveCookieMessagePayload;
};
[MessageType.PullCookie]: {
type: MessageType.PullCookie;
payload: PullCookieMessagePayload;
Expand Down Expand Up @@ -56,6 +66,13 @@ export function pushCookieUsingMessage(payload: PushCookieMessagePayload) {
});
}

export function removeCookieUsingMessage(payload: RemoveCookieMessagePayload) {
return sendMessage<MessageType.RemoveCookie>({
payload,
type: MessageType.RemoveCookie,
});
}

export function pullCookieUsingMessage(payload: PullCookieMessagePayload) {
return sendMessage<MessageType.PullCookie>({
payload,
Expand Down
1 change: 1 addition & 0 deletions packages/tsconfig/utils.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"declaration": true,
"module": "CommonJS",
"moduleResolution": "Node",
"declarationMap": true,
"target": "ES6",
"types": ["node"],
"plugins": [
Expand Down
2 changes: 1 addition & 1 deletion pages/popup/src/Popup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const Popup = () => {
<Button
disabled={!activeTabUrl || domainItemConfig?.pushing || pushing}
className=" mr-2 w-[160px] justify-start"
onClick={handlePush}>
onClick={() => handlePush()}>
{domainItemConfig.pushing ? (
<RotateCw size={16} className="mr-2 animate-spin" />
) : (
Expand Down
19 changes: 18 additions & 1 deletion pages/sidepanel/src/SidePanel.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { withErrorBoundary, withSuspense } from '@sync-your-cookie/shared';
import { useTheme, withErrorBoundary, withSuspense } from '@sync-your-cookie/shared';
import { Toaster } from '@sync-your-cookie/ui';
import { useEffect } from 'react';
import CookieTable from './components/CookieTable';
const SidePanel = () => {
Expand All @@ -10,11 +11,27 @@ const SidePanel = () => {
}
});
}, []);
const { theme } = useTheme();

return (
<div className="">
<header></header>
<CookieTable />
<Toaster
theme={theme}
closeButton
toastOptions={{
duration: 1500,
style: {
// width: 'max-content',
// margin: '0 auto',
},
// className: 'w-[240px]',
}}
visibleToasts={1}
richColors
position="top-center"
/>
</div>
);
};
Expand Down
66 changes: 66 additions & 0 deletions pages/sidepanel/src/components/CookieTable/hooks/useAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useCookieAction } from '@sync-your-cookie/shared';
import type { Cookie } from '@sync-your-cookie/storage';
import { useState } from 'react';
import { toast } from 'sonner';
import { CookieItem } from './../index';
import { useSelected } from './useSelected';

export const useAction = (cookie: Cookie) => {
const [loading, setLoading] = useState(false);

const { selectedDomain, showCookiesColumns, setSelectedDomain, cookieList } = useSelected(cookie);
const cookieAction = useCookieAction(selectedDomain, toast);
const handleDelete = async (cookie: CookieItem) => {
try {
setLoading(true);
await cookieAction.handleRemove(cookie.domain);
} finally {
setLoading(false);
}
};

const handlePull = async (activeTabUrl: string, cookie: CookieItem) => {
try {
setLoading(true);
await cookieAction.handlePull(activeTabUrl, cookie.domain, false);
} finally {
setLoading(false);
}
};

const handlePush = async (cookie: CookieItem) => {
try {
setLoading(true);
await cookieAction.handlePush(cookie.domain);
} finally {
setLoading(false);
}
};

const handleViewCookies = async (domain: string) => {
console.log('domain', domain);
setSelectedDomain(domain);
console.log('cookie', cookie);
};

const handleBack = () => {
setSelectedDomain('');
};

console.log('cookies', cookie?.domainCookieMap?.[selectedDomain]);

return {
handleDelete,
handlePull,
handlePush,
handleViewCookies,
loading,
selectedDomain,
setSelectedDomain,
handleBack,
showCookiesColumns,
cookieAction,
// handlePush,
cookieList,
};
};

0 comments on commit 32615e7

Please sign in to comment.