-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathnotifications.js
224 lines (204 loc) · 7.74 KB
/
notifications.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Notification stuff
import browser from 'webextension-polyfill';
import {messageHandlers} from '../messageHandling';
import {makeRequest} from './webrequest';
/**
* Gets the storage key where metadata for the given notification is stored.
* @param {string} notificationID
* @returns {string}
*/
const notificationMetaDataKey = notificationID => `notifmeta-${notificationID}`;
/**
* Sets the notification ID and meta data object for a given notification.
* @param notificationID string notificationID
* @param notificationObject object containing the meta data
*/
function setNotificationMetaData (notificationID, notificationObject) {
return browser.storage.session.set({
[notificationMetaDataKey(notificationID)]: notificationObject,
});
}
/**
* Returns the notification meta data object for a given notification id.
* @param notificationID notificationID
* @returns {Promise<object>}
*/
function getNotificationMetaData (notificationID) {
return browser.storage.session.get({[notificationMetaDataKey(notificationID)]: null});
}
/**
* Deletes the notification meta data object for a given notification id.
* @param notificationID subreddit
* @returns {promise<object>}
*/
function deleteNotificationMetaData (notificationID) {
return browser.storage.session.remove(notificationMetaDataKey(notificationID));
}
// TODO: I know we've had this conversation before but I'm 99% sure this isn't
// actually necessary anymore...
/**
* Generates a UUID. We use this instead of something simpler because Firefox
* requires notification IDs to be UUIDs.
* @returns {string}
*/
function uuidv4 () {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(
/[018]/g,
c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16),
);
}
/**
* Sends a native browser notification.
* @param {object} options The notification options
*/
async function sendNativeNotification ({title, body, url, modHash, markreadid}) {
// If we have the getPermissionLevel function, check if we have permission
// to send notifications. This function doesn't currently exist on Firefox
// for some reason. (https://bugzilla.mozilla.org/show_bug.cgi?id=1213455)
if (typeof browser.notifications.getPermissionLevel !== 'undefined') {
const permission = await browser.notifications.getPermissionLevel();
if (permission !== 'granted') {
throw new Error('No permission to send native notifications');
}
}
const notificationID = await browser.notifications.create(uuidv4(), {
type: 'basic',
iconUrl: browser.runtime.getURL('data/images/icon48.png'),
title,
message: body,
});
await setNotificationMetaData(notificationID, {
type: 'native',
url,
modHash,
markreadid,
});
return notificationID;
}
/**
* Sends an in-page notification on all open Reddit windows
* @param {object} options The notification options
*/
async function sendPageNotification ({title, body, url, modHash, markreadid}) {
const notificationID = uuidv4();
await setNotificationMetaData(notificationID, {
type: 'page',
url,
modHash,
markreadid,
});
const message = {
action: 'tb-show-page-notification',
details: {
id: notificationID,
title,
body,
},
};
const tabs = await browser.tabs.query({url: 'https://*.reddit.com/*'});
for (const tab of tabs) {
browser.tabs.sendMessage(tab.id, message).catch(error => {
// Receiving end errors are not really relevant to us and happen a lot for iframes and such where toolbox isn't active.
if (error.message !== 'Could not establish connection. Receiving end does not exist.') {
console.warn('tb-show-page-notification: ', error.message, error);
}
});
}
return notificationID;
}
// Handle notification clearing
browser.alarms.onAlarm.addListener(alarmInfo => {
const name = alarmInfo.name;
if (name.startsWith('tb-notification-')) {
const notificationID = name.replace('tb-notification-', '');
clearNotification(notificationID);
}
});
// Handle notification creation
messageHandlers.set('tb-notification', async request => {
const sendNotification = request.native ? sendNativeNotification : sendPageNotification;
const notificationID = await sendNotification(request.details);
// The Alarms API is baffling simplistic and limited.
// Because of that the ID will be send back to the tab that requested the notification and a timeout used there to relay back to the background worker.
// But because it is possible tabs get closed before the timeout we keep the alarm here as a backup.
browser.alarms.create(`tb-notification-${notificationID}`, {
delayInMinutes: 1,
});
return notificationID; // no response needed
});
/**
* Clears a notification
* @param {string} notificationID The ID of the notification
*/
async function clearNotification (notificationID) {
const metadata = await getNotificationMetaData(notificationID);
if (!metadata) {
// Notification has already been cleared
return;
}
if (metadata.type === 'native') {
// Clear a native notification
browser.notifications.clear(notificationID);
} else {
// Tell all tabs to clear the in-page notification
const message = {
action: 'tb-clear-page-notification',
id: notificationID,
};
const tabs = await browser.tabs.query({url: 'https://*.reddit.com/*'});
for (const tab of tabs) {
browser.tabs.sendMessage(tab.id, message).catch(error => {
// Receiving end errors are not really relevant to us and happen a lot for iframes and such where toolbox isn't active.
if (error.message !== 'Could not establish connection. Receiving end does not exist.') {
console.warn('tb-clear-page-notification: ', error.message, error);
}
});
}
// We don't get a callback when the notifications are closed, so we just
// clean up the data here
await deleteNotificationMetaData(notificationID);
}
}
/**
* Handles a click on a notification
* @param {string} notificationID The ID of the notification
*/
async function onClickNotification (notificationID) {
// Store the metadata so we can work with it after clearing the notification
const metadata = await getNotificationMetaData(notificationID);
console.log('notification clicked: ', metadata);
// Mark as read if needed.
if (metadata.markreadid) {
makeRequest({
method: 'POST',
endpoint: '/api/read_message',
body: {
id: metadata.markreadid,
uh: metadata.modHash,
api_type: 'json',
},
});
}
// Open up in new tab.
const window = await browser.windows.getLastFocused();
browser.tabs.create({
url: metadata.url,
windowId: window.id,
});
// Notification no longer needed, clear it.
clearNotification(notificationID);
}
// Handle click/clear events on in-page notifications
messageHandlers.set('tb-page-notification-click', request => {
onClickNotification(request.id);
});
messageHandlers.set('tb-page-notification-clear', request => {
clearNotification(request.id);
});
// Handle events on native notifications
browser.notifications.onClicked.addListener(onClickNotification);
browser.notifications.onClosed.addListener(id => {
// Clearing native notifications is done for us, so we don't need to call
// clearNotification, but we do still need to clean up metadata.
deleteNotificationMetaData(id);
});