mirror of
https://github.com/Qortal/qortal-mobile.git
synced 2025-04-18 17:35:53 +00:00
changed qortalrequest messaging
This commit is contained in:
parent
4f91924947
commit
eb8049c12d
9
package-lock.json
generated
9
package-lock.json
generated
@ -9,6 +9,7 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^6.1.2",
|
||||
"@capacitor/browser": "^6.0.3",
|
||||
"@capacitor/cli": "^6.1.2",
|
||||
"@capacitor/core": "^6.1.2",
|
||||
"@chatscope/chat-ui-kit-react": "^2.0.3",
|
||||
@ -398,6 +399,14 @@
|
||||
"@capacitor/core": "^6.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@capacitor/browser": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@capacitor/browser/-/browser-6.0.3.tgz",
|
||||
"integrity": "sha512-V5/ViE+fy3rW+6w0L2du4747/hivBcI/5OGOKi01U9YdFvOWbiiGL+qetq1QdkANEqvYd4yoCeXZL2GyGySn5g==",
|
||||
"peerDependencies": {
|
||||
"@capacitor/core": "^6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@capacitor/cli": {
|
||||
"version": "6.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@capacitor/cli/-/cli-6.1.2.tgz",
|
||||
|
@ -13,6 +13,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^6.1.2",
|
||||
"@capacitor/browser": "^6.0.3",
|
||||
"@capacitor/cli": "^6.1.2",
|
||||
"@capacitor/core": "^6.1.2",
|
||||
"@chatscope/chat-ui-kit-react": "^2.0.3",
|
||||
|
848
src/App.tsx
848
src/App.tsx
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
// @ts-nocheck
|
||||
// TODO
|
||||
// import "./qortalRequests";
|
||||
import "./qortalRequests";
|
||||
import { isArray } from "lodash";
|
||||
import {
|
||||
decryptGroupEncryption,
|
||||
@ -2878,7 +2878,6 @@ async function getChatHeadsDirect() {
|
||||
throw new Error("No Chatheads saved");
|
||||
}
|
||||
}
|
||||
// TODO: listener
|
||||
|
||||
function setupMessageListener() {
|
||||
window.addEventListener("message", async (event) => {
|
||||
|
@ -3,6 +3,8 @@ import FileSaver from 'file-saver';
|
||||
import { executeEvent } from '../../utils/events';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { navigationControllerAtom } from '../../atoms/global';
|
||||
|
||||
|
||||
class Semaphore {
|
||||
constructor(count) {
|
||||
this.count = count
|
||||
@ -58,7 +60,7 @@ const fileToBase64 = (file) => new Promise(async (resolve, reject) => {
|
||||
}
|
||||
})
|
||||
|
||||
function openIndexedDB() {
|
||||
export function openIndexedDB() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open("fileStorageDB", 1);
|
||||
|
||||
@ -79,58 +81,7 @@ function openIndexedDB() {
|
||||
});
|
||||
}
|
||||
|
||||
async function handleGetFileFromIndexedDB(fileId, sendResponse) {
|
||||
try {
|
||||
const db = await openIndexedDB();
|
||||
const transaction = db.transaction(["files"], "readonly");
|
||||
const objectStore = transaction.objectStore("files");
|
||||
|
||||
const getRequest = objectStore.get(fileId);
|
||||
|
||||
getRequest.onsuccess = async function (event) {
|
||||
if (getRequest.result) {
|
||||
const file = getRequest.result.data;
|
||||
|
||||
try {
|
||||
const base64String = await fileToBase64(file);
|
||||
|
||||
// Create a new transaction to delete the file
|
||||
const deleteTransaction = db.transaction(["files"], "readwrite");
|
||||
const deleteObjectStore = deleteTransaction.objectStore("files");
|
||||
const deleteRequest = deleteObjectStore.delete(fileId);
|
||||
|
||||
deleteRequest.onsuccess = function () {
|
||||
try {
|
||||
sendResponse({ result: base64String });
|
||||
|
||||
} catch (error) {
|
||||
console.log('error', error)
|
||||
}
|
||||
};
|
||||
|
||||
deleteRequest.onerror = function () {
|
||||
console.error(`Error deleting file with ID ${fileId} from IndexedDB`);
|
||||
sendResponse({ result: null, error: "Failed to delete file from IndexedDB" });
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error converting file to Base64:", error);
|
||||
sendResponse({ result: null, error: "Failed to convert file to Base64" });
|
||||
}
|
||||
} else {
|
||||
console.error(`File with ID ${fileId} not found in IndexedDB`);
|
||||
sendResponse({ result: null, error: "File not found in IndexedDB" });
|
||||
}
|
||||
};
|
||||
|
||||
getRequest.onerror = function () {
|
||||
console.error(`Error retrieving file with ID ${fileId} from IndexedDB`);
|
||||
sendResponse({ result: null, error: "Error retrieving file from IndexedDB" });
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error opening IndexedDB:", error);
|
||||
sendResponse({ result: null, error: "Error opening IndexedDB" });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const UIQortalRequests = [
|
||||
'GET_USER_ACCOUNT', 'DECRYPT_DATA', 'SEND_COIN', 'GET_LIST_ITEMS',
|
||||
@ -215,7 +166,7 @@ const UIQortalRequests = [
|
||||
}
|
||||
}
|
||||
|
||||
const showSaveFilePicker = async (data) => {
|
||||
export const showSaveFilePicker = async (data) => {
|
||||
let blob
|
||||
let fileName
|
||||
try {
|
||||
@ -368,7 +319,7 @@ isDOMContentLoaded: false
|
||||
if (event?.data?.requestedHandler !== 'UI') return;
|
||||
|
||||
const sendMessageToRuntime = (message, eventPort) => {
|
||||
window.sendMessage(message.action, message, 60000, message.isFromExtension)
|
||||
window.sendMessage(message.action, message.payload, 60000, message.isExtension)
|
||||
.then((response) => {
|
||||
if (response.error) {
|
||||
eventPort.postMessage({
|
||||
@ -402,6 +353,7 @@ isDOMContentLoaded: false
|
||||
) {
|
||||
let data;
|
||||
try {
|
||||
console.log('storeFilesInIndexedDB', structuredClone(event.data))
|
||||
data = await storeFilesInIndexedDB(event.data);
|
||||
} catch (error) {
|
||||
console.error('Error storing files in IndexedDB:', error);
|
||||
@ -457,7 +409,9 @@ isDOMContentLoaded: false
|
||||
name: event?.data?.payload?.name
|
||||
} }, '*'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
// Add the listener for messages coming from the frameWindow
|
||||
@ -471,17 +425,7 @@ isDOMContentLoaded: false
|
||||
|
||||
}, []); // Empty dependency array to run once when the component mounts
|
||||
|
||||
// TODO
|
||||
// chrome.runtime?.onMessage.addListener( function (message, sender, sendResponse) {
|
||||
// if(message.action === "SHOW_SAVE_FILE_PICKER"){
|
||||
// showSaveFilePicker(message?.data)
|
||||
// }
|
||||
|
||||
// else if (message.action === "getFileFromIndexedDB") {
|
||||
// handleGetFileFromIndexedDB(message.fileId, sendResponse);
|
||||
// return true; // Keep the message channel open for async response
|
||||
// }
|
||||
// });
|
||||
|
||||
|
||||
return {path, history, resetHistory, changeCurrentIndex}
|
||||
};
|
||||
|
@ -1,6 +1,7 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import DOMPurify from 'dompurify';
|
||||
import './styles.css'; // Ensure this CSS file is imported
|
||||
import { Browser } from '@capacitor/browser';
|
||||
|
||||
export const MessageDisplay = ({ htmlContent , isReply}) => {
|
||||
|
||||
@ -28,25 +29,15 @@ export const MessageDisplay = ({ htmlContent , isReply}) => {
|
||||
});
|
||||
|
||||
// Function to handle link clicks
|
||||
const handleClick = (e) => {
|
||||
const handleClick = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Ensure we are targeting an <a> element
|
||||
const target = e.target.closest('a');
|
||||
if (target) {
|
||||
const href = target.getAttribute('href');
|
||||
// TODO
|
||||
// if (chrome && chrome.tabs) {
|
||||
// chrome.tabs.create({ url: href }, (tab) => {
|
||||
// if (chrome.runtime.lastError) {
|
||||
// console.error('Error opening tab:', chrome.runtime.lastError);
|
||||
// } else {
|
||||
// console.log('Tab opened successfully:', tab);
|
||||
// }
|
||||
// });
|
||||
// } else {
|
||||
// console.error('chrome.tabs API is not available.');
|
||||
// }
|
||||
await Browser.open({ url: href });
|
||||
|
||||
} else {
|
||||
console.error('No <a> tag found or href is null.');
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import { Home, Groups, Message, ShowChart } from "@mui/icons-material";
|
||||
import Box from "@mui/material/Box";
|
||||
import BottomLogo from "../../assets/svgs/BottomLogo5.svg";
|
||||
import LogoSelected from "../../assets/svgs/LogoSelected.svg";
|
||||
import { Browser } from '@capacitor/browser';
|
||||
|
||||
import { CustomSvg } from "../../common/CustomSvg";
|
||||
import { WalletIcon } from "../../assets/Icons/WalletIcon";
|
||||
@ -183,10 +184,10 @@ export const MobileFooter = ({
|
||||
}}
|
||||
/>
|
||||
<BottomNavigationAction
|
||||
onClick={() => {
|
||||
// TODO
|
||||
// chrome.tabs.create({ url: "https://www.qort.trade"});
|
||||
onClick={async () => {
|
||||
await Browser.open({ url: 'https://www.qort.trade' });
|
||||
}}
|
||||
|
||||
icon={
|
||||
<IconWrapper label="Trading" color="rgba(250, 250, 250, 0.5)">
|
||||
<TradingIcon color="rgba(250, 250, 250, 0.5)" />
|
||||
|
@ -24,13 +24,13 @@ window.addEventListener("message", (event) => {
|
||||
}
|
||||
});
|
||||
|
||||
export const sendMessageBackground = (action, data = {}, timeout = 60000, isFromExtension) => {
|
||||
export const sendMessageBackground = (action, data = {}, timeout = 60000, isExtension) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = generateRequestId(); // Unique ID for each request
|
||||
callbackMap.set(requestId, { resolve, reject }); // Store both resolve and reject callbacks
|
||||
|
||||
// Send the message with `backgroundMessage` type
|
||||
window.postMessage({ type: "backgroundMessage", action, requestId, payload: data, isFromExtension }, "*");
|
||||
window.postMessage({ type: "backgroundMessage", action, requestId, payload: data, isExtension }, "*");
|
||||
|
||||
// Set up a timeout to automatically reject if no response is received
|
||||
const timeoutId = setTimeout(() => {
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { addForeignServer, addListItems, createPoll, decryptData, deleteListItems, deployAt, encryptData, getCrossChainServerInfo, getDaySummary, getForeignFee, getListItems, getServerConnectionHistory, getTxActivitySummary, getUserAccount, getUserWallet, getUserWalletInfo, getWalletBalance, joinGroup, publishMultipleQDNResources, publishQDNResource, removeForeignServer, saveFile, sendChatMessage, sendCoin, setCurrentForeignServer, updateForeignFee, voteOnPoll } from "./qortalRequests/get";
|
||||
import { storeData } from "./utils/chromeStorage";
|
||||
import { getData, storeData } from "./utils/chromeStorage";
|
||||
|
||||
|
||||
|
||||
@ -28,7 +28,7 @@ function setLocalStorage(key, data) {
|
||||
qortalRequestPermissions[key] = value;
|
||||
|
||||
// Save the updated object back to storage
|
||||
await setLocalStorage({ qortalRequestPermissions });
|
||||
await setLocalStorage('qortalRequestPermissions', qortalRequestPermissions );
|
||||
|
||||
console.log('Permission set for', key);
|
||||
} catch (error) {
|
||||
@ -53,7 +53,7 @@ function setLocalStorage(key, data) {
|
||||
// TODO: GET_FRIENDS_LIST
|
||||
// NOT SURE IF TO IMPLEMENT: LINK_TO_QDN_RESOURCE, QDN_RESOURCE_DISPLAYED, SET_TAB_NOTIFICATIONS
|
||||
|
||||
function setupMessageListener() {
|
||||
function setupMessageListenerQortalRequest() {
|
||||
window.addEventListener("message", async (event) => {
|
||||
const request = event.data;
|
||||
|
||||
@ -87,6 +87,7 @@ function setLocalStorage(key, data) {
|
||||
|
||||
case "ENCRYPT_DATA": {
|
||||
try {
|
||||
console.log('ENCRYPTDATA', request)
|
||||
const res = await encryptData(request.payload, event.source);
|
||||
event.source.postMessage({
|
||||
requestId: request.requestId,
|
||||
@ -98,7 +99,7 @@ function setLocalStorage(key, data) {
|
||||
event.source.postMessage({
|
||||
requestId: request.requestId,
|
||||
action: request.action,
|
||||
error: error.message,
|
||||
error: error?.message,
|
||||
type: "backgroundMessageResponse",
|
||||
}, event.origin);
|
||||
}
|
||||
@ -368,6 +369,7 @@ function setLocalStorage(key, data) {
|
||||
case "GET_WALLET_BALANCE": {
|
||||
try {
|
||||
const res = await getWalletBalance(request.payload, false, isFromExtension);
|
||||
console.log('ressss', res)
|
||||
event.source.postMessage({
|
||||
requestId: request.requestId,
|
||||
action: request.action,
|
||||
@ -612,5 +614,5 @@ function setLocalStorage(key, data) {
|
||||
}
|
||||
|
||||
// Initialize the message listener
|
||||
setupMessageListener();
|
||||
setupMessageListenerQortalRequest();
|
||||
|
||||
|
@ -180,174 +180,101 @@ const _voteOnPoll = async ({pollName, optionIndex, optionName}, isFromExtension)
|
||||
}
|
||||
};
|
||||
|
||||
function getFileFromContentScript(fileId, sender) {
|
||||
// Map to store resolvers and rejectors by requestId
|
||||
const fileRequestResolvers = new Map();
|
||||
|
||||
const handleFileMessage = (event) => {
|
||||
const { action, requestId, result, error } = event.data;
|
||||
|
||||
if (action === "getFileFromIndexedDBResponse" && fileRequestResolvers.has(requestId)) {
|
||||
const { resolve, reject } = fileRequestResolvers.get(requestId);
|
||||
fileRequestResolvers.delete(requestId); // Clean up after resolving
|
||||
|
||||
if (result) {
|
||||
resolve(result);
|
||||
} else {
|
||||
reject(error || "Failed to retrieve file");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", handleFileMessage);
|
||||
|
||||
function getFileFromContentScript(fileId) {
|
||||
console.log('handleGetFileFromIndexedDB', fileId)
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.tabs.sendMessage(
|
||||
sender.tab.id,
|
||||
{ action: "getFileFromIndexedDB", fileId: fileId },
|
||||
(response) => {
|
||||
if (response && response.result) {
|
||||
resolve(response.result);
|
||||
} else {
|
||||
reject(response?.error || "Failed to retrieve file");
|
||||
}
|
||||
}
|
||||
const requestId = `getFile_${fileId}_${Date.now()}`;
|
||||
console.log('handleGetFileFromIndexedDB', requestId)
|
||||
|
||||
fileRequestResolvers.set(requestId, { resolve, reject }); // Store resolvers by requestId
|
||||
console.log('handleGetFileFromIndexedDB', 'passed')
|
||||
|
||||
// Send the request message
|
||||
window.postMessage(
|
||||
{ action: "getFileFromIndexedDB", fileId, requestId },
|
||||
"*"
|
||||
);
|
||||
});
|
||||
}
|
||||
function sendToSaveFilePicker(data, sender) {
|
||||
console.log('handleGetFileFromIndexedDB', 'after', window.origin)
|
||||
|
||||
chrome.tabs.sendMessage(sender.tab.id, {
|
||||
action: "SHOW_SAVE_FILE_PICKER",
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
async function responseFromExtension() {
|
||||
return new Promise((resolve) => {
|
||||
|
||||
// Send message to the content script to check focus
|
||||
chrome.runtime.sendMessage({ action: "QORTAL_REQUEST_PERMISSION", payloa }, (response) => {
|
||||
|
||||
if (chrome.runtime.lastError) {
|
||||
resolve(false); // Error occurred, assume not focused
|
||||
} else {
|
||||
resolve(response); // Resolve based on the response
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function getUserPermission(payload: any, isFromExtension?: boolean) {
|
||||
function waitForWindowReady(windowId) {
|
||||
return new Promise((resolve) => {
|
||||
const checkInterval = setInterval(() => {
|
||||
chrome.windows.get(windowId, (win) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
clearInterval(checkInterval); // Stop polling if there's an error
|
||||
resolve(false);
|
||||
} else if (win.state === "normal" || win.state === "maximized") {
|
||||
clearInterval(checkInterval); // Window is ready
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
}, 100); // Check every 100ms
|
||||
});
|
||||
}
|
||||
|
||||
if(isFromExtension){
|
||||
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// Set a timeout for 1 second
|
||||
const timeout = setTimeout(() => {
|
||||
resolve(false);
|
||||
}, 30000);
|
||||
|
||||
// Send message to the content script to check focus
|
||||
chrome.runtime.sendMessage(
|
||||
{ action: "QORTAL_REQUEST_PERMISSION", payload, isFromExtension },
|
||||
(response) => {
|
||||
if (response === undefined) return;
|
||||
clearTimeout(timeout); // Clear the timeout if we get a response
|
||||
|
||||
if (chrome.runtime.lastError) {
|
||||
resolve(false); // Error occurred, assume not focused
|
||||
} else {
|
||||
resolve(response); // Resolve based on the response
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
await new Promise((res) => {
|
||||
const popupUrl = chrome.runtime.getURL("index.html?secondary=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) =>
|
||||
w.tabs &&
|
||||
w.tabs.some((tab) => tab.url && tab.url.startsWith(popupUrl))
|
||||
);
|
||||
if (existingPopup) {
|
||||
// If the popup exists but is minimized or not focused, focus it
|
||||
chrome.windows.update(existingPopup.id, {
|
||||
focused: true,
|
||||
state: "normal",
|
||||
});
|
||||
res(null);
|
||||
} else {
|
||||
// No existing popup found, create a new one
|
||||
chrome.system.display.getInfo((displays) => {
|
||||
// Assuming the primary display is the first one (adjust logic as needed)
|
||||
const primaryDisplay = displays[0];
|
||||
const screenWidth = primaryDisplay.bounds.width;
|
||||
const windowHeight = 500; // Your window height
|
||||
const windowWidth = 400; // Your window width
|
||||
|
||||
// Calculate left position for the window to appear on the right of the screen
|
||||
const leftPosition = screenWidth - windowWidth;
|
||||
|
||||
// Calculate top position for the window, adjust as desired
|
||||
const topPosition =
|
||||
(primaryDisplay.bounds.height - windowHeight) / 2;
|
||||
|
||||
chrome.windows.create(
|
||||
{
|
||||
url: popupUrl,
|
||||
type: "popup",
|
||||
width: windowWidth,
|
||||
height: windowHeight,
|
||||
left: leftPosition,
|
||||
top: 0,
|
||||
},
|
||||
async (newWindow) => {
|
||||
removeDuplicateWindow(popupUrl);
|
||||
await waitForWindowReady(newWindow.id);
|
||||
|
||||
res(null);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
await new Promise((res) => {
|
||||
// Timeout to handle no response scenario
|
||||
setTimeout(() => {
|
||||
chrome.runtime.sendMessage({
|
||||
action: "SET_COUNTDOWN",
|
||||
payload: 30,
|
||||
});
|
||||
res(true);
|
||||
}, 1000);
|
||||
});
|
||||
return new Promise((resolve) => {
|
||||
// Set a timeout for 1 second
|
||||
const timeout = setTimeout(() => {
|
||||
resolve(false);
|
||||
}, 30000);
|
||||
|
||||
// Send message to the content script to check focus
|
||||
chrome.runtime.sendMessage(
|
||||
{ action: "QORTAL_REQUEST_PERMISSION", payload },
|
||||
(response) => {
|
||||
if (response === undefined) return;
|
||||
clearTimeout(timeout); // Clear the timeout if we get a response
|
||||
|
||||
if (chrome.runtime.lastError) {
|
||||
resolve(false); // Error occurred, assume not focused
|
||||
} else {
|
||||
resolve(response); // Resolve based on the response
|
||||
}
|
||||
if (fileRequestResolvers.has(requestId)) {
|
||||
fileRequestResolvers.get(requestId).reject("Request timed out");
|
||||
fileRequestResolvers.delete(requestId); // Clean up on timeout
|
||||
}
|
||||
);
|
||||
}, 10000); // 10-second timeout
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function sendToSaveFilePicker(data) {
|
||||
window.postMessage({
|
||||
action: "SHOW_SAVE_FILE_PICKER",
|
||||
payload: data,
|
||||
}, "*");
|
||||
}
|
||||
|
||||
|
||||
const responseResolvers = new Map();
|
||||
|
||||
const handleMessage = (event) => {
|
||||
const { action, requestId, result } = event.data;
|
||||
console.log("Received message:", event);
|
||||
|
||||
// Check if this is the expected response action and if we have a stored resolver
|
||||
if (action === "QORTAL_REQUEST_PERMISSION_RESPONSE" && responseResolvers.has(requestId)) {
|
||||
// Resolve the stored promise with the result
|
||||
responseResolvers.get(requestId)(result || false);
|
||||
responseResolvers.delete(requestId); // Clean up after resolving
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", handleMessage);
|
||||
|
||||
|
||||
|
||||
async function getUserPermission(payload, isFromExtension) {
|
||||
return new Promise((resolve) => {
|
||||
const requestId = `qortalRequest_${Date.now()}`;
|
||||
responseResolvers.set(requestId, resolve); // Store resolver by requestId
|
||||
|
||||
// Send the request message
|
||||
window.postMessage(
|
||||
{ action: "QORTAL_REQUEST_PERMISSION", payload, requestId, isFromExtension },
|
||||
"*"
|
||||
);
|
||||
|
||||
// Optional timeout to handle no response scenario
|
||||
setTimeout(() => {
|
||||
if (responseResolvers.has(requestId)) {
|
||||
responseResolvers.get(requestId)(false); // Resolve with `false` if no response
|
||||
responseResolvers.delete(requestId);
|
||||
}
|
||||
}, 30000); // 30-second timeout
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export const getUserAccount = async () => {
|
||||
try {
|
||||
const wallet = await getSaveWallet();
|
||||
@ -366,7 +293,7 @@ export const encryptData = async (data, sender) => {
|
||||
let data64 = data.data64;
|
||||
let publicKeys = data.publicKeys || [];
|
||||
if (data.fileId) {
|
||||
data64 = await getFileFromContentScript(data.fileId, sender);
|
||||
data64 = await getFileFromContentScript(data.fileId);
|
||||
}
|
||||
if (!data64) {
|
||||
throw new Error("Please include data to encrypt");
|
||||
@ -633,7 +560,7 @@ export const publishQDNResource = async (data: any, sender, isFromExtension) =>
|
||||
throw new Error("Only encrypted data can go into private services");
|
||||
}
|
||||
if (data.fileId) {
|
||||
data64 = await getFileFromContentScript(data.fileId, sender);
|
||||
data64 = await getFileFromContentScript(data.fileId);
|
||||
}
|
||||
if (data.encrypt) {
|
||||
try {
|
||||
@ -669,7 +596,7 @@ export const publishQDNResource = async (data: any, sender, isFromExtension) =>
|
||||
const { accepted } = resPermission;
|
||||
if (accepted) {
|
||||
if (data.fileId && !data.encrypt) {
|
||||
data64 = await getFileFromContentScript(data.fileId, sender);
|
||||
data64 = await getFileFromContentScript(data.fileId);
|
||||
}
|
||||
try {
|
||||
const resPublish = await publishData({
|
||||
@ -853,7 +780,7 @@ export const publishMultipleQDNResources = async (data: any, sender, isFromExten
|
||||
continue;
|
||||
}
|
||||
if (resource.fileId) {
|
||||
data64 = await getFileFromContentScript(resource.fileId, sender);
|
||||
data64 = await getFileFromContentScript(resource.fileId);
|
||||
}
|
||||
if (data.encrypt) {
|
||||
try {
|
||||
@ -1108,7 +1035,8 @@ export const sendChatMessage = async (data, isFromExtension) => {
|
||||
isEncrypted: 1,
|
||||
isText: 1,
|
||||
});
|
||||
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({
|
||||
chatBytes: tx.chatBytes,
|
||||
@ -1154,7 +1082,8 @@ export const sendChatMessage = async (data, isFromExtension) => {
|
||||
// if (!hasEnoughBalance) {
|
||||
// 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({
|
||||
chatBytes: tx.chatBytes,
|
||||
@ -1277,8 +1206,7 @@ export const saveFile = async (data, sender, isFromExtension) => {
|
||||
blob,
|
||||
fileId,
|
||||
fileHandleOptions,
|
||||
},
|
||||
sender
|
||||
}
|
||||
);
|
||||
return true;
|
||||
} else {
|
||||
|
83
src/utils/indexedDB.ts
Normal file
83
src/utils/indexedDB.ts
Normal file
@ -0,0 +1,83 @@
|
||||
export async function handleGetFileFromIndexedDB(event) {
|
||||
try {
|
||||
const { fileId, requestId } = event.data;
|
||||
const db = await openIndexedDB();
|
||||
const transaction = db.transaction(["files"], "readonly");
|
||||
const objectStore = transaction.objectStore("files");
|
||||
|
||||
const getRequest = objectStore.get(fileId);
|
||||
|
||||
getRequest.onsuccess = async function (event) {
|
||||
if (getRequest.result) {
|
||||
const file = getRequest.result.data;
|
||||
|
||||
try {
|
||||
const base64String = await fileToBase64(file);
|
||||
|
||||
// Create a new transaction to delete the file
|
||||
const deleteTransaction = db.transaction(["files"], "readwrite");
|
||||
const deleteObjectStore = deleteTransaction.objectStore("files");
|
||||
const deleteRequest = deleteObjectStore.delete(fileId);
|
||||
|
||||
deleteRequest.onsuccess = function () {
|
||||
try {
|
||||
|
||||
window.postMessage(
|
||||
{ action: "getFileFromIndexedDBResponse", requestId, result: base64String },
|
||||
"*"
|
||||
);
|
||||
} catch (error) {
|
||||
console.log('error', error)
|
||||
}
|
||||
};
|
||||
|
||||
deleteRequest.onerror = function () {
|
||||
console.error(`Error deleting file with ID ${fileId} from IndexedDB`);
|
||||
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error converting file to Base64:", error);
|
||||
event.ports[0].postMessage({
|
||||
result: null,
|
||||
error: "Failed to convert file to Base64",
|
||||
});
|
||||
window.postMessage(
|
||||
{ action: "getFileFromIndexedDBResponse", requestId, result: null,
|
||||
error: "Failed to convert file to Base64"
|
||||
},
|
||||
"*"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.error(`File with ID ${fileId} not found in IndexedDB`);
|
||||
|
||||
window.postMessage(
|
||||
{ action: "getFileFromIndexedDBResponse", requestId, result: null,
|
||||
error: 'File not found in IndexedDB'
|
||||
},
|
||||
"*"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
getRequest.onerror = function () {
|
||||
console.error(`Error retrieving file with ID ${fileId} from IndexedDB`);
|
||||
|
||||
event.source.postMessage(
|
||||
{ action: "getFileFromIndexedDBResponse", requestId, result: null,
|
||||
error: 'Error retrieving file from IndexedDB'
|
||||
},
|
||||
event.origin
|
||||
);
|
||||
};
|
||||
} catch (error) {
|
||||
const { requestId } = event.data;
|
||||
console.error("Error opening IndexedDB:", error);
|
||||
event.source.postMessage(
|
||||
{ action: "getFileFromIndexedDBResponse", requestId, result: null,
|
||||
error: 'Error opening IndexedDB'
|
||||
},
|
||||
event.origin
|
||||
);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user