Revert "Fix bug with clicking search suggestions, start working on proper API for hooking into the service worker."

This reverts commit fdae47c9b3.
This commit is contained in:
wearrrrr 2024-04-22 18:55:29 -05:00
parent 91488e88f5
commit 93d48c7277
10 changed files with 44 additions and 22760 deletions

View file

@ -51,7 +51,7 @@ app.use(compression({ threshold: 0, filter: () => true }));
app.use(cookieParser()); app.use(cookieParser());
// Set process.env.MASQR_ENABLED to "true" to enable masqr protection. // Set process.env.MASQR_ENABLED to "true" to enable masqr protection.
if (MASQR_ENABLED == "true") { if (process.env.MASQR_ENABLED == "true") {
console.log(chalk.gray("Starting Masqr...")); console.log(chalk.gray("Starting Masqr..."));
app.use(await masqrCheck({ whitelist: whiteListedDomains, licenseServer: LICENSE_SERVER_URL })); app.use(await masqrCheck({ whitelist: whiteListedDomains, licenseServer: LICENSE_SERVER_URL }));
} }

View file

@ -0,0 +1 @@
console.log("Hello World!");

View file

@ -1,34 +0,0 @@
let lowes = [];
async function loadLowes() {
await fetch("/marketplace/adblock/peterlowes.json")
.then(response => response.json())
.then(data => {
data.rules.forEach((rule) => {
lowes.push(rule["remote-domains"]);
});
});
console.log("Loaded Peter Lowes' List!");
console.log(lowes);
}
loadLowes();
function registerFetchListener() {
self.addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
console.log(event.request.url);
if (lowes.some((lowe) => __uv$config.decodeUrl(event.request.url).includes(lowe))) {
return new Response("Blocked by Peter Lowes", {status: 403});
}
if (event.request.url.startsWith(location.origin + __uv$config.prefix)) {
return await uv.fetch(event);
}
return await fetch(event.request);
})()
);
});
}
registerFetchListener();

File diff suppressed because it is too large Load diff

View file

@ -7,27 +7,13 @@ importScripts(__uv$config.sw);
const uv = new UVServiceWorker(); const uv = new UVServiceWorker();
async function loadHooks() { self.addEventListener("fetch", (event) => {
const db = await new Promise((resolve, reject) => { event.respondWith(
const request = indexedDB.open("AluDB", 1); (async () => {
request.onsuccess = () => resolve(request.result); if (event.request.url.startsWith(location.origin + __uv$config.prefix)) {
request.onerror = reject; return await uv.fetch(event);
});
const transaction = db.transaction("InstalledExtensions", "readwrite");
const objectStore = transaction.objectStore("InstalledExtensions");
const extensions = await new Promise((resolve, reject) => {
const request = objectStore.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = reject;
});
extensions.forEach((extension) => {
if (extension.serviceWorkerExtension) {
// Load the base64 encoded script contents;
importScripts(`data:text/plain;base64,${extension.script}`);
} }
return await fetch(event.request);
})()
);
}); });
}
loadHooks();

View file

@ -168,7 +168,6 @@
topbar.style.pointerEvents = "auto"; topbar.style.pointerEvents = "auto";
document.body.style.overflow = "hidden"; document.body.style.overflow = "hidden";
iframe.addEventListener("load", setActive); iframe.addEventListener("load", setActive);
iframe.addEventListener("load", loadExtensionScripts);
closeButton.onclick = () => { closeButton.onclick = () => {
iframe.style.opacity = "0"; iframe.style.opacity = "0";
topbar.style.opacity = "0"; topbar.style.opacity = "0";
@ -177,7 +176,7 @@
document.body.style.overflow = "auto"; document.body.style.overflow = "auto";
iframe.classList.remove("active"); iframe.classList.remove("active");
iframe.removeEventListener("load", setActive); iframe.removeEventListener("load", setActive);
iframe.removeEventListener("load", loadExtensionScripts);
setTimeout(() => { setTimeout(() => {
iframe.src = "about:blank"; iframe.src = "about:blank";
}, 500); }, 500);
@ -228,7 +227,6 @@
}, 200); }, 200);
} }
window.loadFormContent = loadContent; window.loadFormContent = loadContent;
window.loadSelectedTransport = loadSelectedTransportScript;
function isUrl(val = "") { function isUrl(val = "") {
if (/^http(s?):\/\//.test(val) || (val.includes(".") && val.substr(0, 1) !== " ")) return true; if (/^http(s?):\/\//.test(val) || (val.includes(".") && val.substr(0, 1) !== " ")) return true;

View file

@ -10,7 +10,6 @@ declare global {
decodeUrl: (url: string) => string; decodeUrl: (url: string) => string;
}; };
loadFormContent: Function | null; loadFormContent: Function | null;
loadSelectedTransport: Function | null;
} }
} }

