Browse Source

log service worker messages to the DB (now works)

kb/add-usage-guide
Trent Larson 11 months ago
parent
commit
7fe256dc9e
  1. 16
      README.md
  2. 1
      project.task.yaml
  3. 1
      src/App.vue
  4. 5
      src/db/tables/logs.ts
  5. 36
      sw_scripts/additional-scripts.js
  6. 32
      sw_scripts/safari-notifications.js

16
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/",` 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. * Update the CHANGELOG.md & the version in package.json, run `npm install`, and commit.
* Tag wth the new version: `git tag 0.1.0`. * 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` * `npm run build`
* `npx prettier --write ./sw_scripts/`
...to make sure the service worker scripts are in proper form
* `cp sw_scripts/[ns]* dist/` * `cp sw_scripts/[ns]* dist/`
... to copy the contents of the `sw_scripts` folder to the `dist` folder - except additional_scripts.js. ... 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/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".) * 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.)
* 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 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). * Clear Cache Storage. (in Chrome, in dev tools under Application; in Firefox, in dev tools under Storage.)

1
project.task.yaml

@ -3,6 +3,7 @@ tasks:
- 08 notifications : - 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 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 - prompt user to install on their home screen https://benborgers.com/posts/pwa-detect-installed
- warn if they're using the web (android only?) - warn if they're using the web (android only?)
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getInstalledRelatedApps https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getInstalledRelatedApps

1
src/App.vue

@ -373,6 +373,7 @@ export default class App extends Vue {
} }
private askPermission(): Promise<NotificationPermission> { private askPermission(): Promise<NotificationPermission> {
console.log("Requesting permission for notifications:", navigator);
if (!("serviceWorker" in navigator && navigator.serviceWorker.controller)) { if (!("serviceWorker" in navigator && navigator.serviceWorker.controller)) {
return Promise.reject("Service worker not available."); return Promise.reject("Service worker not available.");
} }

5
src/db/tables/logs.ts

@ -3,5 +3,8 @@ export interface Log {
} }
export const LogSchema = { 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",
}; };

36
sw_scripts/additional-scripts.js

@ -5,34 +5,30 @@ importScripts(
); );
self.addEventListener("install", (event) => { self.addEventListener("install", (event) => {
console.log("Service worker scripts importing...", event); console.log("Service worker got install. Importing scripts...", event);
importScripts( importScripts(
"safari-notifications.js", "safari-notifications.js",
"nacl.js", "nacl.js",
"noble-curves.js", "noble-curves.js",
"noble-hashes.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); console.log(`${new Date().toISOString()} ${message}`, arg1, arg2);
let fullMessage = `${new Date().toISOString()} ${message}`; let fullMessage = `${new Date().toISOString()} ${message}`;
if (arg1) { if (arg1) {
fullMessage += `: ${JSON.stringify(arg1)}`; fullMessage += `\n${JSON.stringify(arg1)}`;
} }
if (arg2) { if (arg2) {
fullMessage += ` -- ${JSON.stringify(arg2)}`; fullMessage += `\n${JSON.stringify(arg2)}`;
} }
// const logged = self.appendDailyLog(fullMessage);
self.logMessage(fullMessage);
// if (logged || !logged) {
// console.log(`${new Date().toISOString()} ${message}`, arg1, arg2);
// }
} }
self.addEventListener("push", function (event) { self.addEventListener("push", function (event) {
logDbOrConsole(this, "Received push event:", event); logConsoleAndDb("Service worker received a push event.", event);
event.waitUntil( event.waitUntil(
(async () => { (async () => {
try { try {
@ -49,40 +45,40 @@ self.addEventListener("push", function (event) {
badge: payload ? payload.badge : "badge.png", badge: payload ? payload.badge : "badge.png",
}; };
await self.registration.showNotification(title, options); await self.registration.showNotification(title, options);
logDbOrConsole(self, "Notified user:", options); logConsoleAndDb("Notified user:", options);
} else { } else {
logDbOrConsole(self, "No notification message."); logConsoleAndDb("No notification message.");
} }
} catch (error) { } catch (error) {
logDbOrConsole(self, "Error with push event", event, error); logConsoleAndDb("Error with push event", event, error);
} }
})(), })(),
); );
}); });
self.addEventListener("message", (event) => { 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") { if (event.data && event.data.type === "SEND_LOCAL_DATA") {
self.secret = event.data.data; self.secret = event.data.data;
event.ports[0].postMessage({ success: true }); event.ports[0].postMessage({ success: true });
} }
logDbOrConsole(this, "Service worker posted message."); logConsoleAndDb("Service worker posted a message.");
}); });
self.addEventListener("activate", (event) => { 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 // see https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim
// and https://web.dev/articles/service-worker-lifecycle#clientsclaim // and https://web.dev/articles/service-worker-lifecycle#clientsclaim
event.waitUntil(clients.claim()); event.waitUntil(clients.claim());
logDbOrConsole(this, "Service worker activated."); logConsoleAndDb("Service worker is activated.");
}); });
self.addEventListener("fetch", (event) => { self.addEventListener("fetch", (event) => {
logDbOrConsole(this, "Got fetch event:", event); logConsoleAndDb("Service worker got fetch event.", event);
}); });
self.addEventListener("error", (event) => { self.addEventListener("error", (event) => {
logDbOrConsole(this, "Error in Service Worker:", event); logConsoleAndDb("Service worker error", event);
console.error("Full Error:", event); console.error("Full Error:", event);
console.error("Message:", event.message); console.error("Message:", event.message);
console.error("File:", event.filename); console.error("File:", event.filename);

32
sw_scripts/safari-notifications.js

@ -395,33 +395,41 @@ async function setMostRecentNotified(id) {
data["lastNotifiedClaimId"] = id; data["lastNotifiedClaimId"] = id;
await updateRecord(store, data); await updateRecord(store, data);
} else { } else {
console.error("IndexedDB settings record not found."); console.error(
"safari-notifications setMostRecentNotified IndexedDB settings record not found",
);
} }
transaction.oncomplete = () => db.close(); transaction.oncomplete = () => db.close();
} catch (error) { } catch (error) {
console.error("IndexedDB error:", error); console.error(
"safari-notifications setMostRecentNotified IndexedDB error",
error,
);
} }
} }
async function logMessage(message) { async function appendDailyLog(message) {
try { try {
const db = await openIndexedDB("TimeSafari"); const db = await openIndexedDB("TimeSafari");
const transaction = db.transaction("logs", "readwrite"); const transaction = db.transaction("logs", "readwrite");
const store = transaction.objectStore("logs"); const store = transaction.objectStore("logs");
// will only keep one day's worth of logs // will only keep one day's worth of logs
const todayKey = new Date().toDateString(); const todayKey = new Date().toDateString();
let data = await getRecord(store, todayKey); const previous = await getRecord(store, todayKey);
if (!data) { if (!previous) {
await store.clear(); // clear out anything older than today await store.clear(); // clear out anything older than today
} }
data = data || ""; let fullMessage = (previous && previous.message) || "";
data += `\n${message}`; if (fullMessage) {
await updateRecord(store, { message: data }, todayKey); fullMessage += "\n";
}
fullMessage += message;
await updateRecord(store, { date: todayKey, message: fullMessage });
transaction.oncomplete = () => db.close(); transaction.oncomplete = () => db.close();
return true; return true;
} catch (error) { } catch (error) {
console.error("IndexedDB logMessage error:", error); console.error("safari-notifications logMessage IndexedDB error", error);
return false; return false;
} }
} }
@ -443,9 +451,9 @@ function getRecord(store, key) {
} }
// Note that this assumes there is only one record in the store. // 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) => { 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.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error); request.onerror = () => reject(request.error);
}); });
@ -547,7 +555,7 @@ async function getNotificationCount() {
await setMostRecentNotified(most_recent_notified); await setMostRecentNotified(most_recent_notified);
} else { } else {
console.error( 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.status,
response, response,
); );

Loading…
Cancel
Save