Skip to content

Commit

Permalink
WIP: service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
benthecarman committed Oct 18, 2023
1 parent 5e1b97d commit cd8fe6c
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"@kobalte/tailwindcss": "^0.5.0",
"@modular-forms/solid": "^0.18.1",
"@mutinywallet/barcode-scanner": "5.0.0-beta.3",
"@mutinywallet/mutiny-wasm": "0.4.23",
"@mutinywallet/mutiny-wasm": "^0.4.23",
"@mutinywallet/waila-wasm": "^0.2.1",
"@nostr-dev-kit/ndk": "^0.8.11",
"@solid-primitives/upload": "^0.0.111",
Expand Down
54 changes: 54 additions & 0 deletions public/sw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// /// <reference lib="WebWorker" />
// /// <reference types="vite/client" />
//
// import initMutinyWallet, { MutinyWallet } from "@mutinywallet/mutiny-wasm";
//
// // SERVICE WORKER SETUP STUFF
// declare let self: ServiceWorkerGlobalScope
//
// const entries = self.__WB_MANIFEST
//
// if (import.meta.env.DEV)
// entries.push({ url: '/', revision: Math.random().toString() })
//
// // allow only fallback in dev: we don't want to cache anything
// let allowlist: undefined | RegExp[]
// if (import.meta.env.DEV)
// allowlist = [/^\/$/]
//
// // deny api and server page calls
// let denylist: undefined | RegExp[]
// if (import.meta.env.PROD) {
// denylist = [
// /^\/sw.js$/,
// // exclude webmanifest: has its own cache
// /^\/manifest-(.*).webmanifest$/,
// ]
// }
//
//
// ACTUAL LOGIC
console.log("hello from the service worker?")

self.addEventListener('push', (event) => {
console.log("push event", event)
const data = event.data.json();
const options = {
body: data.body,
icon: data.icon,
badge: data.badge
};
event.waitUntil(
self.registration.showNotification(data.title, options)
);
});










56 changes: 51 additions & 5 deletions src/components/ResetRouter.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,63 @@
import { Button, InnerCard, NiceP, VStack } from "~/components";
import { useI18n } from "~/i18n/context";
import { useMegaStore } from "~/state/megaStore";
import {MutinyWallet} from "@mutinywallet/mutiny-wasm";

// if ('serviceWorker' in navigator) {
// navigator.serviceWorker.register('sw.ts').then(registration => {
// console.log('Service Worker registered with scope:', registration.scope);
// }).catch(error => {
// console.error('Service Worker registration failed:', error);
// });
// }

async function subscribeUserToPush() {
console.log("waiting for service worker");
const registration = await navigator.serviceWorker.ready;
console.log("using push manager");
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array('BJbNCspGEEdyrj4hI6DD5OBlXpEgVzfaWwZP72p0EiSUTQKXyWauOKGzi-_NWq0dT31s3r5MRPvYVeussdEBygM')
});
console.log("talking to mutiny notification service");
try {
// Send the subscription to your server
await MutinyWallet.test_register_web_push("https://auth-staging.mutinywallet.com", "http://localhost:8080", JSON.stringify(subscription));
console.log("registered")
} catch (e) {
console.error(e)
}
}

function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}


export function ResetRouter() {
const i18n = useI18n();
const [state, _] = useMegaStore();

async function reset() {
try {
await state.mutiny_wallet?.reset_router();
} catch (e) {
console.error(e);
}
// Request notification permission from the user
Notification.requestPermission().then(async permission => {
if (permission === 'granted') {
console.log('Notification permission granted.');
await subscribeUserToPush();
console.log('subscribed.');
} else {
console.error('Notification permission denied.');
}
});
}

return (
Expand Down
6 changes: 5 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ const commitHash = child.execSync("git rev-parse --short HEAD").toString().trim(

const pwaOptions: Partial<VitePWAOptions> = {
base: "/",
injectRegister: 'inline',
filename: 'sw.ts',
strategies: 'injectManifest',
registerType: "autoUpdate",
devOptions: {
enabled: false
enabled: true,
type: "module"
},
includeAssets: ["favicon.ico", "robots.txt"],
manifest: manifest
Expand Down

0 comments on commit cd8fe6c

Please sign in to comment.