This commit is contained in:
PhilReact 2024-10-29 07:27:46 +02:00
parent 4da55da54e
commit 5074f79a5f
6 changed files with 443 additions and 115 deletions

View File

@ -205,17 +205,18 @@ export const clearAllQueues = () => {
export const pauseAllQueues = () => { export const pauseAllQueues = () => {
controlAllQueues("pause"); controlAllQueues("pause");
chrome?.runtime?.sendMessage({ window.sendMessage("pauseAllQueues", {})
action: "pauseAllQueues", .catch((error) => {
payload: {}, console.error("Failed to pause all queues:", error.message || "An error occurred");
}); });
}; };
export const resumeAllQueues = () => { export const resumeAllQueues = () => {
controlAllQueues("resume"); controlAllQueues("resume");
chrome?.runtime?.sendMessage({ window.sendMessage("resumeAllQueues", {}).catch((error) => {
action: "resumeAllQueues", console.error("Failed to resume all queues:", error.message || "An error occurred");
payload: {},
}); });
}; };
export const MyContext = createContext<MyContextInterface>(defaultValues); export const MyContext = createContext<MyContextInterface>(defaultValues);

View File

@ -6,9 +6,13 @@ import {
banFromGroup, banFromGroup,
cancelBan, cancelBan,
cancelInvitationToGroup, cancelInvitationToGroup,
checkLocalFunc,
checkNewMessages,
checkThreads, checkThreads,
clearAllNotifications, clearAllNotifications,
createGroup, createGroup,
decryptDirectFunc,
decryptSingleForPublishes,
decryptSingleFunc, decryptSingleFunc,
decryptWallet, decryptWallet,
findUsableApi, findUsableApi,
@ -32,9 +36,12 @@ import {
leaveGroup, leaveGroup,
makeAdmin, makeAdmin,
notifyAdminRegenerateSecretKey, notifyAdminRegenerateSecretKey,
pauseAllQueues,
registerName, registerName,
removeAdmin, removeAdmin,
resumeAllQueues,
saveTempPublish, saveTempPublish,
sendChatDirect,
sendChatGroup, sendChatGroup,
sendChatNotification, sendChatNotification,
sendCoin, sendCoin,
@ -1415,4 +1422,228 @@ export async function publishGroupEncryptedResourceCase(request, event) {
event.origin event.origin
); );
} }
}
export async function pauseAllQueuesCase(request, event) {
try {
await pauseAllQueues();
event.source.postMessage(
{
requestId: request.requestId,
action: "pauseAllQueues",
payload: true,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "pauseAllQueues",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function resumeAllQueuesCase(request, event) {
try {
await resumeAllQueues();
event.source.postMessage(
{
requestId: request.requestId,
action: "resumeAllQueues",
payload: true,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "resumeAllQueues",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function checkLocalCase(request, event) {
try {
const response = await checkLocalFunc()
event.source.postMessage(
{
requestId: request.requestId,
action: "pauseAllQueues",
payload: response,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "checkLocal",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function decryptSingleForPublishesCase(request, event) {
try {
const { data, secretKeyObject, skipDecodeBase64} = request.payload;
const response = await decryptSingleForPublishes({ data, secretKeyObject, skipDecodeBase64 });
event.source.postMessage(
{
requestId: request.requestId,
action: "decryptSingleForPublishes",
payload: response,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "decryptSingle",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function decryptDirectCase(request, event) {
try {
const { data, involvingAddress} = request.payload;
const response = await decryptDirectFunc({ data, involvingAddress });
event.source.postMessage(
{
requestId: request.requestId,
action: "decryptDirect",
payload: response,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "decryptDirect",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function sendChatGroupCase(request, event) {
try {
const { groupId,
typeMessage = undefined,
chatReference = undefined,
messageText} = request.payload;
const response = await sendChatGroup({ groupId, typeMessage, chatReference, messageText });
event.source.postMessage(
{
requestId: request.requestId,
action: "sendChatGroup",
payload: response,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "sendChatGroup",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function sendChatDirectCase(request, event) {
try {
const { directTo,
typeMessage = undefined,
chatReference = undefined,
messageText,
publicKeyOfRecipient,
address,
otherData} = request.payload;
const response = await sendChatDirect({ directTo,
chatReference,
messageText,
typeMessage,
publicKeyOfRecipient,
address,
otherData });
event.source.postMessage(
{
requestId: request.requestId,
action: "sendChatDirect",
payload: response,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "sendChatDirect",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
export async function setupGroupWebsocketCase(request, event) {
try {
checkNewMessages();
checkThreads();
event.source.postMessage(
{
requestId: request.requestId,
action: "sendChatDirect",
payload: true,
type: "backgroundMessageResponse",
},
event.origin
);
} catch (error) {
event.source.postMessage(
{
requestId: request.requestId,
action: "sendChatDirect",
error: error?.message,
type: "backgroundMessageResponse",
},
event.origin
);
}
} }

View File

@ -37,10 +37,13 @@ import {
banFromGroupCase, banFromGroupCase,
cancelBanCase, cancelBanCase,
cancelInvitationToGroupCase, cancelInvitationToGroupCase,
checkLocalCase,
clearAllNotificationsCase, clearAllNotificationsCase,
createGroupCase, createGroupCase,
decryptDirectCase,
decryptGroupEncryptionCase, decryptGroupEncryptionCase,
decryptSingleCase, decryptSingleCase,
decryptSingleForPublishesCase,
decryptWalletCase, decryptWalletCase,
encryptAndPublishSymmetricKeyGroupChatCase, encryptAndPublishSymmetricKeyGroupChatCase,
encryptSingleCase, encryptSingleCase,
@ -64,16 +67,21 @@ import {
nameCase, nameCase,
notificationCase, notificationCase,
notifyAdminRegenerateSecretKeyCase, notifyAdminRegenerateSecretKeyCase,
pauseAllQueuesCase,
publishGroupEncryptedResourceCase, publishGroupEncryptedResourceCase,
publishOnQDNCase, publishOnQDNCase,
registerNameCase, registerNameCase,
removeAdminCase, removeAdminCase,
resumeAllQueuesCase,
saveTempPublishCase, saveTempPublishCase,
sendChatDirectCase,
sendChatGroupCase,
sendCoinCase, sendCoinCase,
setApiKeyCase, setApiKeyCase,
setChatHeadsCase, setChatHeadsCase,
setCustomNodesCase, setCustomNodesCase,
setGroupDataCase, setGroupDataCase,
setupGroupWebsocketCase,
updateThreadActivityCase, updateThreadActivityCase,
userInfoCase, userInfoCase,
validApiCase, validApiCase,
@ -150,8 +158,8 @@ export const clearAllQueues = () => {
}); });
}; };
const pauseAllQueues = () => controlAllQueues("pause"); export const pauseAllQueues = () => controlAllQueues("pause");
const resumeAllQueues = () => controlAllQueues("resume"); export const resumeAllQueues = () => controlAllQueues("resume");
const checkDifference = (createdTimestamp) => { const checkDifference = (createdTimestamp) => {
return ( return (
Date.now() - createdTimestamp < timeDifferenceForNotificationChatsBackground Date.now() - createdTimestamp < timeDifferenceForNotificationChatsBackground
@ -862,7 +870,7 @@ export const checkThreads = async (bringBack) => {
} finally { } finally {
} }
}; };
const checkNewMessages = async () => { export const checkNewMessages = async () => {
try { try {
let mutedGroups = (await getUserSettings({ key: "mutedGroups" })) || []; let mutedGroups = (await getUserSettings({ key: "mutedGroups" })) || [];
if (!isArray(mutedGroups)) mutedGroups = []; if (!isArray(mutedGroups)) mutedGroups = [];
@ -1731,7 +1739,7 @@ export async function sendChatGroup({
return _response; return _response;
} }
async function sendChatDirect({ export async function sendChatDirect({
address, address,
directTo, directTo,
typeMessage, typeMessage,
@ -1834,7 +1842,7 @@ export async function decryptSingleFunc({
} }
return holdMessages; return holdMessages;
} }
async function decryptSingleForPublishes({ export async function decryptSingleForPublishes({
messages, messages,
secretKeyObject, secretKeyObject,
skipDecodeBase64, skipDecodeBase64,
@ -1857,7 +1865,7 @@ async function decryptSingleForPublishes({
return holdMessages; return holdMessages;
} }
async function decryptDirectFunc({ messages, involvingAddress }) { export async function decryptDirectFunc({ messages, involvingAddress }) {
const senderPublicKey = await getPublicKey(involvingAddress); const senderPublicKey = await getPublicKey(involvingAddress);
let holdMessages = []; let holdMessages = [];
@ -2665,7 +2673,7 @@ export async function setChatHeads(data) {
}); });
} }
async function checkLocalFunc() { export async function checkLocalFunc() {
const apiKey = await getApiKeyFromStorage(); const apiKey = await getApiKeyFromStorage();
return !!apiKey; return !!apiKey;
} }
@ -3075,12 +3083,90 @@ function setupMessageListener() {
case "encryptSingle": case "encryptSingle":
encryptSingleCase(request, event); encryptSingleCase(request, event);
break; break;
case "decryptSingle": case "decryptSingle":
decryptSingleCase(request, event); decryptSingleCase(request, event);
break; break;
case "pauseAllQueues":
pauseAllQueuesCase(request, event);
break;
case "resumeAllQueues":
resumeAllQueuesCase(request, event);
break;
case "checkLocal":
checkLocalCase(request, event);
break;
case "decryptSingleForPublishes":
decryptSingleForPublishesCase(request, event);
break;
case "decryptDirect":
decryptDirectCase(request, event);
break;
case "sendChatGroup":
sendChatGroupCase(request, event);
break;
case "sendChatDirect":
sendChatDirectCase(request, event);
break;
case "setupGroupWebsocket":
setupGroupWebsocketCase(request, event);
break;
case "logout":
{
try {
const logoutFunc = async () => {
forceCloseWebSocket();
clearAllQueues();
if (interval) {
// for announcement notification
clearInterval(interval);
}
const wallet = await getSaveWallet();
const address = wallet.address0;
const key1 = `tempPublish-${address}`;
const key2 = `group-data-${address}`;
const key3 = `${address}-publishData`;
chrome.storage.local.remove(
[
"keyPair",
"walletInfo",
"active-groups-directs",
key1,
key2,
key3,
],
() => {
if (chrome.runtime.lastError) {
// Handle error
console.error(chrome.runtime.lastError.message);
} else {
chrome.tabs.query({}, function (tabs) {
tabs.forEach((tab) => {
chrome.tabs.sendMessage(tab.id, { type: "LOGOUT" });
});
});
// Data removed successfully
event.source.postMessage(
{
requestId: request.requestId,
action: "logout",
payload: true,
type: "backgroundMessageResponse",
},
event.origin
);
}
}
);
};
logoutFunc();
} catch (error) {}
}
break;
default: default:
console.error("Unknown action:", request.action); console.error("Unknown action:", request.action);
break break;
} }
}); });
} }

View File

@ -101,43 +101,41 @@ export const ChatDirect = ({ myAddress, isNewChat, selectedDirect, setSelectedDi
const decryptMessages = (encryptedMessages: any[], isInitiated: boolean)=> { const decryptMessages = (encryptedMessages: any[], isInitiated: boolean)=> {
try { try {
return new Promise((res, rej)=> { return new Promise((res, rej)=> {
chrome?.runtime?.sendMessage({ action: "decryptDirect", payload: { window.sendMessage("decryptDirect", {
data: encryptedMessages, data: encryptedMessages,
involvingAddress: selectedDirect?.address involvingAddress: selectedDirect?.address,
}}, (response) => { })
.then((response) => {
if (!response?.error) { if (!response?.error) {
processWithNewMessages(response, selectedDirect?.address);
processWithNewMessages(response, selectedDirect?.address) res(response);
res(response)
if(isInitiated){
const formatted = response.map((item: any)=> { if (isInitiated) {
return { const formatted = response.map((item) => ({
...item, ...item,
id: item.signature, id: item.signature,
text: item.message, text: item.message,
unread: item?.sender === myAddress ? false : true unread: item?.sender === myAddress ? false : true,
} }));
} ) setMessages((prev) => [...prev, ...formatted]);
setMessages((prev)=> [...prev, ...formatted]) } else {
} else { const formatted = response.map((item) => ({
const formatted = response.map((item: any)=> {
return {
...item, ...item,
id: item.signature, id: item.signature,
text: item.message, text: item.message,
unread: false unread: false,
} }));
} ) setMessages(formatted);
setMessages(formatted) hasInitialized.current = true;
hasInitialized.current = true }
return;
} }
} rej(response.error);
rej(response.error) })
}); .catch((error) => {
rej(error.message || "An error occurred");
});
}) })
} catch (error) { } catch (error) {
@ -246,43 +244,52 @@ const sendChatDirect = async ({ chatReference = undefined, messageText, otherDat
if(!directTo) return if(!directTo) return
return new Promise((res, rej)=> { return new Promise((res, rej)=> {
chrome?.runtime?.sendMessage({ action: "sendChatDirect", payload: { window.sendMessage("sendChatDirect", {
directTo, chatReference, messageText, otherData, publicKeyOfRecipient, address: directTo directTo,
}}, async (response) => { chatReference,
messageText,
if (!response?.error) { otherData,
if(isNewChatVar){ publicKeyOfRecipient,
address: directTo,
let getRecipientName = null })
try { .then(async (response) => {
getRecipientName = await getNameInfo(response.recipient) if (!response?.error) {
} catch (error) { if (isNewChatVar) {
let getRecipientName = null;
try {
getRecipientName = await getNameInfo(response.recipient);
} catch (error) {
console.error("Error fetching recipient name:", error);
}
setSelectedDirect({
address: response.recipient,
name: getRecipientName,
timestamp: Date.now(),
sender: myAddress,
senderName: myName,
});
setNewChat(null);
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);
} }
setSelectedDirect({ res(response);
"address": response.recipient, return;
"name": getRecipientName,
"timestamp": Date.now(),
"sender": myAddress,
"senderName": myName
})
setNewChat(null)
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);
} }
res(response) rej(response.error);
return })
} .catch((error) => {
rej(response.error) rej(error.message || "An error occurred");
}); });
}) })
} catch (error) { } catch (error) {
throw new Error(error) throw new Error(error)

View File

@ -424,16 +424,23 @@ export const ChatGroup = ({selectedGroup, secretKey, setSecretKey, getSecretKey,
const sendChatGroup = async ({groupId, typeMessage = undefined, chatReference = undefined, messageText}: any)=> { const sendChatGroup = async ({groupId, typeMessage = undefined, chatReference = undefined, messageText}: any)=> {
try { try {
return new Promise((res, rej)=> { return new Promise((res, rej)=> {
chrome?.runtime?.sendMessage({ action: "sendChatGroup", payload: { window.sendMessage("sendChatGroup", {
groupId, typeMessage, chatReference, messageText groupId,
}}, (response) => { typeMessage,
chatReference,
if (!response?.error) { messageText,
res(response) })
return .then((response) => {
} if (!response?.error) {
rej(response.error) res(response);
}); return;
}
rej(response.error);
})
.catch((error) => {
rej(error.message || "An error occurred");
});
}) })
} catch (error) { } catch (error) {
throw new Error(error) throw new Error(error)

View File

@ -86,38 +86,34 @@ export const getTempPublish = async () => {
export const decryptPublishes = async (encryptedMessages: any[], secretKey) => { export const decryptPublishes = async (encryptedMessages: any[], secretKey) => {
try { try {
return await new Promise((res, rej) => { return await new Promise((res, rej) => {
chrome?.runtime?.sendMessage( window.sendMessage("decryptSingleForPublishes", {
{ data: encryptedMessages,
action: "decryptSingleForPublishes", secretKeyObject: secretKey,
payload: { skipDecodeBase64: true,
data: encryptedMessages, })
secretKeyObject: secretKey, .then((response) => {
skipDecodeBase64: true,
},
},
(response) => {
if (!response?.error) { if (!response?.error) {
res(response); res(response);
// if(hasInitialized.current){ // if(hasInitialized.current){
// setMessages((prev) => [...prev, ...formatted]);
// setMessages((prev)=> [...prev, ...formatted])
// } else { // } else {
// const formatted = response.map((item: any)=> { // const formatted = response.map((item) => ({
// return { // ...item,
// ...item, // id: item.signature,
// id: item.signature, // text: item.text,
// text: item.text, // unread: false
// unread: false // }));
// } // setMessages(formatted);
// } ) // hasInitialized.current = true;
// setMessages(formatted)
// hasInitialized.current = true
// } // }
return;
} }
rej(response.error); rej(response.error);
} })
); .catch((error) => {
rej(error.message || "An error occurred");
});
}); });
} catch (error) {} } catch (error) {}
}; };