/
notificationHandler.ts
83 lines (73 loc) · 3.04 KB
/
notificationHandler.ts
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
/**
* License: zlib/libpng
* @author Santo Pfingsten
* @see https://github.com/Lusito/forget-me-not
*/
import { browser } from "webextension-polyfill-ts";
import { settings } from "../lib/settings";
import DelayedExecution from "../lib/delayedExecution";
import { messageUtil } from "../lib/messageUtil";
import { wetLayer } from "wet-layer";
const COOKIE_CLEANUP_NOTIFICATION_ID = "CookieCleanupNotification";
const CLEAR_NOTIFICATION_TIME = 3000;
const DELAY_NOTIFICATION_UPDATE_ON_START = 100;
const DELAY_NOTIFICATION = 500;
export class NotificationHandler {
private enabled: boolean;
private readonly delayNotification = new DelayedExecution(this.showNotification.bind(this));
private readonly delayClearNotification = new DelayedExecution(this.clearNotification.bind(this));
private removalCountsByDomain: { [s: string]: number } = {};
private starting = false;
private updateOnStart = false;
public constructor() {
this.onNotificationClosed = this.onNotificationClosed.bind(this);
browser.notifications.onClosed.addListener(this.onNotificationClosed);
this.enabled = settings.get("showCookieRemovalNotification");
messageUtil.receive("settingsChanged", () => {
this.enabled = settings.get("showCookieRemovalNotification");
});
messageUtil.receive("cookieRemoved", this.onCookieRemoved.bind(this));
}
private onNotificationClosed(id: string) {
this.starting = false;
this.removalCountsByDomain = {};
this.delayClearNotification.cancel();
}
private clearNotification() {
browser.notifications.clear(COOKIE_CLEANUP_NOTIFICATION_ID);
this.starting = false;
this.removalCountsByDomain = {};
}
private showNotification() {
if (this.starting) {
this.updateOnStart = true;
return;
}
const lines = [];
let totalCount = 0;
for (const domain in this.removalCountsByDomain) {
const count = this.removalCountsByDomain[domain];
lines.push(wetLayer.getMessage("cookie_cleanup_notification_line", [domain, count.toString()]));
totalCount += count;
}
this.starting = true;
this.updateOnStart = false;
browser.notifications.create(COOKIE_CLEANUP_NOTIFICATION_ID, {
type: "basic",
iconUrl: browser.extension.getURL("icons/icon96.png"),
title: wetLayer.getMessage("cookie_cleanup_notification_title", totalCount.toString()),
message: lines.join("\n")
}).then((s) => {
this.starting = false;
if (this.updateOnStart)
this.delayNotification.restart(DELAY_NOTIFICATION_UPDATE_ON_START);
});
this.delayClearNotification.restart(CLEAR_NOTIFICATION_TIME);
}
private onCookieRemoved(domain: string) {
if (this.enabled) {
this.removalCountsByDomain[domain] = (this.removalCountsByDomain[domain] || 0) + 1;
this.delayNotification.restart(DELAY_NOTIFICATION);
}
}
}