converted sendmessage

This commit is contained in:
PhilReact 2024-10-29 18:50:03 +02:00
parent c9306493f0
commit 4f91924947
35 changed files with 163 additions and 225 deletions

View File

@ -5,7 +5,7 @@
android:allowBackup="true" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme"> android:theme="@style/AppTheme">

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/> <background android:drawable="@mipmap/ic_launcher_adaptive_back"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/> <foreground android:drawable="@mipmap/ic_launcher_adaptive_fore"/>
</adaptive-icon> </adaptive-icon>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -645,46 +645,16 @@ function App() {
}; };
useEffect(() => { useEffect(() => {
// Listen for messages from the background script // Handler function for incoming messages
const messageListener = (message, sender, sendResponse) => { const messageHandler = (event) => {
// Handle various actions const message = event.data;
if (
message.action === "UPDATE_STATE_CONFIRM_SEND_QORT" && if (message?.action === "CHECK_FOCUS") {
!isMainWindow
) { event.source.postMessage({ action: "CHECK_FOCUS_RESPONSE", isFocused: isFocusedRef.current }, event.origin);
setSendqortState(message.payload);
setExtstate("web-app-request-payment");
} else if (message.action === "closePopup" && !isMainWindow) {
window.close();
} else if ( } else if (
message.action === "UPDATE_STATE_REQUEST_CONNECTION" && message.action === "NOTIFICATION_OPEN_DIRECT"
!isMainWindow
) {
setRequestConnection(message.payload);
setExtstate("web-app-request-connection");
} else if (
message.action === "UPDATE_STATE_REQUEST_BUY_ORDER" &&
!isMainWindow
) {
setRequestBuyOrder(message.payload);
setExtstate("web-app-request-buy-order");
} else if (
message.action === "UPDATE_STATE_REQUEST_AUTHENTICATION" &&
!isMainWindow
) {
setRequestAuthentication(message.payload);
setExtstate("web-app-request-authentication");
} else if (message.action === "SET_COUNTDOWN" && !isMainWindow) {
setCountdown(message.payload);
} else if (message.action === "INITIATE_MAIN") {
setIsMain(true);
isMainRef.current = true;
} else if (message.action === "CHECK_FOCUS" && isMainWindow) {
sendResponse(isFocusedRef.current); // Synchronous response
return true; // Return true if you plan to send a response asynchronously
} else if (
message.action === "NOTIFICATION_OPEN_DIRECT" &&
isMainWindow
) { ) {
executeEvent("openDirectMessage", { executeEvent("openDirectMessage", {
from: message.payload.from, from: message.payload.from,
@ -693,7 +663,7 @@ function App() {
executeEvent("openGroupMessage", { executeEvent("openGroupMessage", {
from: message.payload.from, from: message.payload.from,
}); });
} else if ( } else if (
message.action === "NOTIFICATION_OPEN_ANNOUNCEMENT_GROUP" && message.action === "NOTIFICATION_OPEN_ANNOUNCEMENT_GROUP" &&
isMainWindow isMainWindow
) { ) {
@ -708,31 +678,21 @@ function App() {
data: message.payload.data, data: message.payload.data,
}); });
} }
// Call the permission request handler for "QORTAL_REQUEST_PERMISSION"
qortalRequestPermisson(message, sender, sendResponse);
if (message.action === "QORTAL_REQUEST_PERMISSION" && !isMainWindow) {
return true; // Return true to indicate an async response is coming
}
if (message.action === "QORTAL_REQUEST_PERMISSION" && isMainWindow && message?.isFromExtension) {
qortalRequestPermissonFromExtension(message, sender, sendResponse);
return true;
}
if (message.action === "QORTAL_REQUEST_PERMISSION" && isMainWindow) {
return;
}
}; };
// Add message listener // Attach the event listener
chrome.runtime?.onMessage.addListener(messageListener); window.addEventListener("message", messageHandler);
// Clean up the listener on component unmount // Clean up the event listener on component unmount
return () => { return () => {
chrome.runtime?.onMessage.removeListener(messageListener); window.removeEventListener("message", messageHandler);
}; };
}, []); }, []);
//param = isDecline //param = isDecline
const confirmPayment = (isDecline: boolean) => { const confirmPayment = (isDecline: boolean) => {
// REMOVED FOR MOBILE APP // REMOVED FOR MOBILE APP
@ -1396,7 +1356,7 @@ function App() {
textDecoration: "underline", textDecoration: "underline",
}} }}
onClick={() => { onClick={() => {
chrome.tabs.create({ url: "https://www.qort.trade" }); // TODO
}} }}
> >
Get QORT at qort.trade Get QORT at qort.trade

View File

@ -804,30 +804,27 @@ export async function notificationCase(request, event) {
try { try {
const notificationId = "chat_notification_" + Date.now(); // Create a unique ID const notificationId = "chat_notification_" + Date.now(); // Create a unique ID
chrome.notifications.create(notificationId, { // chrome.notifications.create(notificationId, {
type: "basic", // type: "basic",
iconUrl: "qort.png", // Add an appropriate icon for chat notifications // iconUrl: "qort.png", // Add an appropriate icon for chat notifications
title: "New Group Message!", // title: "New Group Message!",
message: "You have received a new message from one of your groups", // message: "You have received a new message from one of your groups",
priority: 2, // Use the maximum priority to ensure it's noticeable // priority: 2, // Use the maximum priority to ensure it's
// buttons: [ // });
// { title: 'Go to group' }
// ]
});
// Set a timeout to clear the notification after 'timeout' milliseconds // Set a timeout to clear the notification after 'timeout' milliseconds
setTimeout(() => { // setTimeout(() => {
chrome.notifications.clear(notificationId); // chrome.notifications.clear(notificationId);
}, 3000); // }, 3000);
event.source.postMessage( // event.source.postMessage(
{ // {
requestId: request.requestId, // requestId: request.requestId,
action: "notification", // action: "notification",
payload: true, // payload: true,
type: "backgroundMessageResponse", // type: "backgroundMessageResponse",
}, // },
event.origin // event.origin
); // );
} catch (error) { } catch (error) {
event.source.postMessage( event.source.postMessage(
{ {
@ -1399,7 +1396,7 @@ export async function publishGroupEncryptedResourceCase(request, event) {
export async function encryptSingleCase(request, event) { export async function encryptSingleCase(request, event) {
try { try {
const { data, secretKeyObject, typeNumber} = request.payload; const { data, secretKeyObject, typeNumber} = request.payload;
const response = await encryptSingle({ data, secretKeyObject, typeNumber }); const response = await encryptSingle({ data64: data, secretKeyObject, typeNumber });
event.source.postMessage( event.source.postMessage(
{ {
@ -1426,8 +1423,9 @@ export async function publishGroupEncryptedResourceCase(request, event) {
export async function decryptSingleCase(request, event) { export async function decryptSingleCase(request, event) {
try { try {
const { data, secretKeyObject, skipDecodeBase64} = request.payload; const { data, secretKeyObject, skipDecodeBase64} = request.payload;
const response = await decryptSingleFunc({ data, secretKeyObject, skipDecodeBase64 }); console.log({data, secretKeyObject, skipDecodeBase64})
const response = await decryptSingleFunc({ messages: data, secretKeyObject, skipDecodeBase64 });
console.log('response', response)
event.source.postMessage( event.source.postMessage(
{ {
requestId: request.requestId, requestId: request.requestId,

View File

@ -1,6 +1,6 @@
// @ts-nocheck // @ts-nocheck
// TODO
import "./qortalRequests"; // import "./qortalRequests";
import { isArray } from "lodash"; import { isArray } from "lodash";
import { import {
decryptGroupEncryption, decryptGroupEncryption,
@ -311,24 +311,27 @@ export function isUpdateMsg(data) {
async function checkWebviewFocus() { async function checkWebviewFocus() {
return new Promise((resolve) => { return new Promise((resolve) => {
// Set a timeout for 1 second
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
resolve(false); // No response within 1 second, assume not focused resolve(false); // No response within 1 second, assume not focused
}, 1000); }, 1000);
// Send message to the content script to check focus // Send a message to check focus
chrome.runtime.sendMessage({ action: "CHECK_FOCUS" }, (response) => { window.postMessage({ action: "CHECK_FOCUS" }, "*");
clearTimeout(timeout); // Clear the timeout if we get a response
if (chrome.runtime.lastError) { // Listen for the response
resolve(false); // Error occurred, assume not focused const handleMessage = (event) => {
} else { if (event.data?.action === "CHECK_FOCUS_RESPONSE") {
resolve(response); // Resolve based on the response clearTimeout(timeout);
window.removeEventListener("message", handleMessage); // Clean up listener
resolve(event.data.isFocused); // Resolve with the response
} }
}); };
window.addEventListener("message", handleMessage);
}); });
} }
function playNotificationSound() { function playNotificationSound() {
// chrome.runtime.sendMessage({ action: "PLAY_NOTIFICATION_SOUND" }); // chrome.runtime.sendMessage({ action: "PLAY_NOTIFICATION_SOUND" });
} }
@ -395,11 +398,11 @@ const handleNotificationDirect = async (directs) => {
// message: "You have received a new direct message", // message: "You have received a new direct message",
// priority: 2, // Use the maximum priority to ensure it's noticeable // priority: 2, // Use the maximum priority to ensure it's noticeable
// }); // });
if (!isMobile) { // if (!isMobile) {
setTimeout(() => { // setTimeout(() => {
chrome.notifications.clear(notificationId); // chrome.notifications.clear(notificationId);
}, 7000); // }, 7000);
} // }
// chrome.runtime.sendMessage( // chrome.runtime.sendMessage(
// { // {
@ -817,19 +820,19 @@ export const checkThreads = async (bringBack) => {
// priority: 2, // Use the maximum priority to ensure it's noticeable // priority: 2, // Use the maximum priority to ensure it's noticeable
// }); // });
if (!isMobile) { // if (!isMobile) {
setTimeout(() => { // setTimeout(() => {
chrome.notifications.clear(notificationId); // chrome.notifications.clear(notificationId);
}, 7000); // }, 7000);
} // }
playNotificationSound(); playNotificationSound();
} }
} }
const savedtimestampAfter = await getTimestampGroupAnnouncement(); const savedtimestampAfter = await getTimestampGroupAnnouncement();
chrome.runtime.sendMessage({ window.postMessage({
action: "SET_GROUP_ANNOUNCEMENTS", action: "SET_GROUP_ANNOUNCEMENTS",
payload: savedtimestampAfter, payload: savedtimestampAfter,
}); }, "*");
} catch (error) { } catch (error) {
} finally { } finally {
} }
@ -918,18 +921,19 @@ export const checkNewMessages = async () => {
// priority: 2, // Use the maximum priority to ensure it's noticeable // priority: 2, // Use the maximum priority to ensure it's noticeable
// }); // });
if (!isMobile) { // if (!isMobile) {
setTimeout(() => { // setTimeout(() => {
chrome.notifications.clear(notificationId); // chrome.notifications.clear(notificationId);
}, 7000); // }, 7000);
} // }
playNotificationSound(); playNotificationSound();
} }
const savedtimestampAfter = await getTimestampGroupAnnouncement(); const savedtimestampAfter = await getTimestampGroupAnnouncement();
chrome.runtime.sendMessage({ window.postMessage({
action: "SET_GROUP_ANNOUNCEMENTS", action: "SET_GROUP_ANNOUNCEMENTS",
payload: savedtimestampAfter, payload: savedtimestampAfter,
}); }, "*");
} catch (error) { } catch (error) {
} finally { } finally {
} }
@ -1031,10 +1035,10 @@ export async function getSaveWallet() {
export async function clearAllNotifications() { export async function clearAllNotifications() {
const notifications = await chrome.notifications.getAll(); // const notifications = await chrome.notifications.getAll();
for (const notificationId of Object.keys(notifications)) { // for (const notificationId of Object.keys(notifications)) {
await chrome.notifications.clear(notificationId); // await chrome.notifications.clear(notificationId);
} // }
} }
export async function getUserInfo() { export async function getUserInfo() {
@ -1634,7 +1638,7 @@ async function sendChat({ qortAddress, recipientPublicKey, message }) {
reference, reference,
}; };
} }
const path = chrome.runtime.getURL("memory-pow.wasm.full"); const path = `${import.meta.env.BASE_URL}memory-pow.wasm.full`;
const { nonce, chatBytesArray } = await computePow({ const { nonce, chatBytesArray } = await computePow({
chatBytes: tx.chatBytes, chatBytes: tx.chatBytes,
@ -1696,7 +1700,7 @@ export async function sendChatGroup({
// if (!hasEnoughBalance) { // if (!hasEnoughBalance) {
// throw new Error("Must have at least 4 QORT to send a chat message"); // throw new Error("Must have at least 4 QORT to send a chat message");
// } // }
const path = chrome.runtime.getURL("memory-pow.wasm.full"); const path = `${import.meta.env.BASE_URL}memory-pow.wasm.full`;
const { nonce, chatBytesArray } = await computePow({ const { nonce, chatBytesArray } = await computePow({
chatBytes: tx.chatBytes, chatBytes: tx.chatBytes,
@ -1776,7 +1780,7 @@ export async function sendChatDirect({
// if (!hasEnoughBalance) { // if (!hasEnoughBalance) {
// throw new Error("Must have at least 4 QORT to send a chat message"); // throw new Error("Must have at least 4 QORT to send a chat message");
// } // }
const path = chrome.runtime.getURL("memory-pow.wasm.full"); const path = `${import.meta.env.BASE_URL}memory-pow.wasm.full`;
const { nonce, chatBytesArray } = await computePow({ const { nonce, chatBytesArray } = await computePow({
chatBytes: tx.chatBytes, chatBytes: tx.chatBytes,
@ -1923,16 +1927,16 @@ async function createBuyOrderTx({ crosschainAtInfo, useLocal }) {
}; };
} }
setTimeout(() => { // setTimeout(() => {
chrome.tabs.query({}, function (tabs) { // chrome.tabs.query({}, function (tabs) {
tabs.forEach((tab) => { // tabs.forEach((tab) => {
chrome.tabs.sendMessage(tab.id, { // chrome.tabs.sendMessage(tab.id, {
type: "RESPONSE_FOR_TRADES", // type: "RESPONSE_FOR_TRADES",
message: responseMessage, // message: responseMessage,
}); // });
}); // });
}); // });
}, 5000); // }, 5000);
return; return;
} }
@ -2579,14 +2583,14 @@ async function listenForChatMessageForBuyOrder({
senderPublicKey senderPublicKey
); );
chrome.tabs.query({}, function (tabs) { // chrome.tabs.query({}, function (tabs) {
tabs.forEach((tab) => { // tabs.forEach((tab) => {
chrome.tabs.sendMessage(tab.id, { // chrome.tabs.sendMessage(tab.id, {
type: "RESPONSE_FOR_TRADES", // type: "RESPONSE_FOR_TRADES",
message: parsedMessageObj, // message: parsedMessageObj,
}); // });
}); // });
}); // });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
throw new Error(error.message); throw new Error(error.message);
@ -2594,39 +2598,39 @@ async function listenForChatMessageForBuyOrder({
} }
export function removeDuplicateWindow(popupUrl) { export function removeDuplicateWindow(popupUrl) {
chrome.windows.getAll( // chrome.windows.getAll(
{ populate: true, windowTypes: ["popup"] }, // { populate: true, windowTypes: ["popup"] },
(windows) => { // (windows) => {
// Filter to find popups matching the specific URL // // Filter to find popups matching the specific URL
const existingPopupsPending = windows.filter( // const existingPopupsPending = windows.filter(
(w) => // (w) =>
w.tabs && // w.tabs &&
w.tabs.some( // w.tabs.some(
(tab) => tab.pendingUrl && tab.pendingUrl.startsWith(popupUrl) // (tab) => tab.pendingUrl && tab.pendingUrl.startsWith(popupUrl)
) // )
); // );
const existingPopups = windows.filter( // const existingPopups = windows.filter(
(w) => // (w) =>
w.tabs && // w.tabs &&
w.tabs.some((tab) => tab.url && tab.url.startsWith(popupUrl)) // w.tabs.some((tab) => tab.url && tab.url.startsWith(popupUrl))
); // );
if (existingPopupsPending.length > 1) { // if (existingPopupsPending.length > 1) {
chrome.windows.remove( // chrome.windows.remove(
existingPopupsPending?.[0]?.tabs?.[0]?.windowId, // existingPopupsPending?.[0]?.tabs?.[0]?.windowId,
() => {} // () => {}
); // );
} else if ( // } else if (
existingPopupsPending.length > 0 && // existingPopupsPending.length > 0 &&
existingPopups.length > 0 // existingPopups.length > 0
) { // ) {
chrome.windows.remove( // chrome.windows.remove(
existingPopupsPending?.[0]?.tabs?.[0]?.windowId, // existingPopupsPending?.[0]?.tabs?.[0]?.windowId,
() => {} // () => {}
); // );
} // }
} // }
); // );
} }
export async function setChatHeads(data) { export async function setChatHeads(data) {
@ -3143,29 +3147,7 @@ const checkGroupList = async () => {
} }
}; };
const checkActiveChatsForNotifications = async () => {
try {
const popupUrl = chrome.runtime.getURL("index.html?main=true");
chrome.windows.getAll(
{ populate: true, windowTypes: ["popup"] },
(windows) => {
// Attempt to find an existing popup window that has a tab with the correct URL
const existingPopup = windows.find((w) => {
return (
w.tabs &&
w.tabs.some((tab) => tab.url && tab.url.startsWith(popupUrl))
);
});
if (existingPopup) {
} else {
checkGroupList();
}
}
);
} catch (error) {}
};
// Reconnect when service worker wakes up // Reconnect when service worker wakes up

View File

@ -471,16 +471,17 @@ isDOMContentLoaded: false
}, []); // Empty dependency array to run once when the component mounts }, []); // Empty dependency array to run once when the component mounts
chrome.runtime?.onMessage.addListener( function (message, sender, sendResponse) { // TODO
if(message.action === "SHOW_SAVE_FILE_PICKER"){ // chrome.runtime?.onMessage.addListener( function (message, sender, sendResponse) {
showSaveFilePicker(message?.data) // if(message.action === "SHOW_SAVE_FILE_PICKER"){
} // showSaveFilePicker(message?.data)
// }
else if (message.action === "getFileFromIndexedDB") { // else if (message.action === "getFileFromIndexedDB") {
handleGetFileFromIndexedDB(message.fileId, sendResponse); // handleGetFileFromIndexedDB(message.fileId, sendResponse);
return true; // Keep the message channel open for async response // return true; // Keep the message channel open for async response
} // }
}); // });
return {path, history, resetHistory, changeCurrentIndex} return {path, history, resetHistory, changeCurrentIndex}
}; };

View File

@ -130,6 +130,7 @@ export const ChatGroup = ({selectedGroup, secretKey, setSecretKey, getSecretKey,
secretKeyObject: secretKey, secretKeyObject: secretKey,
}) })
.then((response) => { .then((response) => {
console.log('decryptSingle', response)
if (!response?.error) { if (!response?.error) {
const filterUIMessages = encryptedMessages.filter((item) => !isExtMsg(item.data)); const filterUIMessages = encryptedMessages.filter((item) => !isExtMsg(item.data));
const decodedUIMessages = decodeBase64ForUIChatMessages(filterUIMessages); const decodedUIMessages = decodeBase64ForUIChatMessages(filterUIMessages);

View File

@ -35,18 +35,18 @@ export const MessageDisplay = ({ htmlContent , isReply}) => {
const target = e.target.closest('a'); const target = e.target.closest('a');
if (target) { if (target) {
const href = target.getAttribute('href'); const href = target.getAttribute('href');
// TODO
if (chrome && chrome.tabs) { // if (chrome && chrome.tabs) {
chrome.tabs.create({ url: href }, (tab) => { // chrome.tabs.create({ url: href }, (tab) => {
if (chrome.runtime.lastError) { // if (chrome.runtime.lastError) {
console.error('Error opening tab:', chrome.runtime.lastError); // console.error('Error opening tab:', chrome.runtime.lastError);
} else { // } else {
console.log('Tab opened successfully:', tab); // console.log('Tab opened successfully:', tab);
} // }
}); // });
} else { // } else {
console.error('chrome.tabs API is not available.'); // console.error('chrome.tabs API is not available.');
} // }
} else { } else {
console.error('No <a> tag found or href is null.'); console.error('No <a> tag found or href is null.');
} }

View File

@ -184,7 +184,8 @@ export const MobileFooter = ({
/> />
<BottomNavigationAction <BottomNavigationAction
onClick={() => { onClick={() => {
chrome.tabs.create({ url: "https://www.qort.trade"}); // TODO
// chrome.tabs.create({ url: "https://www.qort.trade"});
}} }}
icon={ icon={
<IconWrapper label="Trading" color="rgba(250, 250, 250, 0.5)"> <IconWrapper label="Trading" color="rgba(250, 250, 250, 0.5)">