Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Notification Subscription Loading and Messaging Errors #9038

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions public/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,7 @@
"notes": "Notes",
"notes_placeholder": "Type your Notes",
"notice_board": "Notice Board",
"notification_cancelled": "Notification cancelled",
"notification_permission_denied": "Notification permission denied",
"notification_permission_granted": "Notification permission granted",
"number_of_aged_dependents_above_60": "Number Of Aged Dependents (Above 60)",
Expand Down Expand Up @@ -1157,7 +1158,9 @@
"submitting": "Submitting",
"subscribe": "Subscribe",
"subscribe_on_this_device": "Subscribe on this device",
"subscribed_successfully": "Subscribed Successfully",
"subscription_error": "Subscription Error",
"subscription_failed": "Subscription Failed",
"suggested_investigations": "Suggested Investigations",
"summary": "Summary",
"support": "Support",
Expand Down Expand Up @@ -1200,6 +1203,7 @@
"unlink_camera_and_bed": "Unlink this bed from this camera",
"unsubscribe": "Unsubscribe",
"unsubscribe_failed": "Unsubscribe failed.",
"unsubscribed_successfully": "Unsubscribed Successfully.",
"unsupported_browser": "Unsupported Browser",
"unsupported_browser_description": "Your browser ({{name}} version {{version}}) is not supported. Please update your browser to the latest version or switch to a supported browser for the best experience.",
"up": "Up",
Expand Down
125 changes: 68 additions & 57 deletions src/components/Notifications/NotificationsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -220,30 +220,6 @@ export default function NotificationsList({
}
};
}, [data, totalCount]);
useEffect(() => {
let intervalId: ReturnType<typeof setTimeout>;
if (isSubscribing) {
const checkNotificationPermission = () => {
if (Notification.permission === "denied") {
Warn({
msg: t("notification_permission_denied"),
});
setIsSubscribing(false);
clearInterval(intervalId);
} else if (Notification.permission === "granted") {
Success({
msg: t("notification_permission_granted"),
});
setIsSubscribing(false);
clearInterval(intervalId);
}
};

checkNotificationPermission();
intervalId = setInterval(checkNotificationPermission, 1000);
}
return () => clearInterval(intervalId);
}, [isSubscribing]);

const intialSubscriptionState = async () => {
try {
Expand All @@ -267,7 +243,14 @@ export default function NotificationsList({
const handleSubscribeClick = () => {
const status = isSubscribed;
if (status === "NotSubscribed" || status === "SubscribedOnAnotherDevice") {
subscribe();
if (Notification.permission === "denied") {
Warn({
msg: t("notification_permission_denied"),
});
setIsSubscribing(false);
} else {
subscribe();
}
} else {
unsubscribe();
}
Expand Down Expand Up @@ -322,6 +305,10 @@ export default function NotificationsList({
body: data,
});

Warn({
msg: t("unsubscribed_successfully"),
});

setIsSubscribed("NotSubscribed");
setIsSubscribing(false);
})
Expand All @@ -342,43 +329,67 @@ export default function NotificationsList({

async function subscribe() {
setIsSubscribing(true);
const response = await request(routes.getPublicKey);
const public_key = response.data?.public_key;
const sw = await navigator.serviceWorker.ready;
const push = await sw.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: public_key,
});
const p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);
try {
const response = await request(routes.getPublicKey);
const public_key = response.data?.public_key;
const sw = await navigator.serviceWorker.ready;
const push = await sw.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: public_key,
});
const p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);
Comment on lines +340 to +351
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for key encoding

The btoa encoding of push notification keys could fail if the binary data contains invalid characters. Consider adding try-catch blocks around the encoding operations.

-      const p256dh = btoa(
-        String.fromCharCode.apply(
-          null,
-          new Uint8Array(push.getKey("p256dh") as any) as any,
-        ),
-      );
-      const auth = btoa(
-        String.fromCharCode.apply(
-          null,
-          new Uint8Array(push.getKey("auth") as any) as any,
-        ),
-      );
+      let p256dh, auth;
+      try {
+        p256dh = btoa(
+          String.fromCharCode(...new Uint8Array(push.getKey("p256dh") as ArrayBuffer))
+        );
+        auth = btoa(
+          String.fromCharCode(...new Uint8Array(push.getKey("auth") as ArrayBuffer))
+        );
+      } catch (error) {
+        throw new Error("Failed to encode push notification keys");
+      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const p256dh = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("p256dh") as any) as any,
),
);
const auth = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(push.getKey("auth") as any) as any,
),
);
let p256dh, auth;
try {
p256dh = btoa(
String.fromCharCode(...new Uint8Array(push.getKey("p256dh") as ArrayBuffer))
);
auth = btoa(
String.fromCharCode(...new Uint8Array(push.getKey("auth") as ArrayBuffer))
);
} catch (error) {
throw new Error("Failed to encode push notification keys");
}


const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};
const data = {
pf_endpoint: push.endpoint,
pf_p256dh: p256dh,
pf_auth: auth,
};

const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});
const { res } = await request(routes.updateUserPnconfig, {
pathParams: { username: username },
body: data,
});

if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
if (res?.ok) {
setIsSubscribed("SubscribedOnThisDevice");
Success({
msg: t("subscribed_successfully"),
});
setIsSubscribing(false);
} else {
Error({
msg: t("subscription_failed"),
});
setIsSubscribing(false);
}
} catch (error) {
const permission = Notification.permission;

if (permission === "denied" || permission === "default") {
Warn({
msg: t("notification_permission_denied"),
});
setIsSubscribing(false);
return;
}
Error({
msg: t("subscription_failed"),
});
} finally {
setIsSubscribing(false);
}
setIsSubscribing(false);
}

const handleMarkAllAsRead = async () => {
setIsMarkingAllAsRead(true);
await Promise.all(
Expand Down
Loading