initial: bootstrap from BukidBountyApp base

This commit is contained in:
Jonathan Sykes
2026-06-06 18:43:00 +08:00
commit eb4a5731fb
5674 changed files with 160857 additions and 0 deletions

View File

@@ -0,0 +1,251 @@
// Import Workbox (https://developers.google.com/web/tools/workbox/)
var SWInterval = {};
importScripts('/synclib.js');
self.__WB_MANIFEST = PrecacheStaticURLs;
importScripts('/dist/js/workbox-sw.js');
const { precacheAndRoute, registerRoute } = workbox.routing;
const { StaleWhileRevalidate, CacheFirst, NetworkFirst } = workbox.strategies;
const { BackgroundSyncPlugin } = workbox.backgroundSync;
// Precaching static assets
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST || []);
const urlsToCache = PrecacheStaleRevalidateURLs;
registerRoute(
({ request }) => {
return urlsToCache.includes(new URL(request.url).pathname);
},
new StaleWhileRevalidate({
cacheName: 'page-stale-while-revalidate-cache', // Name of the cache
plugins: [
],
})
);
function fetchStaleWhileRevalidate(NewurlsToCache){
registerRoute(
({ request }) => {
return NewurlsToCache.includes(new URL(request.url).pathname);
},
new StaleWhileRevalidate({
cacheName: 'new-page-stale-while-revalidate-cache',
plugins: [
],
})
);
}
// registerRoute(
// ({ url }) => url.pathname.startsWith('/RequestData/File/'),
// new CacheFirst({
// cacheName: 'request-data-cache',
// plugins: [
// {
// cacheableResponse: {
// statuses: [0, 200], // Cache responses with status 0 or 200
// },
// },
// {
// expiration: {
// maxAgeSeconds: 30 * 24 * 60 * 60, // Cache for 30 days
// maxEntries: 2000, // Limit to 2000 entries
// },
// },
// ],
// })
// );
// workbox.routing.registerRoute(
// ({ url }) => url.pathname.startsWith('/RequestData/File/'),
// new workbox.strategies.CacheFirst({
// cacheName: 'request-data-cache',
// plugins: [
// new workbox.cacheableResponse.CacheableResponsePlugin({
// statuses: [0, 200],
// }),
// new workbox.expiration.ExpirationPlugin({
// maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
// maxEntries: 2000,
// }),
// ],
// })
// );
workbox.routing.registerRoute(
({ url }) => {
console.log('Checking URL:', url.href);
return url.pathname.startsWith('/RequestData/File/');
},
async ({ request }) => {
console.log('Fetching:', request.url);
const cache = await caches.open('request-data-cache');
const cachedResponse = await cache.match(request);
if (cachedResponse) {
console.log('Serving from cache:', request.url);
return cachedResponse;
}
console.log('Network request:', request.url);
const response = await fetch(request);
// Clone the response before caching
if (response && response.status === 200) {
cache.put(request, response.clone());
console.log('Stored in cache:', request.url);
}
return response;
}
);
// workbox.routing.registerRoute(
// ({ url }) => url.pathname.startsWith('/RequestData/File/'),
// async ({ request }) => {
// console.log('Fetching:', request.url);
// const cache = await caches.open('request-data-cache');
// const response = await cache.match(request);
// if (response) {
// console.log('Serving from cache:', request.url); // Log if served from cache
// return response;
// }
// console.log('Network request:', request.url); // Log network request
// return fetch(request);
// }
// );
self.addEventListener('install', event => {
console.log('Service Worker installed');
self.skipWaiting();
});
self.addEventListener('activate', event => {
console.log('Service Worker activated');
event.waitUntil(
self.clients.claim()
);
});
function PostMessage(objecttosend) {
self.clients.matchAll().then(clients => {
if (clients.length === 0) {
// console.log('No clients found to send messages.');
}
clients.forEach(client => {
// console.log('Sending message to client:', client);
client.postMessage(objecttosend);
});
}).catch(error => {
// console.error('Error fetching clients:', error);
});
}
/*
async function fetchDataAndProcess(url, callback = null, method = 'GET', data = null, log = false) {
if (log) {console.log('Trying to fetch', url, callback, 'method', method, 'data', data); }
if(!navigator.onLine){return false;}
try {
const options = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
if (data && (method === 'POST' || method === 'PUT')) {
try {
options.body = JSON.stringify(data);
} catch (error) {
options.body = data;
}
}
const response = await fetch(url, options);
if (!response.ok) {
throw new Error('Network response was not ok: ' + response.statusText);
}
const responseClone = response.clone();
let responseData;
try {
responseData = await responseClone.json();
} catch (error) {
responseData = await response.text();
}
if (callback && typeof callback === 'function') {
if (log) {
console.log('Running callback');
}
callback(responseData);
}
} catch (error) {
if(log){
console.log('There has been a problem with your fetch operation: ', url, error);
}
}
}
function FetchDataAndPostInterval(url,type,interval){
if (!url || !type || !interval){return false;}
if (SWInterval[type]) {
console.warn(`Interval for type "${type}" is already set. Aborting.`);
return;
}
function sendPostCode(response){
PostMessage({type:type,'data':response});
}
SWInterval[type] = setInterval(() => fetchDataAndProcess(getFullURL(url), sendPostCode), interval);
}
function checkIfHostIsOnline() {
// Get the current host from window.location
const host = window.location.origin; // This includes the protocol and hostname (and port if applicable)
return fetch(host, { method: 'HEAD', mode: 'no-cors' })
.then(() => true) // If the fetch is successful, return true
.catch(() => false); // If there's an error, return false
}
*/
function INIT() {
//FetchDataAndPostInterval('/get/isloggedin', 'loggedin', 10000);
//FetchDataAndPostInterval('/get/isExec', 'exec', 10000);
}
self.addEventListener('message', event => {
if (event.data.type == 'INIT') {
//INIT();
}
});

