-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathHandler.ts
More file actions
297 lines (246 loc) · 7.86 KB
/
Handler.ts
File metadata and controls
297 lines (246 loc) · 7.86 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/**
* Provides desktop notifications via periodic polling with an
* increasing request delay on inactivity.
*
* @author Alexander Ebert
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @woltlabExcludeBundle tiny
*/
import * as Ajax from "../Ajax";
import { AjaxCallbackSetup } from "../Ajax/Data";
import * as Core from "../Core";
import * as EventHandler from "../Event/Handler";
import { serviceWorkerSupported, updateNotificationLastReadTime } from "./ServiceWorker";
import { updateCounter } from "WoltLabSuite/Core/Ui/User/Menu/Manager";
interface NotificationHandlerOptions {
icon: string;
}
interface PollingResult {
notification: {
link: string;
message?: string;
title: string;
};
}
interface AjaxResponse {
returnValues: {
keepAliveData: {
userNotificationCount: number;
};
lastRequestTimestamp: number;
pollData: PollingResult;
};
}
class NotificationHandler {
private allowNotification: boolean;
private readonly icon: string;
private inactiveSince = 0;
private lastRequestTimestamp = window.TIME_NOW;
private requestTimer?: number = undefined;
/**
* Initializes the desktop notification system.
*/
constructor(options: NotificationHandlerOptions) {
options = Core.extend(
{
icon: "",
},
options,
) as NotificationHandlerOptions;
this.icon = options.icon;
this.prepareNextRequest();
document.addEventListener("visibilitychange", (ev) => this.onVisibilityChange(ev));
window.addEventListener("storage", () => this.onStorage());
this.onVisibilityChange();
if ("Notification" in window && Notification.permission === "granted") {
this.allowNotification = true;
}
if (serviceWorkerSupported()) {
window.navigator.serviceWorker.addEventListener("message", (event) => {
const payload = event.data;
if (payload.time > this.lastRequestTimestamp) {
this.lastRequestTimestamp = payload.time;
}
});
}
}
enableNotifications(): void {
this.allowNotification = true;
}
/**
* Detects when this window is hidden or restored.
*/
private onVisibilityChange(event?: Event) {
// document was hidden before
if (event && !document.hidden) {
const difference = (Date.now() - this.inactiveSince) / 60_000;
if (difference > 4) {
this.resetTimer();
this.dispatchRequest();
}
}
this.inactiveSince = document.hidden ? Date.now() : 0;
}
/**
* Returns the delay in minutes before the next request should be dispatched.
*/
private getNextDelay(): number {
if (this.inactiveSince === 0) {
return 5;
}
// milliseconds -> minutes
const inactiveMinutes = ~~((Date.now() - this.inactiveSince) / 60_000);
if (inactiveMinutes < 15) {
return 5;
} else if (inactiveMinutes < 30) {
return 10;
}
return 15;
}
/**
* Resets the request delay timer.
*/
private resetTimer(): void {
if (this.requestTimer) {
window.clearTimeout(this.requestTimer);
this.requestTimer = undefined;
}
}
/**
* Schedules the next request using a calculated delay.
*/
private prepareNextRequest(): void {
this.resetTimer();
this.requestTimer = window.setTimeout(() => this.dispatchRequest(), this.getNextDelay() * 60_000);
}
/**
* Requests new data from the server.
*/
dispatchRequest(): void {
const parameters: ArbitraryObject = {};
EventHandler.fire("com.woltlab.wcf.notification", "beforePoll", parameters);
// this timestamp is used to determine new notifications and to avoid
// notifications being displayed multiple times due to different origins
// (=subdomains) used, because we cannot synchronize them in the client
parameters.lastRequestTimestamp = this.lastRequestTimestamp;
Ajax.api(this, {
parameters: parameters,
});
}
/**
* Notifies subscribers for updated data received by another tab.
*/
private onStorage(): void {
// abort and re-schedule periodic request
this.prepareNextRequest();
let pollData: unknown;
let keepAliveData: unknown;
let abort = false;
try {
pollData = window.localStorage.getItem(Core.getStoragePrefix() + "notification");
keepAliveData = window.localStorage.getItem(Core.getStoragePrefix() + "keepAliveData");
pollData = JSON.parse(pollData as string);
keepAliveData = JSON.parse(keepAliveData as string);
} catch {
abort = true;
}
if (!abort) {
EventHandler.fire("com.woltlab.wcf.notification", "onStorage", {
pollData,
keepAliveData,
});
}
}
_ajaxSuccess(data: AjaxResponse): void {
const keepAliveData = data.returnValues.keepAliveData;
const pollData = data.returnValues.pollData;
// forward keep alive data
updateCounter("com.woltlab.wcf.notifications", keepAliveData.userNotificationCount);
// store response data in local storage
let abort = false;
try {
window.localStorage.setItem(Core.getStoragePrefix() + "notification", JSON.stringify(pollData));
window.localStorage.setItem(Core.getStoragePrefix() + "keepAliveData", JSON.stringify(keepAliveData));
} catch (e) {
// storage is unavailable, e.g. in private mode, log error and disable polling
abort = true;
window.console.log(e);
}
if (!abort) {
this.prepareNextRequest();
}
this.lastRequestTimestamp = data.returnValues.lastRequestTimestamp;
// Update the last read time for the service worker
updateNotificationLastReadTime(this.lastRequestTimestamp);
EventHandler.fire("com.woltlab.wcf.notification", "afterPoll", pollData);
this.showNotification(pollData);
}
/**
* Displays a desktop notification.
*/
private showNotification(pollData: PollingResult): void {
if (!this.allowNotification) {
return;
}
if (typeof pollData.notification === "object" && typeof pollData.notification.message === "string") {
let notification: Notification;
const div = document.createElement("div");
div.innerHTML = pollData.notification.message;
div.querySelectorAll("img").forEach((img) => {
img.replaceWith(document.createTextNode(img.alt));
});
try {
notification = new window.Notification(pollData.notification.title, {
body: div.textContent!,
icon: this.icon,
});
} catch (e) {
// The `Notification` constructor is not available on Android.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=481856
if (e instanceof Error) {
if (e.name === "TypeError") {
return;
}
}
throw e;
}
notification.onclick = () => {
window.focus();
notification.close();
window.location.href = pollData.notification.link;
};
}
}
_ajaxSetup(): ReturnType<AjaxCallbackSetup> {
return {
data: {
actionName: "poll",
className: "wcf\\data\\session\\SessionAction",
},
ignoreError: !window.ENABLE_DEBUG_MODE,
silent: !window.ENABLE_DEBUG_MODE,
};
}
updateLastRequestTimestamp(timestamp: number): void {
this.lastRequestTimestamp = Math.max(timestamp, this.lastRequestTimestamp);
}
}
let notificationHandler: NotificationHandler;
/**
* Initializes the desktop notification system.
*/
export function setup(options: NotificationHandlerOptions): void {
if (!notificationHandler) {
notificationHandler = new NotificationHandler(options);
}
}
export function enableNotifications(): void {
notificationHandler!.enableNotifications();
}
export function updateLastRequestTimestamp(timestamp: number): void {
notificationHandler?.updateLastRequestTimestamp(timestamp);
}
export function poll(): void {
notificationHandler?.dispatchRequest();
}