From b665d229f3d02bee49e7f00ccee9e5a9edd5e754 Mon Sep 17 00:00:00 2001 From: PhilReact Date: Mon, 28 Oct 2024 12:07:22 +0200 Subject: [PATCH] cases --- src/App.tsx | 10 +- src/ExtStates/NotAuthenticated.tsx | 127 ++++++------ src/background-cases.ts | 183 +++++++++++++++++ src/background.ts | 73 +++++-- src/components/Chat/ChatDirect.tsx | 14 +- src/components/Group/Group.tsx | 306 ++++++----------------------- 6 files changed, 383 insertions(+), 330 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 3c2372d..4f3802b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -404,13 +404,17 @@ function App() { globalApiKey = key; } useEffect(() => { - chrome?.runtime?.sendMessage({ action: "getApiKey" }, (response) => { + window.sendMessage("getApiKey") + .then((response) => { if (response) { - handleSetGlobalApikey(response) + handleSetGlobalApikey(response); setApiKey(response); - } + }) + .catch((error) => { + console.error("Failed to get API key:", error?.message || "An error occurred"); }); + }, []); useEffect(() => { if (extState) { diff --git a/src/ExtStates/NotAuthenticated.tsx b/src/ExtStates/NotAuthenticated.tsx index 44e8db7..81a44b8 100644 --- a/src/ExtStates/NotAuthenticated.tsx +++ b/src/ExtStates/NotAuthenticated.tsx @@ -90,14 +90,16 @@ export const NotAuthenticated = ({ }, []); useEffect(() => { - chrome?.runtime?.sendMessage( - { action: "getCustomNodesFromStorage" }, - (response) => { - if (response) { - setCustomNodes(response || []); - } + window.sendMessage("getCustomNodesFromStorage") + .then((response) => { + if (response) { + setCustomNodes(response || []); } - ); + }) + .catch((error) => { + console.error("Failed to get custom nodes from storage:", error.message || "An error occurred"); + }); + }, []); useEffect(()=> { @@ -147,19 +149,21 @@ export const NotAuthenticated = ({ // Assuming the response is in plain text and will be 'true' or 'false' const data = await response.text(); if (data === "true") { - chrome?.runtime?.sendMessage( - { action: "setApiKey", payload }, - (response) => { - if (response) { - handleSetGlobalApikey(payload); - setIsValidApiKey(true); - setUseLocalNode(true); - if(!fromStartUp){ - setApiKey(payload) - } + window.sendMessage("setApiKey", payload) + .then((response) => { + if (response) { + handleSetGlobalApikey(payload); + setIsValidApiKey(true); + setUseLocalNode(true); + if (!fromStartUp) { + setApiKey(payload); } } - ); + }) + .catch((error) => { + console.error("Failed to set API key:", error.message || "An error occurred"); + }); + } else { setIsValidApiKey(false); setUseLocalNode(false); @@ -208,17 +212,19 @@ export const NotAuthenticated = ({ setCustomNodes(nodes); setCustomNodeToSaveIndex(null); if (!nodes) return; - chrome?.runtime?.sendMessage( - { action: "setCustomNodes", nodes }, - (response) => { - if (response) { - setMode("list"); - setUrl("http://"); - setCustomApiKey(""); - // add alert - } - } - ); + window.sendMessage("setCustomNodes", nodes) + .then((response) => { + if (response) { + setMode("list"); + setUrl("http://"); + setCustomApiKey(""); + // add alert if needed + } + }) + .catch((error) => { + console.error("Failed to set custom nodes:", error.message || "An error occurred"); + }); + }; @@ -338,16 +344,17 @@ export const NotAuthenticated = ({ url: "http://127.0.0.1:12391", }) setUseLocalNode(false) - chrome?.runtime?.sendMessage( - { action: "setApiKey", payload:null }, - (response) => { - if (response) { - setApiKey(null); - handleSetGlobalApikey(null); - - } - } - ); + window.sendMessage("setApiKey", null) + .then((response) => { + if (response) { + setApiKey(null); + handleSetGlobalApikey(null); + } + }) + .catch((error) => { + console.error("Failed to set API key:", error.message || "An error occurred"); + }); + } }} @@ -462,16 +469,17 @@ export const NotAuthenticated = ({ setMode("list"); setShow(false); setUseLocalNode(false); - chrome?.runtime?.sendMessage( - { action: "setApiKey", payload:null }, - (response) => { - if (response) { - setApiKey(null); - handleSetGlobalApikey(null); - - } - } - ); + window.sendMessage("setApiKey", null) + .then((response) => { + if (response) { + setApiKey(null); + handleSetGlobalApikey(null); + } + }) + .catch((error) => { + console.error("Failed to set API key:", error.message || "An error occurred"); + }); + }} variant="contained" > @@ -517,16 +525,17 @@ export const NotAuthenticated = ({ setShow(false); setIsValidApiKey(false); setUseLocalNode(false); - chrome?.runtime?.sendMessage( - { action: "setApiKey", payload:null }, - (response) => { - if (response) { - setApiKey(null); - handleSetGlobalApikey(null); - - } - } - ); + window.sendMessage("setApiKey", null) + .then((response) => { + if (response) { + setApiKey(null); + handleSetGlobalApikey(null); + } + }) + .catch((error) => { + console.error("Failed to set API key:", error.message || "An error occurred"); + }); + }} variant="contained" > diff --git a/src/background-cases.ts b/src/background-cases.ts index ce85224..abcb7e9 100644 --- a/src/background-cases.ts +++ b/src/background-cases.ts @@ -1,5 +1,6 @@ import { addDataPublishes, + addTimestampEnterChat, addUserSettings, banFromGroup, cancelBan, @@ -7,7 +8,9 @@ import { createGroup, decryptWallet, findUsableApi, + getApiKeyFromStorage, getBalanceInfo, + getCustomNodesFromStorage, getDataPublishes, getKeyPair, getLTCBalance, @@ -24,6 +27,7 @@ import { removeAdmin, saveTempPublish, sendCoin, + setChatHeads, walletVersion, } from "./background"; @@ -715,4 +719,183 @@ export async function balanceCase(request, event) { event.origin ); } + } + + export async function notificationCase(request, event) { + try { + const notificationId = "chat_notification_" + Date.now(); // Create a unique ID + + chrome.notifications.create(notificationId, { + type: "basic", + iconUrl: "qort.png", // Add an appropriate icon for chat notifications + title: "New Group Message!", + message: "You have received a new message from one of your groups", + priority: 2, // Use the maximum priority to ensure it's noticeable + // buttons: [ + // { title: 'Go to group' } + // ] + }); + // Set a timeout to clear the notification after 'timeout' milliseconds + setTimeout(() => { + chrome.notifications.clear(notificationId); + }, 3000); + + event.source.postMessage( + { + requestId: request.requestId, + action: "notification", + payload: true, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "notification", + error: "Error displaying notifaction", + type: "backgroundMessageResponse", + }, + event.origin + ); + } + } + + export async function addTimestampEnterChatCase(request, event) { + try { + const { groupId, timestamp } = request.payload; + const response = await addTimestampEnterChat({groupId, timestamp}); + + event.source.postMessage( + { + requestId: request.requestId, + action: "addTimestampEnterChat", + payload: response, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "addTimestampEnterChat", + error: error?.message, + type: "backgroundMessageResponse", + }, + event.origin + ); + } + } + + export async function setApiKeyCase(request, event) { + try { + const payload = request.payload; + chrome.storage.local.set({ apiKey: payload }, () => { + // sendResponse(true); + }); + + event.source.postMessage( + { + requestId: request.requestId, + action: "setApiKey", + payload: true, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "setApiKey", + error: error?.message, + type: "backgroundMessageResponse", + }, + event.origin + ); + } + } + export async function setCustomNodesCase(request, event) { + try { + const nodes = request.payload; + chrome.storage.local.set({ customNodes: nodes }, () => { + // sendResponse(true); + }); + + event.source.postMessage( + { + requestId: request.requestId, + action: "setCustomNodes", + payload: true, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "setCustomNodes", + error: error?.message, + type: "backgroundMessageResponse", + }, + event.origin + ); + } + } + + export async function getApiKeyCase(request, event) { + try { + const response = await getApiKeyFromStorage(); + + + event.source.postMessage( + { + requestId: request.requestId, + action: "getApiKey", + payload: response, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "getApiKey", + error: error?.message, + type: "backgroundMessageResponse", + }, + event.origin + ); + } + } + + export async function getCustomNodesFromStorageCase(request, event) { + try { + const response = await getCustomNodesFromStorage(); + + + event.source.postMessage( + { + requestId: request.requestId, + action: "getCustomNodesFromStorage", + payload: response, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "getCustomNodesFromStorage", + error: error?.message, + type: "backgroundMessageResponse", + }, + event.origin + ); + } } \ No newline at end of file diff --git a/src/background.ts b/src/background.ts index 3a1e247..2cb3575 100644 --- a/src/background.ts +++ b/src/background.ts @@ -30,6 +30,7 @@ import { TradeBotRespondMultipleRequest } from "./transactions/TradeBotRespondMu import { RESOURCE_TYPE_NUMBER_GROUP_CHAT_REACTIONS } from "./constants/resourceTypes"; import { addDataPublishesCase, + addTimestampEnterChatCase, addUserSettingsCase, balanceCase, banFromGroupCase, @@ -37,6 +38,8 @@ import { cancelInvitationToGroupCase, createGroupCase, decryptWalletCase, + getApiKeyCase, + getCustomNodesFromStorageCase, getDataPublishesCase, getTempPublishCase, getUserSettingsCase, @@ -48,10 +51,14 @@ import { ltcBalanceCase, makeAdminCase, nameCase, + notificationCase, registerNameCase, removeAdminCase, saveTempPublishCase, sendCoinCase, + setApiKeyCase, + setChatHeadsCase, + setCustomNodesCase, userInfoCase, validApiCase, versionCase, @@ -134,7 +141,7 @@ const checkDifference = (createdTimestamp) => { Date.now() - createdTimestamp < timeDifferenceForNotificationChatsBackground ); }; -const getApiKeyFromStorage = async () => { +export const getApiKeyFromStorage = async () => { return new Promise((resolve, reject) => { chrome.storage.local.get("apiKey", (result) => { if (chrome.runtime.lastError) { @@ -145,7 +152,7 @@ const getApiKeyFromStorage = async () => { }); }; -const getCustomNodesFromStorage = async () => { +export const getCustomNodesFromStorage = async () => { return new Promise((resolve, reject) => { chrome.storage.local.get("customNodes", (result) => { if (chrome.runtime.lastError) { @@ -396,16 +403,20 @@ const handleNotificationDirect = async (directs) => { } } catch (error) { if (!isFocused) { - chrome.runtime.sendMessage( - { - action: "notification", - payload: {}, - }, - (response) => { + window + .sendMessage("notification", {}) + .then((response) => { if (!response?.error) { + // Handle success if needed } - } - ); + }) + .catch((error) => { + console.error( + "Failed to send notification:", + error.message || "An error occurred" + ); + }); + const notificationId = "chat_notification_" + Date.now(); chrome.notifications.create(notificationId, { type: "basic", @@ -639,16 +650,20 @@ const handleNotification = async (groups) => { } } catch (error) { if (!isFocused) { - chrome.runtime.sendMessage( - { - action: "notification", - payload: {}, - }, - (response) => { + window + .sendMessage("notification", {}) + .then((response) => { if (!response?.error) { + // Handle success if needed } - } - ); + }) + .catch((error) => { + console.error( + "Failed to send notification:", + error.message || "An error occurred" + ); + }); + const notificationId = "chat_notification_" + Date.now(); chrome.notifications.create(notificationId, { type: "basic", @@ -2614,7 +2629,7 @@ export function removeDuplicateWindow(popupUrl) { ); } -async function setChatHeads(data) { +export async function setChatHeads(data) { const wallet = await getSaveWallet(); const address = wallet.address0; const dataString = JSON.stringify(data); @@ -2818,7 +2833,7 @@ async function setGroupData({ }); } -async function addTimestampEnterChat({ groupId, timestamp }) { +export async function addTimestampEnterChat({ groupId, timestamp }) { const wallet = await getSaveWallet(); const address = wallet.address0; const data = await getTimestampEnterChat(); @@ -2974,6 +2989,24 @@ function setupMessageListener() { case "removeAdmin": removeAdminCase(request, event); break; + case "notification": + notificationCase(request, event); + break; + + case "addTimestampEnterChat": + addTimestampEnterChatCase(request, event); + break; + case "setApiKey": + setApiKeyCase(request, event); + break; + case "setCustomNodes": + setCustomNodesCase(request, event); + case "getApiKey": + getApiKeyCase(request, event); + break; + case "getCustomNodesFromStorage": + getCustomNodesFromStorageCase(request, event); + break; default: console.error("Unknown action:", request.action); } diff --git a/src/components/Chat/ChatDirect.tsx b/src/components/Chat/ChatDirect.tsx index 916e7ff..3f14d91 100644 --- a/src/components/Chat/ChatDirect.tsx +++ b/src/components/Chat/ChatDirect.tsx @@ -267,13 +267,13 @@ const sendChatDirect = async ({ chatReference = undefined, messageText, otherDat "senderName": myName }) setNewChat(null) - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: response.recipient, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: response.recipient, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { getTimestampEnterChat() }, 400); diff --git a/src/components/Group/Group.tsx b/src/components/Group/Group.tsx index ce01cd9..6abd1d8 100644 --- a/src/components/Group/Group.tsx +++ b/src/components/Group/Group.tsx @@ -901,22 +901,22 @@ export const Group = ({ setMemberGroups(message.payload); if (selectedGroupRef.current && groupSectionRef.current === "chat") { - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: selectedGroupRef.current.groupId, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: selectedGroupRef.current.groupId, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + } if (selectedDirectRef.current) { - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: selectedDirectRef.current.address, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: selectedDirectRef.current.address, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + } setTimeout(() => { getTimestampEnterChat(); @@ -946,18 +946,7 @@ export const Group = ({ // Update the component state with the received 'sendqort' state setDirects(message.payload); - // if (selectedGroupRef.current) { - // chrome?.runtime?.sendMessage({ - // action: "addTimestampEnterChat", - // payload: { - // timestamp: Date.now(), - // groupId: selectedGroupRef.current.groupId, - // }, - // }); - // } - // setTimeout(() => { - // getTimestampEnterChat(); - // }, 200); + } else if (message.action === "PLAY_NOTIFICATION_SOUND") { audio.play(); } @@ -1115,13 +1104,13 @@ export const Group = ({ setNewChat(false); - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: findDirect.address, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: findDirect.address, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { setSelectedDirect(findDirect); @@ -1152,13 +1141,13 @@ export const Group = ({ setNewChat(false); - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: findDirect.address, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: findDirect.address, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { setSelectedDirect(findDirect); @@ -1201,13 +1190,13 @@ export const Group = ({ const handleMarkAsRead = (e) => { const { groupId } = e.detail; - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + chrome?.runtime?.sendMessage({ action: "addGroupNotificationTimestamp", @@ -1323,13 +1312,13 @@ export const Group = ({ setFirstSecretKeyInCreation(false); setGroupSection("chat"); - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: findGroup.groupId, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: findGroup.groupId, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { setSelectedGroup(findGroup); @@ -1537,13 +1526,13 @@ export const Group = ({ setNewChat(false); setSelectedDirect(null); if (selectedGroupRef.current) { - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: selectedGroupRef.current.groupId, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: selectedGroupRef.current.groupId, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { getTimestampEnterChat(); @@ -1644,13 +1633,13 @@ export const Group = ({ setNewChat(false); // setSelectedGroup(null); setIsOpenDrawer(false); - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: direct.address, - }, - }); + window.sendMessage("addTimestampEnterChat", { + timestamp: Date.now(), + groupId: direct.address, + }).catch((error) => { + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { setSelectedDirect(direct); @@ -1771,172 +1760,7 @@ export const Group = ({ borderRadius: !isMobile && '0px 15px 15px 0px' }} > - {/*
- {isMobile && ( - - { - setIsOpenDrawer(false); - }} - sx={{ - cursor: "pointer", - color: "white", - }} - /> - - )} - { - setChatMode((prev) => - prev === "directs" ? "groups" : "directs" - ); - - }} - sx={{ - backgroundColor: chatMode === 'directs' && ( groupChatHasUnread || groupsAnnHasUnread) ? 'red' : 'revert' - }} - > - {chatMode === "groups" && ( - <> - - - )} - - {chatMode === "directs" ? "Switch to groups" : "Direct msgs"} - -
*/} - {/*
- {directs.map((direct: any) => ( - - - // - // - // } - onClick={() => { - setSelectedDirect(null); - setNewChat(false); - // setSelectedGroup(null); - setIsOpenDrawer(false); - chrome?.runtime?.sendMessage({ - action: "addTimestampEnterChat", - payload: { - timestamp: Date.now(), - groupId: direct.address, - }, - }); - setTimeout(() => { - setSelectedDirect(direct); - - getTimestampEnterChat(); - }, 200); - }} - sx={{ - display: "flex", - width: "100%", - flexDirection: "column", - cursor: "pointer", - border: "1px #232428 solid", - padding: "2px", - borderRadius: "2px", - background: - direct?.address === selectedDirect?.address && "white", - }} - > - - - - {(direct?.name || direct?.address)?.charAt(0)} - - - - {direct?.sender !== myAddress && - direct?.timestamp && - ((!timestampEnterData[direct?.address] && - Date.now() - direct?.timestamp < - timeDifferenceForNotificationChats) || - timestampEnterData[direct?.address] < - direct?.timestamp) && ( - - )} - - - - ))} -
*/} +
{ + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { getTimestampEnterChat();