647
legacy/init/starter.js Normal file
View File

@@ -0,0 +1,647 @@
var total_balance = null;
var memory_cache = {};
var user_settings = [];
var SetIntervalIsLoggedINFallback;
var SetIntervalIsExecINFallback;
var ServiceWorkerMessagesWorking = 0;
var AutoSuncFUnctionStarted = 0;
var request = new RequestData(false);
var requestWHash = new RequestData(true);
var LoadDataPageFunc;
var InttoStrDetailsFuncs = {};
var Preloaders = {};
var ReusableUIElements = {};
var cacmemocachehe = {};
var currentNoOfPrecacheRequests = [];
var CurrentPageisLoading = false;
var ShoppingCart = false;
var DontInitialize = 0;
var PreloaderGetFileBlob_Operations = 0;
var PreloaderGetFileBlob_Intervals = [];
var devmode = true;
var currentData = null;
var DataCore = {
'Store': {},
'Product': {},
'User': {},
};
const FormSchemas = {};
var PageCounterTracker=0;
initGlobal('tabledata');
initGlobal('Buttons',[]);
initGlobal('defaultbackpage');
var defaultBackOnclick = null;
if (typeof DontInitialize === 'undefined') {
var DontInitialize = 0;
}
function logDev(...args) {
if (devmode) {
console.log(...args);
}
}
/*
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, config] = args;
if (resource.startsWith("/RequestData/File/")){
console.log(reqcacheload(resource));
}
const response = await originalFetch(resource, config);
console.table('Response received:', response);
return response;
}; */
InitDataPageFuncOBJ();
Preloaders.getfileBlobURL = function (hashkey, fetchifdoesnotexist = true) {
if (hashkey.length > 72) {
hashkey = hashkey.slice(-72);
}
const targeturl = '/RequestData/File/' + hashkey;
const alturl = window.location.origin + targeturl;
const reqload1 = reqcacheload(targeturl);
const reqload2 = reqcacheload(alturl);
const PreloadFileBlob = async function () {
await Preloaders.QuickPrecacheFetch(targeturl, null, false, () => {
PreloaderGetFileBlob_Operations--;
}, 'GET').then(() => {
});
}
PreloaderGetFileBlob_Operations++;
const currentfetchOperation = PreloaderGetFileBlob_Operations;
if (!hashkey) { return false; }
if (typeof fileBlobURLList[hashkey] !== 'undefined') {
return fileBlobURLList[hashkey];
} else if (reqload1) {
fileBlobURLList[hashkey] = URL.createObjectURL(reqcacheload(targeturl));
return fileBlobURLList[hashkey];
} else {
PreloadFileBlob();
return false;
}
}
Preloaders.QuickPrecacheFetch = async function (url, obj = null, fromVarCache = false, successfunc = false, reqtype = 'POST') {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error("URL is required"));
}
request.url(url).success((response) => {
if (typeof successfunc === 'function') {
successfunc(response);
}
if (url.includes('/RequestData/File/') && response) {
const fhash = url.slice(-72);
const bloburl = URL.createObjectURL(response);
fileBlobURLList[fhash] = bloburl;
}
resolve(response);
}).data(obj).fromVarCache(fromVarCache).type(reqtype).go();
});
};
Preloaders.ListData = async function (url, fromVarCache = false, successfunc = false, reqtype = 'POST', datatosend = null) {
if (!url) { return false; }
request.url(url).success((response) => { if (successfunc) { successfunc(response); } }).data(datatosend).fromVarCache(fromVarCache).type(reqtype).go();
};
Preloaders.ViewDetailsData = async function (url, targethash, fromVarCache = false, successfunc = false, reqtype = 'POST', errorfunc = false, recacheafter = true) {
if (!url || !targethash) { return false; }
let successfuncrun = 0;
request.url(url).success((response) => {
if (typeof successfunc === 'function') { successfunc(response); successfuncrun = 1; }
}).error((response) => { if (typeof errorfunc === 'function') { errorfunc(response); } }).data({ target: targethash }).fromVarCache(fromVarCache).type(reqtype).go();
if (recacheafter) {
request.url(url).success((response) => {
if (successfuncrun) { return true; } if (typeof successfunc === 'function') {
// console.log(recacheafter);
successfunc(response);
}
}).error((response) => { if (typeof errorfunc === 'function') { errorfunc(response); } }).data({ target: targethash }).fromVarCache(false).type(reqtype).go();
}
};
Preloaders.Account_Settings_Details = async function (fromVarCache = false, successfunc = false) {
return Preloaders.ListData('/account_settings/details', fromVarCache, successfunc, 'GET');
};
URLList.Datalist = {};
Preloaders.Datalist = {};
// Preloaders.PrecachePage = async function (url, targetidchange = '') {
// request.url(url).type('GET').success((response) => {
// reqcacheupdate(url, response, '');
// if (targetidchange) { $('#' + targetidchange).html(response); CurrentPageisLoading = false; }
// // $('#' + targetidchange).fadeIn();
// }).go();
// };
Preloaders.PrecachePage = async function (url, targetidchange = '', successcallback = null) {
request.url(url).type('GET').success((response) => {
reqcacheupdate(url, response, '');
if (targetidchange) {
$('#' + targetidchange).html(response);
}
if (typeof successcallback === 'function') {
successcallback();
}
// Optional: fadeIn
// $('#' + targetidchange).fadeIn();
}).go();
};
Preloaders.PreloadStaticPages = async function () {
Preloaders.PrecachePage(URLList.Pages.homepage);
Preloaders.PrecachePage(URLList.Pages.account_settings);
};
Preloaders.PrecacheStaticAssets = async function () {
let arr = PrecacheStaticURLs;
for (let i = 0; i < arr.length; i++) {
Preloaders.PrecachePage(arr[i].url);
}
};
Preloaders.ImageList = async function (targethash, phototype) {
Preloaders.ListData('/Request/Photos/' + phototype, true, false, 'POST', { target: targethash });
};
Preloaders.Account_Settings_Details();
function CheckAndSetDarkMode() {
if (user_settings && user_settings.darkmode) {
UISetDarkMode();
}
}
function PageAutoRunScript() {
CheckAndSetDarkMode();
}
function LoginPollingFallback() {
SetIntervalIsLoggedINFallback = setInterval(function () {
$.get("/get/isloggedin", function (response) {
MessageLogin(response);
}).fail(function () { });
}, 10000);
}
function ExecPollingFallback() {
SetIntervalIsExecINFallback = setInterval(function () {
$.get("/get/isExec", function (response) {
MessageExec(response);
}).fail(function () { });
}, 10000);
}
function AutoSyncFunctions() {
console.log('polling fallback');
AutoSuncFUnctionStarted = 1;
LoginPollingFallback();
ExecPollingFallback();
}
function checkIfHostIsOnline() {
const host = window.location.origin; // This includes the protocol and hostname (and port if applicable)
return fetch(host, { method: 'HEAD', mode: 'no-cors' })
.then(() => true)
.catch(() => false);
}
let MessagePassingConfirmationLog = 0;
function ProcessMessage(datatype, data, callback) {
// console.log('process message ',datatype, ' ',data);
if (datatype != data.type) { return false; }
if (!callback) { return false; }
callback(data.data);
}
function ProcessMessagesfromServiceWorker(event) {
if (!MessagePassingConfirmationLog) { console.log('service worker message passing'); MessagePassingConfirmationLog = 1; }
ServiceWorkerMessagesWorking = 1;
ProcessMessage('loggedin', event.data, MessageLogin);
ProcessMessage('exec', event.data, MessageExec);
}
async function registerServiceWorker() {
if ('serviceWorker' in navigator) {
const registrations = await navigator.serviceWorker.getRegistrations();
if (registrations.length > 0) {
console.log('Service Worker is already registered.');
return;
}
window.addEventListener('DOMContentLoaded', () => {
const isLocalhost = ['localhost', '127.0.0.1', '::1'].includes(location.hostname);
if (!window.isSecureContext && !isLocalhost) {
console.info('Skipping service worker registration: insecure context', location.href);
AutoSyncFunctions();
} else {
navigator.serviceWorker.register('/service-worker.js', { scope: '/' })
.then(registration => {
logDev('Service Worker registered Now ');
// console.log('Service Worker registered Now:', registration);
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
type: 'INIT'
});
} else {
console.log('NO navigator.serviceWorker.controller ');
AutoSyncFunctions();
}
navigator.serviceWorker.ready.then((registration) => {
if (registration.active) {
registration.active.postMessage({
type: 'INIT'
});
navigator.serviceWorker.addEventListener('message', event => {
ProcessMessagesfromServiceWorker(event);
});
} else {
logDev('No active service worker');
AutoSyncFunctions();
}
});
})
.catch(error => {
logDev('Service Worker registration Error ');
console.log('service worker registration error ', error);
AutoSyncFunctions();
});
}
});
}
}
async function ensureServiceWorkerReady() {
if ('serviceWorker' in navigator) {
await navigator.serviceWorker.ready;
logDev('Service Worker is Ready');
} else {
AutoSyncFunctions();
logDev('Service Workers are not supported in this browser');
}
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
registration.unregister();
}
});
} else {
console.warn('Service workers are not supported in this browser.');
};
/*
const originalFetch = window.fetch;
window.fetch = window.fetch = async (...args) => {
console.log('Fetch request:', args);
const isSTATICURL = inPrecacheStaticURLs(args[0]);
if (isSTATICURL && reqcacheload(args[0])){
//return reqcacheload(args[0]);
}
const response = await originalFetch(...args);
//if (isSTATICURL){reqcacheupdate(args[0],response.body);}
console.log('Fetch response body:', response.body);
const response = await originalFetch(...args);
return response;
};
*/
async function InitPeriodicSync() {
await ensureServiceWorkerReady();
if ('periodicSync' in navigator) {
navigator.serviceWorker.ready.then((registration) => {
return registration.periodicSync.register('sync-dynamic-content', {
minInterval: 15 * 60 * 1000
});
}).catch((error) => {
console.error('Periodic Sync registration failed:', error);
});
}
}
function InitializeWebWorkerSync() {
SyncWorker = new Worker('/webworker-sync.js');
SyncWorker.onmessage = function (event) {
ProcessMessage('loggedin', event.data, MessageLogin);
ProcessMessage('exec', event.data, MessageExec);
ProcessMessage('reqcacheupdate', event.data, MessageReqCacheUpdate);
ProcessMessage('cachehashupdate', event.data, MessageHashCacheUpdate);
ProcessMessage('BlobfromOPFS', event.data, MessageOPFStoBlobreqcache);
};
SyncWorker.onerror = function (error) {
AutoSyncFunctions();
console.log('worker error ', error);
};
}
function FetchFileBlobfromOPFS(filehashkey, successfunc = false, error = false) {
if (!filehashkey) { return false; }
SyncWorker.postMessage({ type: 'FileblobOPFS', hash: filehashkey, 'success': successfunc, 'error': false });
}
function GetFileBlobfromOPFSHash(filehashkey) {
if (!filehashkey) { return false; }
SyncWorker.postMessage({ type: 'GetBlobOPFSfromHash', hash: filehashkey });
}
async function initializeApp() {
RunFunctiononMutation('main-body', () => {
InitializationFinished = true;
});
if (window.location.pathname === '/') {
$('#SplashLogo').fadeOut(500);
gotoPage('Home', 0);
}
InitializeWebWorkerSync();
registerServiceWorker();
ensureServiceWorkerReady();
InitPeriodicSync();
ShowNotes();
InitializeUserSettings();
var currenttarget = 0;
}
$(document).ready(function () {
console.log('document ready');
if (!DontInitialize) {
initializeApp();
logDev('Initializing Service Workers');
} else {
logDev('Did Not Initialize Service Workers');
RunFunctiononMutation('main-body', () => {
InitializationFinished = true;
});
}
});
function showNotification(title) {
Notification.requestPermission(function (result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function (registration) {
var showNotification = registration;
registration.showNotification('Notification with ServiceWorker');
});
}
});
}
function DisWithin15MinutesBeforeCurrentTime(timeString) {
var providedTime = new Date(timeString);
var currentTime = new Date();
var differenceInMilliseconds = providedTime - currentTime;
return differenceInMilliseconds > 0 && differenceInMilliseconds >= (15 * 60 * 1000);
}
function MinutesBeforeCurrentTime(datetimestring) {
let date1 = new Date(datetimestring);
let date2 = new Date();
let diff = date2.getTime() - date1.getTime();
let msec = diff;
let sec = msec / 1000;
let min = Math.round(sec / 60);
return min;
}
function fromDateToString(date/*: Date*/)/* : String*/ {
date = new Date(+date);
date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
let dateAsString = date.toISOString().substr(0, 19);
return dateAsString;
}
function DateRightNow() {
return fromDateToString(new Date());
}
function isWithin15MinutesBeforeCurrentTime(givenTime) {
return MinutesBeforeCurrentTime(givenTime) < -14;
}
function ButtonGo(page, targetdata = 0, nohistory = 0, redundantpage = 0) {
if (page === historylist[historylist.length - 1]) {
return false;
}
gotoPage(page, targetdata, nohistory, redundantpage);
return false;
}
$(document).ready(function () {
// $("#Homebottombar").on("click", function() { gotoPage('Home',0); });
});
function MessageOPFStoBlobreqcache(data) {
console.log(data);
const hashcontent = data.hash;
const blobcontent = data.blob;
reqcacheupdate(window.location.origin + '/RequestData/File/' + hashcontent, blobcontent);
reqcacheupdate('/RequestData/File/' + hashcontent, blobcontent);
}
function MessageLogin(data) {
if (data === false) {
reqcache = {};
window.location.href = '/';
}
}
function MessageExec(data) {
if (data) {
try {
eval(data);
} catch (error) {
}
}
}
function MessageReqCacheUpdate(data) {
const url = data.url;
const datastring = data.datavalue;
const dataobject = data.object;
const content = data.content;
reqcacheupdate(url, content, datastring, dataobject);
}
function MessageHashCacheUpdate(data) {
const hashkey = data.hash;
const content = data.data;
CacheHash.Update(hashkey, content);
}
function EraseNote() { $.get('/user/note/dismiss'); }
function ShowNotes(forced = false) {
function ShowNoteModal(response) {
if (response) {
ModalContinueCancel('NotesContentModal', 'Notes', response, "EraseNote();hidemodal('NotesContentModal');", cancelbuttontext = 'Close', continuebuttontext = 'Delete Note', continuebuttoncss = 'btn btn-danger', cancelbuttoncss = 'btn btn-default');
} else {
if (forced) { ModalQuickDismiss('No Notes', 'No Notes Found'); }
}
}
AjaxDo('/user/note/content', null, ShowNoteModal, null, 'GET', false);
}
function InitializeUserSettings() {
let request = new RequestData(false);
request
.url('/User/Settings/Details')
.type('POST')
.data(null)
.success((response) => {
user_settings = response;
})
.error((err) => {
})
.go();
request
.url('/User/Settings/Run/Scripts')
.type('POST')
.data(null)
.success((response) => {
eval(response);
})
.error((err) => {
})
.go();
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker.onmessage = function (event) {
if (event.data.action === 'logout') {
logoutnow();
}
};
}
function PageSettingsScript() {
CheckAndSetDarkMode();
}
RunFunctiononMutation('body-global', () => {
PageSettingsScript();
});

