Skip to content

Commit 2600b9c

Browse files
committed
Some fixes to push notification subscriptions and stuff
1 parent 5582cfc commit 2600b9c

4 files changed

Lines changed: 100 additions & 81 deletions

File tree

server-src/server.js

Lines changed: 58 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -395,16 +395,19 @@ async function validateUserCookie(decryptedUserdata) {
395395
json.sessions = [];
396396
}
397397
const currentSessionToken = decryptedUserdata.session;
398-
const isValidSession = json.sessions.some(
399-
(session) => session.id === currentSessionToken,
398+
const curSession = json.sessions.find(
399+
(session) => session.id == currentSessionToken,
400400
);
401-
if (isValidSession) {
401+
if (curSession) {
402+
var pushSubscription = curSession.pushSubscription;
402403
return {
403404
color,
404405
font,
405406
displayName,
406407
success: true,
407408
valid: true,
409+
sessionCreated: curSession.created,
410+
pushEndpoint: pushSubscription ? pushSubscription.endpoint : undefined,
408411
};
409412
} else {
410413
return {
@@ -2653,76 +2656,76 @@ function applyRateLimit(req) {
26532656
return false;
26542657
}
26552658

2656-
async function registerPushNotifications(username, newSubscription) {
2657-
var filename = `push_sub_${username.trim().toLowerCase()}.json`;
2658-
var subscriptions = [];
2659-
2660-
try {
2661-
// 1. Try to download existing subs
2662-
const buffer = await storage.downloadFile(filename, false);
2663-
subscriptions = JSON.parse(buffer.toString());
2659+
async function registerPushNotifications(decryptedUserdata, newSubscription) {
2660+
var userFile = `user-${decryptedUserdata.username}.json`;
2661+
var data = await storage.downloadFile(userFile);
2662+
var json = JSON.parse(data);
26642663

2665-
// 2. Prevent duplicates (check if endpoint already exists)
2666-
const exists = subscriptions.find(
2667-
(s) => s.endpoint === newSubscription.endpoint,
2668-
);
2669-
if (!exists) {
2670-
subscriptions.push(newSubscription);
2671-
}
2672-
subscriptions = subscriptions.slice(-cons.MAX_PUSH_SUBSCRIPTIONS);
2673-
} catch (err) {
2674-
// File doesn't exist yet, start a new list
2675-
subscriptions = [newSubscription];
2664+
var sessionID = decryptedUserdata.session;
2665+
if (!json.sessions) {
2666+
throw new Error("User data is missing sessions array");
2667+
}
2668+
var currentSession = json.sessions.find((s) => s.id == sessionID);
2669+
if (!currentSession) {
2670+
throw new Error("Current session not found in user data");
26762671
}
26772672

2678-
// 3. Upload the updated list
2679-
await storage.uploadFile(
2680-
filename,
2681-
JSON.stringify(subscriptions),
2682-
"application/json",
2683-
);
2673+
currentSession.pushSubscription = newSubscription;
2674+
2675+
await storage.uploadFile(userFile, JSON.stringify(json), "application/json");
26842676
}
26852677

26862678
async function removeSubscriptionFromFile(username, endpointToRemove) {
2687-
const filename = `push_sub_${username.toLowerCase()}.json`;
2688-
2689-
try {
2690-
// 1. Download the current list of devices
2691-
const buffer = await storage.downloadFile(filename, false);
2692-
let subscriptions = JSON.parse(buffer.toString());
2693-
2694-
// 2. Filter out the specific endpoint
2695-
const updatedSubscriptions = subscriptions.filter(
2696-
(sub) => sub.endpoint !== endpointToRemove,
2697-
);
2679+
var userFile = `user-${username}.json`;
2680+
var data = await storage.downloadFile(userFile);
2681+
var json = JSON.parse(data);
26982682

2699-
// 3. If no subscriptions are left, delete the file; otherwise, update it
2700-
if (updatedSubscriptions.length === 0) {
2701-
await storage.deleteFile(filename);
2702-
} else {
2703-
await storage.uploadFile(
2704-
filename,
2705-
JSON.stringify(updatedSubscriptions),
2706-
"application/json",
2707-
);
2683+
if (json.sessions) {
2684+
for (const session of json.sessions) {
2685+
if (
2686+
session.pushSubscription &&
2687+
session.pushSubscription.endpoint == endpointToRemove
2688+
) {
2689+
session.pushSubscription = null;
2690+
break;
2691+
}
27082692
}
2709-
} catch (err) {
2710-
console.error("Error removing subscription:", err);
27112693
}
2694+
2695+
await storage.uploadFile(userFile, JSON.stringify(json), "application/json");
27122696
}
27132697

27142698
async function getSubscriptions(username) {
27152699
try {
2716-
const filename = `push_sub_${username.toLowerCase()}.json`;
2717-
const buffer = await storage.downloadFile(filename, false);
2718-
let subscriptions = JSON.parse(buffer.toString());
2700+
var userFile = `user-${username}.json`;
2701+
var data = await storage.downloadFile(userFile);
2702+
var json = JSON.parse(data);
27192703

2720-
return subscriptions;
2704+
if (json.sessions) {
2705+
var subscriptions = [];
2706+
for (const session of json.sessions) {
2707+
if (session.pushSubscription) {
2708+
subscriptions.push(session.pushSubscription);
2709+
}
2710+
}
2711+
return subscriptions;
2712+
} else {
2713+
return null;
2714+
}
27212715
} catch (e) {
27222716
return;
27232717
}
27242718
}
27252719

2720+
async function hasSubscription(username, subscription) {
2721+
const subs = await getSubscriptions(username);
2722+
if (subs) {
2723+
return subs.some((sub) => sub.endpoint == subscription.endpoint);
2724+
} else {
2725+
return false;
2726+
}
2727+
}
2728+
27262729
async function sendPushMessage(username, payload) {
27272730
const subs = await getSubscriptions(username);
27282731
if (!subs) return;
@@ -2733,7 +2736,6 @@ async function sendPushMessage(username, payload) {
27332736
} catch (err) {
27342737
// 404: Not Found, 410: Gone (Unsubscribed)
27352738
if (err.statusCode === 404 || err.statusCode === 410) {
2736-
console.log(`Cleaning up dead subscription for ${username}`);
27372739
await removeSubscriptionFromFile(username, sub.endpoint);
27382740
}
27392741
}
@@ -2900,7 +2902,7 @@ const server = http.createServer(async function (req, res) {
29002902
}
29012903

29022904
try {
2903-
await registerPushNotifications(decryptedUserdata.username, json);
2905+
await registerPushNotifications(decryptedUserdata, json);
29042906
res.end("");
29052907
return;
29062908
} catch (e) {

src/accounthelper/index.js

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -40,21 +40,36 @@ async function checkSessionCookie() {
4040
var json = await request.json();
4141
if (json.valid) {
4242
lastValidationState = json;
43+
try {
44+
var subscription = await pushNotificationHelper.getSubscription();
45+
} catch (e) {
46+
return json;
47+
}
48+
if (!subscription) {
49+
return json;
50+
}
51+
if (json.endpoint !== subscription.endpoint) {
52+
try {
53+
await uploadPushSubscription(subscription);
54+
} catch (e) {
55+
console.log("Error updating push subscription:", e);
56+
}
57+
}
4358
return json;
4459
}
4560
lastValidationState = null;
4661
(async function () {
47-
try{
48-
await pushNotificationHelper.__unsubscribe()
49-
}catch(e){}
62+
try {
63+
await pushNotificationHelper.__unsubscribe();
64+
} catch (e) {}
5065
})();
5166
return false;
5267
} catch (e) {
5368
lastValidationState = null;
5469
(async function () {
55-
try{
56-
await pushNotificationHelper.__unsubscribe()
57-
}catch(e){}
70+
try {
71+
await pushNotificationHelper.__unsubscribe();
72+
} catch (e) {}
5873
})();
5974
return false;
6075
}
@@ -94,18 +109,18 @@ async function signupAccount(username, password, robot_check_id) {
94109

95110
async function logoutOfAccount() {
96111
(async function () {
97-
try{
98-
await pushNotificationHelper.unsubscribe()
99-
}catch(e){}
100-
})();
112+
try {
113+
await pushNotificationHelper.unsubscribe();
114+
} catch (e) {}
115+
})();
101116
var request = await fetch(getServerURL() + "/account/logout", {
102117
method: "POST",
103118
});
104119
(async function () {
105-
try{
106-
await pushNotificationHelper.__unsubscribe()
107-
}catch(e){}
108-
})();
120+
try {
121+
await pushNotificationHelper.__unsubscribe();
122+
} catch (e) {}
123+
})();
109124
}
110125

111126
function getProfilePictureURL(username) {
@@ -190,16 +205,16 @@ async function uploadRemovePushSubscription(subscription) {
190205
var response = await fetch(getServerURL() + "/webpush/unsubscribe", {
191206
method: "POST",
192207
body: JSON.stringify({
193-
endpoint: subscription.endpoint
208+
endpoint: subscription.endpoint,
194209
}),
195210
headers: { "Content-Type": "application/json" },
196211
});
197-
if (!response.ok) {
212+
/*if (!response.ok) {
198213
throw new Error(
199214
"Issue when sending to remove subscription. Error: " +
200215
(await response.text()),
201216
);
202-
}
217+
}*/
203218
}
204219

205220
pushNotificationHelper.subscribe = async function (retry = false) {

src/chat/interface/notifications/index.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -430,17 +430,19 @@ class RealTimeNotifications {
430430
}
431431
this._disablingSWP = true;
432432

433-
var output = await dialogs.confirm("Are you sure you want to disable push notifications? If you do that, you'll not recieve any more system notifications from the bell.");
433+
var output = await dialogs.confirm(
434+
"Are you sure you want to disable push notifications? If you do that, you'll not recieve any more system notifications from the bell.",
435+
);
434436

435437
if (!output) {
436438
return;
437439
}
438440

439-
try{
441+
try {
440442
await accountHelper.pushNotificationHelper.unsubscribe();
441443
dialogs.alert("Push notifications disabled successfully!");
442-
}catch(e){
443-
dialogs.alert("Unable to disable push notifications: "+e);
444+
} catch (e) {
445+
dialogs.alert("Unable to disable push notifications: " + e);
444446
console.error(e);
445447
}
446448

@@ -454,13 +456,13 @@ class RealTimeNotifications {
454456
}
455457
this._enablingSWP = true;
456458
var prevText = this.addSWPButton.textContent;
457-
try{
459+
try {
458460
this.addSWPButton.textContent = "Click allow if it appears anywhere";
459461
await notify.requestPermission();
460462
this.addSWPButton.textContent = "Subscribing to push notifications...";
461463
await accountHelper.pushNotificationHelper.subscribe();
462-
}catch(e){
463-
dialog.alert("Unable to enable push notifications: "+e);
464+
} catch (e) {
465+
dialog.alert("Unable to enable push notifications: " + e);
464466
console.error(e);
465467
}
466468
this.loadNotifications();

wpstatic/version.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"timestamp":"1770742963099"}
1+
{ "timestamp": "1770814973859" }

0 commit comments

Comments
 (0)