From 7fe256dc9efd3c01bfc24978d65e9be67e948be7 Mon Sep 17 00:00:00 2001 From: Trent Larson Date: Fri, 22 Dec 2023 12:51:18 -0700 Subject: [PATCH] log service worker messages to the DB (now works) --- README.md | 16 ++++++------- project.task.yaml | 1 + src/App.vue | 1 + src/db/tables/logs.ts | 5 ++++- sw_scripts/additional-scripts.js | 36 +++++++++++++----------------- sw_scripts/safari-notifications.js | 32 ++++++++++++++++---------- 6 files changed, 50 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 34a169a..4a8392d 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,6 @@ npm run lint If you are deploying in a subdirectory, add it to `publicPath` in vue.config.js, eg: `publicPath: "/app/time-tracker/",` -* `npx prettier --write ./sw_scripts/` - -...to make sure the service worker scripts are in proper form - * Update the CHANGELOG.md & the version in package.json, run `npm install`, and commit. * Tag wth the new version: `git tag 0.1.0`. @@ -34,6 +30,10 @@ If you are deploying in a subdirectory, add it to `publicPath` in vue.config.js, * `npm run build` +* `npx prettier --write ./sw_scripts/` + +...to make sure the service worker scripts are in proper form + * `cp sw_scripts/[ns]* dist/` ... to copy the contents of the `sw_scripts` folder to the `dist` folder - except additional_scripts.js. @@ -112,10 +112,10 @@ To add an icon, add to main.ts and reference with `fa` element and `icon` attrib ### Clear/Reset data & restart -* Clear cache for site. (In Chrome, go to `chrome://settings/cookies` and "all site data and permissions"; in Firefox, go to `about:preferences` and search for "cache" then "Manage Data".) -* Unregister service worker (in Chrome, go to `chrome://serviceworker-internals/`; in Firefox, go to `about:serviceworkers`). -* Clear notification permission (in Chrome, go to `chrome://settings/content/notifications`; in Firefox, go to `about:preferences` and search for "notifications"). -* Clear Cache Storage (in Chrome, in dev tools under Application; in Firefox, in dev tools under Storage). +* Clear cache for site. (In Chrome, go to `chrome://settings/cookies` and "all site data and permissions"; in Firefox, go to `about:preferences` and search for "cache" then "Manage Data", and also manually remove the IndexedDB data if the DBs still show.) +* Clear notification permission. (in Chrome, go to `chrome://settings/content/notifications`; in Firefox, go to `about:preferences` and search for "notifications".) +* Unregister service worker. (in Chrome, go to `chrome://serviceworker-internals/`; in Firefox, go to `about:serviceworkers`.) +* Clear Cache Storage. (in Chrome, in dev tools under Application; in Firefox, in dev tools under Storage.) diff --git a/project.task.yaml b/project.task.yaml index 1ccd004..5ba2e88 100644 --- a/project.task.yaml +++ b/project.task.yaml @@ -3,6 +3,7 @@ tasks: - 08 notifications : - get the rest of our Android devices to work... and insert tooling (exportable logs?) so that we can see problems and troubleshoot as we onboard + - get an error registering notifications on Firefox and subscription info is null - prompt user to install on their home screen https://benborgers.com/posts/pwa-detect-installed - warn if they're using the web (android only?) https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getInstalledRelatedApps diff --git a/src/App.vue b/src/App.vue index b69bbd0..2c20d32 100644 --- a/src/App.vue +++ b/src/App.vue @@ -373,6 +373,7 @@ export default class App extends Vue { } private askPermission(): Promise { + console.log("Requesting permission for notifications:", navigator); if (!("serviceWorker" in navigator && navigator.serviceWorker.controller)) { return Promise.reject("Service worker not available."); } diff --git a/src/db/tables/logs.ts b/src/db/tables/logs.ts index 2dd99f7..9207a2f 100644 --- a/src/db/tables/logs.ts +++ b/src/db/tables/logs.ts @@ -3,5 +3,8 @@ export interface Log { } export const LogSchema = { - logs: "message", + // Currently keyed by "date" because A) today's log data is what we need so we append, and + // B) we don't want it to grow so we remove everything if this is the first entry today. + // See safari-notifications.js logMessage for the associated logic. + logs: "date, message", }; diff --git a/sw_scripts/additional-scripts.js b/sw_scripts/additional-scripts.js index 5defa97..3582bfc 100644 --- a/sw_scripts/additional-scripts.js +++ b/sw_scripts/additional-scripts.js @@ -5,34 +5,30 @@ importScripts( ); self.addEventListener("install", (event) => { - console.log("Service worker scripts importing...", event); + console.log("Service worker got install. Importing scripts...", event); importScripts( "safari-notifications.js", "nacl.js", "noble-curves.js", "noble-hashes.js", ); - console.log("Service worker scripts imported."); + console.log("Service worker imported scripts."); }); -function logDbOrConsole(self, message, arg1, arg2) { +function logConsoleAndDb(message, arg1, arg2) { console.log(`${new Date().toISOString()} ${message}`, arg1, arg2); let fullMessage = `${new Date().toISOString()} ${message}`; if (arg1) { - fullMessage += `: ${JSON.stringify(arg1)}`; + fullMessage += `\n${JSON.stringify(arg1)}`; } if (arg2) { - fullMessage += ` -- ${JSON.stringify(arg2)}`; + fullMessage += `\n${JSON.stringify(arg2)}`; } - // const logged = - self.logMessage(fullMessage); - // if (logged || !logged) { - // console.log(`${new Date().toISOString()} ${message}`, arg1, arg2); - // } + self.appendDailyLog(fullMessage); } self.addEventListener("push", function (event) { - logDbOrConsole(this, "Received push event:", event); + logConsoleAndDb("Service worker received a push event.", event); event.waitUntil( (async () => { try { @@ -49,40 +45,40 @@ self.addEventListener("push", function (event) { badge: payload ? payload.badge : "badge.png", }; await self.registration.showNotification(title, options); - logDbOrConsole(self, "Notified user:", options); + logConsoleAndDb("Notified user:", options); } else { - logDbOrConsole(self, "No notification message."); + logConsoleAndDb("No notification message."); } } catch (error) { - logDbOrConsole(self, "Error with push event", event, error); + logConsoleAndDb("Error with push event", event, error); } })(), ); }); self.addEventListener("message", (event) => { - logDbOrConsole(this, "Service worker message:", event); + logConsoleAndDb("Service worker got a message...", event); if (event.data && event.data.type === "SEND_LOCAL_DATA") { self.secret = event.data.data; event.ports[0].postMessage({ success: true }); } - logDbOrConsole(this, "Service worker posted message."); + logConsoleAndDb("Service worker posted a message."); }); self.addEventListener("activate", (event) => { - logDbOrConsole(this, "Service worker activating...", event); + logConsoleAndDb("Service worker activating...", event); // see https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim // and https://web.dev/articles/service-worker-lifecycle#clientsclaim event.waitUntil(clients.claim()); - logDbOrConsole(this, "Service worker activated."); + logConsoleAndDb("Service worker is activated."); }); self.addEventListener("fetch", (event) => { - logDbOrConsole(this, "Got fetch event:", event); + logConsoleAndDb("Service worker got fetch event.", event); }); self.addEventListener("error", (event) => { - logDbOrConsole(this, "Error in Service Worker:", event); + logConsoleAndDb("Service worker error", event); console.error("Full Error:", event); console.error("Message:", event.message); console.error("File:", event.filename); diff --git a/sw_scripts/safari-notifications.js b/sw_scripts/safari-notifications.js index e2f6fe0..22dcf99 100644 --- a/sw_scripts/safari-notifications.js +++ b/sw_scripts/safari-notifications.js @@ -395,33 +395,41 @@ async function setMostRecentNotified(id) { data["lastNotifiedClaimId"] = id; await updateRecord(store, data); } else { - console.error("IndexedDB settings record not found."); + console.error( + "safari-notifications setMostRecentNotified IndexedDB settings record not found", + ); } transaction.oncomplete = () => db.close(); } catch (error) { - console.error("IndexedDB error:", error); + console.error( + "safari-notifications setMostRecentNotified IndexedDB error", + error, + ); } } -async function logMessage(message) { +async function appendDailyLog(message) { try { const db = await openIndexedDB("TimeSafari"); const transaction = db.transaction("logs", "readwrite"); const store = transaction.objectStore("logs"); // will only keep one day's worth of logs const todayKey = new Date().toDateString(); - let data = await getRecord(store, todayKey); - if (!data) { + const previous = await getRecord(store, todayKey); + if (!previous) { await store.clear(); // clear out anything older than today } - data = data || ""; - data += `\n${message}`; - await updateRecord(store, { message: data }, todayKey); + let fullMessage = (previous && previous.message) || ""; + if (fullMessage) { + fullMessage += "\n"; + } + fullMessage += message; + await updateRecord(store, { date: todayKey, message: fullMessage }); transaction.oncomplete = () => db.close(); return true; } catch (error) { - console.error("IndexedDB logMessage error:", error); + console.error("safari-notifications logMessage IndexedDB error", error); return false; } } @@ -443,9 +451,9 @@ function getRecord(store, key) { } // Note that this assumes there is only one record in the store. -function updateRecord(store, data, key) { +function updateRecord(store, data) { return new Promise((resolve, reject) => { - const request = key ? store.put(data, key) : store.put(data); + const request = store.put(data); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); @@ -547,7 +555,7 @@ async function getNotificationCount() { await setMostRecentNotified(most_recent_notified); } else { console.error( - "The service worker got a bad response status when fetching claims:", + "safari-notifications getNotificationsCount got a bad response status when fetching claims", response.status, response, );