Skip to content

Commit

Permalink
push and pull cookie by message
Browse files Browse the repository at this point in the history
  • Loading branch information
jackluson committed Oct 22, 2024
1 parent 07ea259 commit bb9a338
Show file tree
Hide file tree
Showing 11 changed files with 314 additions and 143 deletions.
96 changes: 96 additions & 0 deletions chrome-extension/lib/background/listen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { Message, MessageType, pullAndSetCookies, pushCookies, SendResponse } from '@sync-your-cookie/shared';
import { cloudflareStorage, domainConfigStorage } from '@sync-your-cookie/storage';

const check = ({ isSilent = false } = {}) => {
const cloudflareAccountInfo = cloudflareStorage.getSnapshot();
if (!cloudflareAccountInfo?.accountId || !cloudflareAccountInfo.namespaceId || !cloudflareAccountInfo.token) {
let message = 'Account ID is empty';
if (!cloudflareAccountInfo?.namespaceId) {
message = 'NamespaceId ID is empty';
} else if (!cloudflareAccountInfo.token) {
message = 'Token is empty';
}
// if (isSilent === false) {
// toast.error(message, {
// // description: 'Please set cloudflare account id',
// action: {
// label: 'go to settings',
// onClick: () => {
// chrome.runtime.openOptionsPage();
// },
// },
// position: 'top-right',
// });
// }

throw new Error(message);
}
};

type HandleCallback = (response?: SendResponse) => void;

const handlePush = async (domain: string, callback: HandleCallback) => {
try {
await check();
await domainConfigStorage.togglePushingState(domain, true);
const cookies = await chrome.cookies.getAll({
// url: activeTabUrl,
domain: domain,
});
if (cookies?.length) {
const res = await pushCookies(domain, cookies);
console.log(res);
await domainConfigStorage.togglePushingState(domain, false);
if (res.success) {
callback({ isOk: true, msg: 'Pushed success' });
} else {
console.log('json.errors[0]', res.errors[0]);
callback({ isOk: false, msg: 'Pushed fail, please try again ', result: res });
}
} else {
callback({ isOk: false, msg: 'no cookies found', result: cookies });
}
} catch (err) {
callback({ isOk: false, msg: (err as Error).message || 'push fail, please try again ', result: err });
} finally {
await domainConfigStorage.togglePushingState(domain, false);
}
};

const handlePull = async (activeTabUrl: string, domain: string, callback: HandleCallback) => {
try {
await check();
await domainConfigStorage.togglePullingState(domain, true);
const cookieMap = await pullAndSetCookies(activeTabUrl, domain);
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 });
} finally {
await domainConfigStorage.togglePullingState(domain, false);
}
};

export const initListen = async () => {
function handleMessage(
message: Message,
sender: chrome.runtime.MessageSender,
callback: (response?: SendResponse) => void,
) {
const type = message.type;
switch (type) {
case MessageType.PushCookie:
handlePush(message.payload.domain, callback);
break;
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);
break;

default:
break;
}
return true;
}
chrome.runtime.onMessage.addListener(handleMessage);
};
2 changes: 2 additions & 0 deletions packages/shared/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ export * from './lib/hoc';
export * from './lib/hooks';
export * from './lib/Providers';

export * from './lib/message';
export * from './lib/utils';

2 changes: 1 addition & 1 deletion packages/shared/lib/cookie/withStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const pullAndSetCookies = async (activeTabUrl: string, domain: string): P
cookiesPromiseList.push(promise);
}
}
// // reload window after set cookies
// reload window after set cookies
// await new Promise(resolve => {
// setTimeout(resolve, 5000);
// });
Expand Down
6 changes: 3 additions & 3 deletions packages/shared/lib/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useStorageSuspense } from './useStorageSuspense';
import { useCookieAction } from './useCookieAction';
import { useStorage } from './useStorage';

export { useStorageSuspense, useStorage };
import { useStorageSuspense } from './useStorageSuspense';
export { useCookieAction, useStorage, useStorageSuspense };
83 changes: 83 additions & 0 deletions packages/shared/lib/hooks/useCookieAction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { ErrorCode } from '@lib/cloudflare';
import { pullCookieUsingMessage, pushCookieUsingMessage } 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,
})
.then(res => {
if (res.isOk) {
toast.success('Pushed success');
} else {
toast.error(res.msg || 'Pushed 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 || 'Pushed fail');
}
console.log('err', err);
});
};

const handlePull = async (activeTabUrl: string) => {
pullCookieUsingMessage({
activeTabUrl: activeTabUrl,
domain: domain,
})
.then(res => {
if (res.isOk) {
toast.success('Pull success');
} else {
toast.error(res.msg || 'Pull fail');
}
})
.catch(err => {
console.log('err', 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 || 'Pull fail');
}
});
};