View file

@ -3,7 +3,12 @@
"title": "Adblocker", "title": "Adblocker",
"version": "0.0.1", "version": "0.0.1",
"image": "/marketplace/adblock/adblock.png", "image": "/marketplace/adblock/adblock.png",
"script": "/marketplace/adblock/adblocker.sw.js", "script": "/marketplace/adblock/adblocker.js"
"serviceWorkerExtension": true },
"dev.wearr.adblock2": {
"title": "Adblocker2",
"version": "0.0.2",
"image": "/marketplace/adblock/adblock.png",
"script": "/marketplace/adblock/adblocker.js"
} }
} }

View file

@ -82,7 +82,6 @@ export function getStaticPaths() {
await registerSW(); await registerSW();
async function sendAPIRequest(urlInput: HTMLInputElement, searchSuggestions: HTMLDivElement) { async function sendAPIRequest(urlInput: HTMLInputElement, searchSuggestions: HTMLDivElement) {
try {
if (!urlInput) throw new Error("urlInput is null"); if (!urlInput) throw new Error("urlInput is null");
if (!searchSuggestions) throw new Error("searchSuggestions is null"); if (!searchSuggestions) throw new Error("searchSuggestions is null");
let url = urlInput.value; let url = urlInput.value;
@ -97,8 +96,8 @@ export function getStaticPaths() {
suggestionElement.innerText = suggestion.phrase; suggestionElement.innerText = suggestion.phrase;
suggestionElement.addEventListener("click", async () => { suggestionElement.addEventListener("click", async () => {
urlInput.value = suggestion.phrase; urlInput.value = suggestion.phrase;
if (window.loadSelectedTransport) await window.loadSelectedTransport() // I can't be bothered to extend the window object, so I'm just going to use any
if (window.loadFormContent) window.loadFormContent(suggestion.phrase); (window as any).loadFormContent();
}); });
searchSuggestions.appendChild(suggestionElement); searchSuggestions.appendChild(suggestionElement);
}); });
@ -109,9 +108,6 @@ export function getStaticPaths() {
urlInput.classList.add("search-results"); urlInput.classList.add("search-results");
searchSuggestions.style.opacity = "1"; searchSuggestions.style.opacity = "1";
} }
} catch {
}
} }
function addEventListeners() { function addEventListeners() {

View file

@ -1,226 +0,0 @@
---
import { STATIC_PATHS } from "@i18n/utils";
import Layout from "src/layouts/Layout.astro";
import marketplace from "../../json/marketplace.json";
export const getStaticPaths = () => {
return STATIC_PATHS;
};
type MarketplaceItem = {
title: string;
version: string | number;
image: string;
script: string;
};
---
<Layout title="Marketplace | Alu">
<div id="main-content">
<h1 class="title-text">Marketplace</h1>
<p class="title-desc">Install custom userscripts and themes for Alu.</p>
<div class="marketplace-ext-grid">
{
Object.keys(marketplace).map((mp_item) => {
const item = (marketplace as { [key: string]: MarketplaceItem })[mp_item];
const slug = mp_item;
return (
<div class="marketplace-item" data-slug={slug}>
<img class="marketplace-item-image" src={item.image} alt={`${item.title} Logo`} />
<div class="marketplace-item-title">{item.title}</div>
<button class="marketplace-install-btn" data-slug={slug} data-title={item.title}>
Install
</button>
</div>
);
})
}
</div>
</div>
</Layout>
<script>
import "notyf/notyf.min.css";
import { Notyf } from "notyf";
import marketplaceManifest from "../../json/marketplace.json";
const installButtons = document.getElementsByClassName(
"marketplace-install-btn"
) as HTMLCollectionOf<HTMLButtonElement>;
Array.from(installButtons).forEach((btn) => {
btn.addEventListener("click", async (event) => {
const ele = event.target as HTMLButtonElement;
const title = ele.dataset.title;
let notification = new Notyf({
duration: 999999,
position: { x: "right", y: "bottom" },
dismissible: true,
ripple: true,
});
let installNotif = notification.success(`Installing ${title}...`);
if (ele.dataset.slug) {
let obj = await getMarketplaceObj(ele.dataset.slug);
installExtension(obj, ele.dataset.slug)
.then((code) => {
let notifMessage = "";
let timeout = 2000;
switch (code) {
case 0:
notifMessage = `Installed ${title} Successfully!`;
break;
case 1:
notifMessage = `${title} is already installed!`;
timeout = 0;
break;
case -1:
// We should NEVER get here, but just in case.
notifMessage = `Failed to install ${title}!`;
break;
}
setTimeout(() => {
notification.dismiss(installNotif);
notification.options.duration = 2000;
notification.success(notifMessage);
notification.options.duration = 999999;
}, timeout);
})
.catch(() => {
notification.dismiss(installNotif);
notification.options.duration = 2000;
notification.error(`Failed to install ${title}!`);
notification.options.duration = 999999;
});
}
});
});
type MarketplaceItem = {
title: string;
version: string | number;
image: string;
script: string;
scriptBtoa: string | null;
serviceWorkerExtension?: boolean;
};
async function getMarketplaceObj(slug: string): Promise<ExtensionMetadata> {
const manifest = (marketplaceManifest as unknown as { [key: string]: MarketplaceItem })[slug];
manifest.scriptBtoa = btoa(await fetch(manifest.script).then((res) => res.text()));
return manifest;
}
interface ExtensionMetadata {
title: string;
version: string | number;
script: string;
scriptBtoa: string | null;
serviceWorkerExtension?: boolean;
}
enum EXT_RETURN {
INSTALL_SUCCESS = 0,
INSTALL_FAILED = -1,
ALREADY_INSTALLED = 1,
}
async function installExtension(ext: ExtensionMetadata, slug: string) {
return new Promise(async (resolve, reject) => {
const request = window.indexedDB.open("AluDB", 1);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains("InstalledExtensions")) {
db.createObjectStore("InstalledExtensions", { keyPath: "slug" });
}
};
request.onsuccess = async (event) => {
const db = (event.target as IDBOpenDBRequest).result;
const transaction = db.transaction("InstalledExtensions", "readwrite");
const store = transaction.objectStore("InstalledExtensions");
const extensionObject = {
slug: slug,
title: ext.title,
version: ext.version,
script: ext.scriptBtoa,
serviceWorkerExtension: ext.serviceWorkerExtension,
};
// Check if the key already exists in the IDB
let slugCheck = store.get(slug);
slugCheck.onsuccess = async () => {
if (slugCheck.result != undefined) {
resolve(EXT_RETURN.ALREADY_INSTALLED);
} else {
const addRequest = store.add(extensionObject);
addRequest.onerror = () => {
console.error(`Error installing ${slug}!`);
reject(EXT_RETURN.INSTALL_FAILED);
};
addRequest.onsuccess = () => {
resolve(EXT_RETURN.INSTALL_SUCCESS);
};
}
};
slugCheck.onerror = () => {
console.error("Error checking install status!");
reject(EXT_RETURN.INSTALL_FAILED);
};
};
});
}
function InitIDB() {
if (!window.indexedDB) {
console.error("This browser doesn't support IndexedDB");
return;
}
const request = window.indexedDB.open("AluDB", 1);
request.onerror = (event: Event) => {
console.error("Database error: " + (event.target as any).errorCode);
};
request.onsuccess = () => {
console.log("Database opened successfully");
};
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains("InstalledExtensions")) {
db.createObjectStore("InstalledExtensions", { keyPath: "slug" });
console.log("Database setup complete");
}
};
}
InitIDB();
</script>
<style>
.marketplace-ext-grid {
display: grid;
width: 90%;
margin: 0 auto;
color: var(--text-color);
display: grid;
display: flex;
flex-direction: row;
flex-wrap: wrap;
text-align: center;
justify-content: center;
gap: 20px;
}
.marketplace-item {
border: 3px solid var(--accent-color);
padding: 20px;
border-radius: 15px;
width: 180px;
}
.marketplace-item-image {
width: 64px;
height: 64px;
}
.marketplace-install-btn {
width: 100%;
background-color: var(--accent-color);
color: var(--text-color);
border: none;
margin-top: 3px;
padding: 3px;
cursor: pointer;
font-family: "Varela Round", sans-serif;
}
</style>