-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
206 lines (194 loc) · 6.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const publicVapidKey = "";
/**
* Function taken from https://www.npmjs.com/package/web-push#using-vapid-key-for-applicationserverkey
* @param {string} base64String A base64 string.
* @returns A Uint8Array.
*/
function urlBase64ToUint8Array(base64String) {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, "+")
.replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
/**
* Function to get Cross Site Request Forgery (CSRF) token.
* @returns {string} The CSRF token.
*/
function getCsrfToken() {
console.log("Getting CSRF token.");
return document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
}
/**
* Set subscription status based on whether the user has an active subscription.
*/
function setSubscriptionStatus() {
console.log("Setting subscription status.");
const subscribedElement = document.getElementById("subscribed");
const unsubscribedElement = document.getElementById("unsubscribed");
navigator.serviceWorker
.getRegistration()
.then((registration) => {
return registration.pushManager.getSubscription();
})
.then((subscription) => {
// Set subscription status message based on whether the user is subscribed
subscribedElement.setAttribute(
"class",
`${subscription ? "" : "d-none"}`
);
unsubscribedElement.setAttribute(
"class",
`${subscription ? "d-none" : ""}`
);
console.log("Successfully set subscription status.");
})
.catch((err) => {
if (err.message === "registration is undefined") {
console.log("Service Worker registration not found.");
} else {
console.error(`Failed to set subscription status: ${err}`);
}
// Hide subscribed message
subscribedElement.setAttribute("class", "d-none");
// Show unsubscribed message
unsubscribedElement.setAttribute("class", "");
});
}
/**
* Subscribe to PlanetSide 2 alert push notifications.
*/
async function subscribeToPushNotifications() {
// Check if Service Workers are supported for the browser
if ("serviceWorker" in navigator) {
console.log("Registering Service Worker.");
navigator.serviceWorker
.register("/sw.js", { scope: "/" })
.then((_) => {
return navigator.serviceWorker.ready;
})
.then((registration) => {
console.log("Service Worker registration successful.");
// Get selected PlanetSide 2 servers
const checkedServers = [
...document.querySelectorAll("input:checked"),
].map((check) => check.value);
if (!checkedServers.length) {
console.error(
"Check at least one PlanetSide 2 server to subscribe to push notification for."
);
return;
}
console.log(`PlanetSide 2 server IDs selected: ${checkedServers}`);
console.log("Subscribing to push notifications.");
registration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapidKey),
})
.then(async (subscription) => {
// Send message to the Service Worker to save the subscription
registration.active.postMessage({
action: "SAVE_SUBSCRIPTION",
subscription: JSON.stringify(subscription),
});
console.log(`Subscription endpoint: ${subscription.endpoint}`);
await fetch("/api/post-subscription", {
credentials: "same-origin",
method: "POST",
body: JSON.stringify({
servers: checkedServers,
subscription: subscription,
}),
headers: {
"Content-Type": "application/json",
"CSRF-Token": getCsrfToken(),
},
});
setSubscriptionStatus();
})
.catch((err) => {
console.error(`Failed to subscribe to push notifications: ${err}`);
});
})
.catch((err) => {
console.error(`Service Worker registration failed: ${err}`);
});
} else {
console.error("Browser does not support Service Workers.");
alert(
"Your browser does not support Service Workers and therefore, you cannot use PS2Alert.me."
);
}
}
/**
* Unsubscribe from PlanetSide 2 alert push notifications.
*/
async function unsubscribeFromPushNotifications() {
navigator.serviceWorker
.getRegistration()
.then((registration) => {
console.log(
"Getting subscription to unsubscribe from push notifications."
);
registration.pushManager
.getSubscription()
.then(async (subscription) => {
// Send message to the Service Worker to delete the subscription
registration.active.postMessage({ action: "DELETE_SUBSCRIPTION" });
console.log("Unsubscribing from push notifications.");
await subscription.unsubscribe();
await fetch("/api/delete-subscription", {
credentials: "same-origin",
method: "DELETE",
body: JSON.stringify({ endpoint: subscription.endpoint }),
headers: {
"Content-Type": "application/json",
"CSRF-Token": getCsrfToken(),
},
});
await registration.unregister();
setSubscriptionStatus();
})
.catch((err) => {
console.error(
`Failed to unsubscribe from push notifications: ${err}`
);
});
})
.catch((err) => {
console.error(`Failed to get Service Worker registration: ${err}`);
});
}
// Add event listeners for subscribe and unsubscribe events
document
.getElementById("subscribe")
.addEventListener("click", subscribeToPushNotifications);
document
.getElementById("unsubscribe")
.addEventListener("click", unsubscribeFromPushNotifications);
// Show Bootstrap modal
const cookieModal = document.getElementById("cookiemodal");
new bootstrap.Modal(cookieModal).show();
// Set subscribe message when loading the page
setSubscriptionStatus();
// Persist checkbox state across page reloads
const checkboxes = document.querySelectorAll("input");
const checkboxValues = JSON.parse(localStorage.getItem("checkboxValues")) || {};
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("click", (event) => {
console.log(`Saving ${event.target.id} checkbox state.`);
checkboxValues[event.target.id] = event.target.checked;
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
});
Object.entries(checkboxValues).forEach(([id, state]) => {
document.getElementById(id).checked = state;
});