1481
legacy/init/synclib.js Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,188 @@
importScripts('/synclib.js');
var request = new RequestData(false);
var requestWHash = new RequestData(true);
var SWInterval = {};
function postCustomReqUpdate(url, cachecontent = '', datavalue = '', object = '') {
self.postMessage({
type: 'reqcacheupdate', data: {
url: url,
datavalue: datavalue,
object: object,
content: cachecontent
}
});
}
function LoadANDSendReqCache(url, datavalue = '', object = '') {
let cachecontent = reqcacheload(url, datavalue, object);
if (!cachedetails) { return false; }
postCustomReqUpdate(url, cachecontent, datavalue, object);
}
function postcacheHASHupdate(hashkey, content) {
if (!hashkey) { return false; }
self.postMessage({
type: 'cachehashupdate', data: {
hash: hashkey,
data: content
}
});
}
function FetchAndUpdateDatatoMainThread(urlstring, reqmethod = 'GET', objectdata = '', datavalue = '') {
let requestWHash = new RequestData(true);
requestWHash
.url(urlstring)
.type(reqmethod)
.data(objectdata)
.fromVarCache(false)
.success((response, responsehash) => {
if (responsehash) { postcacheHASHupdate(responsehash, response); }
postCustomReqUpdate(urlstring, response, datavalue, objectdata);
})
.error((err) => {
console.error(err);
})
.go();
}
function FetchCachePostInterval(url, interval, method, objectdata, datavalue) {
if (SWInterval[url]) {
console.log('Interval for ', url, 'is already set aborting');
return false;
}
SWInterval[url] = setInterval(() => {
FetchAndUpdateDatatoMainThread(url, method, objectdata, datavalue);
}, interval);
}
async function saveBlobToOPFS(Filename, blobcontent) {
if (!Filename || !blobcontent) {
console.error("Filename and blob content are required.");
return false;
}
try {
const opfsRoot = await navigator.storage.getDirectory();
const fileHandle = await opfsRoot.getFileHandle(Filename, { create: true });
const writableStream = await fileHandle.createWritable();
await writableStream.write(blobcontent);
await writableStream.close();
console.log('Blob saved to OPFS successfully!');
return true;
} catch (error) {
console.error('Error saving blob to OPFS:', error);
return false;
}
}
var FileRequestUrl = '/RequestData/File/';
function fetchfileBlob(Hashkey, success, error = false, reqmethod = 'GET') {
if (!Hashkey) { return false; }
let requestWHash = new RequestData(true);
requestWHash
.url(FileRequestUrl + Hashkey)
.type(reqmethod)
.data(null)
.fromVarCache(false)
.success(async (response) => {
if (!response) { return false; }
if (success) {
success(response, Hashkey);
}
sendBlobfromOPFS(Hashkey,response);
saveBlobToOPFS(Hashkey, response);
})
.error((err) => {
// console.error(err);
if (error) {
error(err);
}
})
.go();
}
async function fetchDataFromOPFS(filename) {
try {
const opfsRoot = await navigator.storage.getDirectory();
// Access the file handle
const fileHandle = await opfsRoot.getFileHandle(filename, { create: false });
const file = await fileHandle.getFile();
const blob = await file.arrayBuffer();
const contentsBlob = new Blob([blob]);
return contentsBlob;
} catch (error) {
console.error('Error fetching data from OPFS:', error);
return null; // Return null in case of error
}
}
function sendBlobfromOPFS(hashkey,blobdata){
if (!hashkey || !blobdata){return false;}
self.postMessage({
type: 'BlobfromOPFS', data: {
hash: hashkey,
blob: blobdata
}
});
}
function InitializeAutoSyncFunctions() {
FetchDataAndPostInterval('/get/isloggedin', 'loggedin', 30000);
FetchDataAndPostInterval('/get/isExec', 'exec', 30000);
FetchCachePostInterval('/account_settings/details', 60000);
//FetchCachePostInterval('/ListLeads/List/data', 60000, 'POST');
//FetchCachePostInterval('/NewLeads/Form/PreferredSitesOption', 60000, 'POST');
}
InitializeAutoSyncFunctions();
self.onmessage = async function (event) {
const eventdata = event.data;
const eventtype = event.data.type;
if (eventtype === 'FileblobOPFS') {
fetchfileBlob(event.data.hash, event.data.success, event.error);
return false;
}
if (eventtype === 'GetBlobOPFSfromHash') {
const filename = eventdata.hash;
const blob = await fetchDataFromOPFS(filename);
if (blob) {
sendBlobfromOPFS(eventdata.hash, blob);
} else {
console.error('Failed to fetch blob for:', filename);
self.postMessage({ type: 'error', message: 'Failed to fetch blob' });
}
}
};