return {
// domainConfig: domainConfig as typeof domainConfig,
pulling: domainConfig.pulling,
pushing: domainConfig.pushing,
domainItemConfig: domainConfig.domainMap[domain] || {},
getDomainItemConfig: (selectedDomain: string) => {
return domainConfig.domainMap[selectedDomain] || {};
},
toggleAutoPullState: domainConfigStorage.toggleAutoPullState,
toggleAutoPushState: domainConfigStorage.toggleAutoPushState,
togglePullingState: domainConfigStorage.togglePullingState,
togglePushingState: domainConfigStorage.togglePushingState,
handlePush,
handlePull,
};
};
64 changes: 64 additions & 0 deletions packages/shared/lib/message/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
export enum MessageType {
PushCookie = 'PushCookie',
PullCookie = 'PullCookie',
}

export type PushCookieMessagePayload = {
domain: string;
};

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

export type MessageMap = {
[MessageType.PushCookie]: {
type: MessageType.PushCookie;
payload: PushCookieMessagePayload;
};
[MessageType.PullCookie]: {
type: MessageType.PullCookie;
payload: PullCookieMessagePayload;
};
};

// export type Message<T extends MessageType = MessageType> = {
// type: T;
// payload: MessagePayloadMap[T];
// };

export type Message<T extends MessageType = MessageType> = MessageMap[T];

export type SendResponse = {
isOk: boolean;
msg: string;
result?: unknown;
};

export function sendMessage<T extends MessageType>(message: Message<T>) {
return new Promise<SendResponse>((resolve, reject) => {
chrome.runtime.sendMessage(message, function (result: SendResponse) {
console.log('result->', result);
if (result?.isOk) {
resolve(result);
} else {
reject(result as SendResponse);
}
});
});
}

export function pushCookieUsingMessage(payload: PushCookieMessagePayload) {
return sendMessage<MessageType.PushCookie>({
payload,
type: MessageType.PushCookie,
});
}

export function pullCookieUsingMessage(payload: PullCookieMessagePayload) {
return sendMessage<MessageType.PullCookie>({
payload,
type: MessageType.PullCookie,
});
}
3 changes: 2 additions & 1 deletion packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@sync-your-cookie/protobuf": "workspace:*",
"@sync-your-cookie/tsconfig": "workspace:*",
"@types/pako": "^2.0.3",
"tsup": "8.0.2"
"tsup": "8.0.2",
"sonner": "^1.5.0"
}
}
2 changes: 1 addition & 1 deletion packages/storage/lib/cookieStorage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ICookie, ICookiesMap } from '@sync-your-cookie/protobuf';
import { BaseStorage, createStorage, StorageType } from './base';

interface Cookie extends ICookiesMap {}
export interface Cookie extends ICookiesMap {}

export const storage: BaseStorage<Cookie> = createStorage<Cookie>(
'cookie-storage-key',
Expand Down
46 changes: 45 additions & 1 deletion packages/storage/lib/domainConfigStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,56 @@ export const domainConfigStorage = {
return { ...currentInfo, ...updateInfo };
});
},

removeItem: async (domain: string) => {
await storage.set(currentInfo => {
const domainCookieMap = currentInfo.domainMap || {};
delete domainCookieMap[domain];
return { ...currentInfo, domainCookieMap };
});
},

togglePullingState: async (domain: string, checked?: boolean) => {
return await storage.set(currentInfo => {
const domainMap = currentInfo?.domainMap || {};
domainMap[domain] = {
...domainMap[domain],
pulling: checked ?? !domainMap[domain]?.pulling,
};
return { ...(currentInfo || {}), domainMap };
});
},

togglePushingState: async (domain: string, checked?: boolean) => {
return await storage.set(currentInfo => {
console.log('currentInfo', currentInfo);
const domainMap = currentInfo?.domainMap || {};
domainMap[domain] = {
...domainMap[domain],
pushing: checked ?? !domainMap[domain]?.pushing,
};
return { ...(currentInfo || {}), domainMap };
});
},

toggleAutoPullState: async (domain: string, checked?: boolean) => {
return await storage.set(currentInfo => {
const domainMap = currentInfo?.domainMap || {};
domainMap[domain] = {
...domainMap[domain],
autoPull: checked ?? !domainMap[domain]?.autoPull,
};
return { ...(currentInfo || {}), domainMap };
});
},

toggleAutoPushState: async (domain: string, checked?: boolean) => {
return await storage.set(currentInfo => {
const domainMap = currentInfo?.domainMap || {};
domainMap[domain] = {
...domainMap[domain],
autoPush: checked ?? !domainMap[domain]?.autoPush,
};
return { ...(currentInfo || {}), domainMap };
});
},
};
Loading

0 comments on commit bb9a338

Please sign in to comment.