Browse Source

Refactored last viewed notification code. Appears to work now.

home-view-notification-improvements
Matthew Raymer 1 year ago
parent
commit
2b8cd180a1
  1. 7
      sw_scripts/additional-scripts.js
  2. 132
      sw_scripts/safari-notifications.js

7
sw_scripts/additional-scripts.js

@ -5,14 +5,12 @@ importScripts(
); );
self.addEventListener("install", (event) => { self.addEventListener("install", (event) => {
console.log("Install event fired.");
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("scripts imported", event);
}); });
self.addEventListener("push", function (event) { self.addEventListener("push", function (event) {
@ -23,10 +21,10 @@ self.addEventListener("push", function (event) {
if (event.data) { if (event.data) {
payload = JSON.parse(event.data.text()); payload = JSON.parse(event.data.text());
} }
const value = await self.getNotificationCount(); const message = await self.getNotificationCount();
const title = payload ? payload.title : "Custom Title"; const title = payload ? payload.title : "Custom Title";
const options = { const options = {
body: payload ? value : "SAMPLE", body: message,
icon: payload ? payload.icon : "icon.png", icon: payload ? payload.icon : "icon.png",
badge: payload ? payload.badge : "badge.png", badge: payload ? payload.badge : "badge.png",
}; };
@ -41,7 +39,6 @@ self.addEventListener("push", function (event) {
self.addEventListener("message", (event) => { self.addEventListener("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;
console.log("Data stored in service worker:", self.secret);
event.ports[0].postMessage({ success: true }); event.ports[0].postMessage({ success: true });
} }
}); });

132
sw_scripts/safari-notifications.js

@ -1,4 +1,3 @@
function bufferFromBase64(base64) { function bufferFromBase64(base64) {
const binaryString = atob(base64); const binaryString = atob(base64);
const length = binaryString.length; const length = binaryString.length;
@ -119,7 +118,6 @@ async function accessToken(identifier) {
issuer: did, issuer: did,
signer, signer,
}); });
console.error(jwt);
return jwt; return jwt;
} }
@ -284,7 +282,6 @@ function ES256KSigner(privateKey, recoverable = false) {
return async function (data) { return async function (data) {
const signature = nobleCurves.secp256k1.sign(sha256(data), privateKeyBytes); const signature = nobleCurves.secp256k1.sign(sha256(data), privateKeyBytes);
console.error(signature);
return toJose( return toJose(
{ {
r: leftpad(signature.r.toString(16)), r: leftpad(signature.r.toString(16)),
@ -387,68 +384,57 @@ async function getSettingById(id) {
}); });
} }
async function setMostRecentNotified(id) {
return new Promise((resolve, reject) => {
const dbName = "TimeSafari";
const storeName = "settings";
const key = 1;
const propertyToUpdate = "lastNotifiedClaimId";
const newValue = id;
let request = indexedDB.open(dbName);
request.onerror = function(event) {
console.error("Database error: " + event.target.errorCode);
};
request.onsuccess = function(event) {
let db = event.target.result;
let transaction = db.transaction(storeName, "readwrite");
let store = transaction.objectStore(storeName);
let getRequest = store.get(key); async function setMostRecentNotified(id) {
try {
getRequest.onsuccess = function(event) { const db = await openIndexedDB("TimeSafari");
let data = event.target.result; const transaction = db.transaction("settings", "readwrite");
const store = transaction.objectStore("settings");
// Only update if the object exists const data = await getRecord(store, 1);
if (data) { if (data) {
// Update the specific property data["lastNotifiedClaimId"] = id;
data[propertyToUpdate] = newValue; await updateRecord(store, data);
// Put the updated object back into the database
let putRequest = store.put(data);
putRequest.onsuccess = function() {
console.error("Record updated successfully");
};
putRequest.onerror = function(event) {
console.error("Error updating record: " + event.target.errorCode);
};
} else { } else {
console.error("Record not found"); console.error("Record not found");
} }
};
getRequest.onerror = function(event) { transaction.oncomplete = () => db.close();
console.error("Error fetching record: " + event.target.errorCode); } catch (error) {
}; console.error("Database error: " + error.message);
}
}
transaction.oncomplete = function() {
db.close();
};
};
request.onupgradeneeded = function(event) { function openIndexedDB(dbName) {
let db = event.target.result; return new Promise((resolve, reject) => {
if (!db.objectStoreNames.contains(storeName)) { const request = indexedDB.open(dbName);
db.createObjectStore(storeName); request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains("settings")) {
db.createObjectStore("settings");
} }
}; };
});
}
function getRecord(store, key) {
return new Promise((resolve, reject) => {
const request = store.get(key);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function updateRecord(store, data) {
return new Promise((resolve, reject) => {
const request = store.put(data);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
}); });
} }
@ -492,6 +478,10 @@ async function getNotificationCount() {
secret = self.secret; secret = self.secret;
const secretUint8Array = self.decodeBase64(secret); const secretUint8Array = self.decodeBase64(secret);
const settings = await getSettingById(1); const settings = await getSettingById(1);
let lastNotifiedClaimId = null;
if ("lastNotifiedClaimId" in settings) {
lastNotifiedClaimId = settings["lastNotifiedClaimId"];
}
const activeDid = settings["activeDid"]; const activeDid = settings["activeDid"];
accounts = await fetchAllAccounts(); accounts = await fetchAllAccounts();
let did = null; let did = null;
@ -510,8 +500,6 @@ async function getNotificationCount() {
const msg = decoder.decode(decrypted); const msg = decoder.decode(decrypted);
const identifier = JSON.parse(JSON.parse(msg)); const identifier = JSON.parse(JSON.parse(msg));
console.log(identifier);
const headers = { const headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
}; };
@ -525,34 +513,32 @@ async function getNotificationCount() {
headers: headers, headers: headers,
}, },
); );
console.error(did, response.status); if (response.status == 200) {
const claims = await response.json(); let json = await response.json();
// formulate a message back for notifications let claims = json["data"];
let lastNotifiedClaimId = null;
if ('lastNotifiedClaimId' in settings) {
lastNotifiedClaimId = settings['lastNotifiedClaimId'];
}
let newClaims = 0; let newClaims = 0;
// search for id recent notified -- if it exists if not return everything count for (var i = 0; i < claims.length; i++) {
for (var i=0; i< response.json()['data'].length; i++) { let claim = claims[i];
let claim = response.json()['data']; if (claim["id"] === lastNotifiedClaimId) {
if (claim['id'] == lastNotifiedClaimId) {
break; break;
} }
newClaims++; newClaims++;
} }
// make the notification message here if (newClaims === 0) {
result = "You have no new claims today.";
// first claim is the most recent (?) } else {
const most_recent_notified = claims[0]['id']; result = `${newClaims} have been shared with you`;
}
const most_recent_notified = claims[0]["id"];
await setMostRecentNotified(most_recent_notified); await setMostRecentNotified(most_recent_notified);
return "TEST";
} else {
break; console.error(response.status);
}
} }
} }
return result;
} }
return result;
} }
self.getNotificationCount = getNotificationCount; self.getNotificationCount = getNotificationCount;

Loading…
Cancel
Save