-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
183 lines (171 loc) · 5.93 KB
/
background.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
// Author: Ngo Kim Phu
var notify, audio, lastUnread = 0;
Promise.any = promises =>
Promise.all(promises.map(promise =>
promise.then(
val => Promise.reject(val),
err => Promise.resolve(err)
)
)).then(
errors => Promise.reject(errors),
val => Promise.resolve(val)
);
Promise.settleIf = (bool, val) => Promise[bool ? 'resolve' : 'reject'](val);
// Right-click menu
browser.contextMenus.create({
title: 'Check now',
contexts: ['browser_action'],
onclick: check,
});
browser.contextMenus.create({
type: 'separator',
contexts: ['browser_action'],
});
browser.contextMenus.create({
title: 'Options',
contexts: ['browser_action'],
onclick: () => browser.runtime.openOptionsPage(),
});
function setBadge(text = '') {
return browser.browserAction.setBadgeText({ text });
}
function setIcon(path = 'icons/yma-48.png') {
return browser.browserAction.setIcon({ path });
}
function getYahooTab() {
return browser.tabs.query({ windowType: 'normal' })
.then(tabs => Promise.any(tabs
.filter(tab => !tab.incognito)
.sort((tabA, tabB) => tabB.lastAccessed - tabA.lastAccessed)
.map(tab => browser.tabs.sendMessage(tab.id, null)
.then(found => Promise.settleIf(found, tab)))
));
}
// Open Yahoo! mail when clicking the extension icon or the notification
(openYahooMail => {
browser.browserAction.onClicked.addListener(openYahooMail);
browser.notifications.onClicked.addListener(openYahooMail);
})(() => {
setBadge();
// switch to a Yahoo mail tab if it exists, otherwise create one
(createTab => getYahooTab()
// check that it's not closed
.then(tab => browser.tabs.get(tab.id))
// set active/focused for window and for tab
.then(tab => browser.windows.update(tab.windowId, { focused: true })
.then(() => browser.tabs.update(tab.id, { active: true })))
.catch(createTab)
)(() => ((createWin, createTab, url) => browser.windows.getCurrent()
.then(win => Promise.settleIf(!win.incognito, win))
// open Yahoo! mail in a non-private window
.then(browser.windows.getAll({ windowTypes: [ 'normal' ] })
.then(wins => Promise.any(wins.map(win =>
Promise.settleIf(!win.incognito, win))))
// switch to the first non-private window
.then(({ id: windowId }) => {
createTab({ url, windowId })
browser.windows.update(windowId, { focused: true })
})
// or create new window
.catch(() => createWin({ url })))
.catch(createTab.bind({ url }))
)(createData => browser.windows.create(createData),
createData => browser.tabs.create(createData),
'https://mail.yahoo.com'));
});
function onLoadSuccess(unread) {
setIcon();
setBadge(unread);
if (notify && unread > lastUnread) {
audio.paused || audio.pause();
audio.currentTime = 0;
audio.play();
browser.notifications.create('newEmail', {
type: 'basic',
title: 'Yahoo! Mail Alerter',
message: `You have ${unread} unread emails`,
iconUrl: 'icons/yma-48.png',
});
}
lastUnread = +unread;
}
function onLoadError() {
setIcon('icons/loadfail.png');
}
function onAuthError() {
setIcon('icons/loadfail.png');
}
async function check(){
setIcon('icons/loading.png');
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://mail.yahoo.com/b/', true);
xhr.withCredentials = true;
xhr.responseType = 'document';
xhr.timeout = 60000;
xhr.ontimeout = onLoadError;
xhr.onerror = onLoadError;
xhr.onload = function() {
let target;
try {
target = this.response.scripts.nodinJsVars.text;
} catch(error) {
console.error('Unexpected Yahoo mail webpage content, searching the whole thing', error);
target = this.response.documentElement.textContent;
}
if (match = target.match(/[Tt]itle[^\w(]*:[^\w(]*(?:\((\d+) unread\) - )?\w/)) {
onLoadSuccess(match[1] || '');
} else {
onAuthError();
}
};
xhr.send();
}
// Initialization after installation
browser.storage.sync.get(['interval', 'notify', 'sound'])
.then(res => {
interval = res.interval;
if (interval === undefined) {
interval = 300;
browser.storage.sync.set({ interval });
} else {
jobId = setInterval(check, interval * 1000);
browser.storage.local.set({ jobId });
}
notify = res.notify;
if (notify === undefined) {
notify = true;
browser.storage.sync.set({ notify });
}
sound = res.sound;
if (sound === undefined || sound === 'sounds/default.wav') {
sound = 'Default';
browser.storage.sync.set({ sound });
} else {
audio = new Audio('sounds/' + sound + '.wav');
}
});
// Update after option changes
browser.storage.onChanged.addListener(changes => {
// Set new interval job when interval option changes
if (changes.interval && changes.interval.newValue != changes.interval.oldValue) {
// Schedule new job
jobId = setInterval(check, changes.interval.newValue * 1000);
// Remove old job
browser.storage.local.get('jobId')
.then(res => {
clearInterval(res.jobId);
// Save new job
browser.storage.local.set({ jobId });
});
}
// Update notification preference
if (changes.notify) {
notify = changes.notify.newValue;
}
// Initialize new sound player when sound option changes
if (changes.sound && changes.sound.newValue != changes.sound.oldValue) {
audio = new Audio('sounds/' + changes.sound.newValue + '.wav');
}
});
// First check after installation
check();