-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathbackground.js
338 lines (300 loc) · 13.7 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import {Database} from "/modules/database.js";
import {Prefs} from "/modules/prefs.js";
import {FeedUpdater} from "/modules/updater.js";
import * as RequestMonitor from "/modules/request-monitor.js";
import {Comm, debounced} from "/modules/utils.js";
const Brief = {
// Port for receiving status updates
_statusPort: null,
// Latest status
_status: null,
// Feeds in known windows
_windowFeeds: new Map(),
// Hooks for debugging
prefs: Prefs,
db: null,
comm: Comm,
// No deinit required, we'll be forcefully unloaded anyway
async init() {
Comm.initMaster();
// @ts-expect-error Types do not know about the temporary flag
browser.runtime.onInstalled.addListener(async ({temporary}) => {
if(temporary) { // `web-ext run` or equivalent
Comm.verbose = true;
const TEST_INDEX = browser.runtime.getURL('/test/index.xhtml');
let tabs = await browser.tabs.query({url: TEST_INDEX});
let debugging = (await browser.tabs.query({}))
.some(({url}) => url === 'about:debugging');
if(tabs.length === 0 && !debugging) {
browser.tabs.create({url: TEST_INDEX});
} else {
for(let {id} of tabs) {
browser.tabs.reload(id);
}
}
}
});
browser.browserAction.onClicked.addListener(
() => browser.tabs.create({url: '/ui/brief.xhtml'}));
browser.browserAction.setBadgeBackgroundColor({color: '#666666'});
browser.menus.create({
id: "brief-button-refresh",
title: browser.i18n.getMessage("briefCtxRefreshFeeds_label"),
contexts: ["browser_action"]
});
browser.menus.create({
id: "brief-button-mark-read",
title: browser.i18n.getMessage("briefCtxMarkFeedsAsRead_label"),
contexts: ["browser_action"]
});
browser.menus.create({
id: "brief-button-show-unread",
type: "checkbox",
title: browser.i18n.getMessage("briefCtxShowUnreadCounter_label"),
contexts: ["browser_action"]
});
browser.menus.create({
id: "brief-button-options",
title: browser.i18n.getMessage("briefCtxShowOptions_label"),
contexts: ["browser_action"]
});
browser.menus.onClicked.addListener(info => this.onContext(info));
/*spawn*/ RequestMonitor.init();
await Prefs.init();
Prefs.addObserver('showUnreadCounter', () => this._updateUI());
Comm.registerObservers({
'feedlist-updated': () => this._updateUI(),
'entries-updated': debounced(100, () => this._updateUI()),
'subscribe-get-feeds': ({windowId}) => this._windowFeeds.get(windowId),
'subscribe-add-feed': ({feed}) => this.db.addFeeds(feed).catch(console.error),
});
this.db = await Database.init();
await FeedUpdater.init({db: this.db});
this._updateUI();
// TODO: first run page
browser.tabs.onUpdated.addListener((id, change, tab) => {
if(tab.active === false) {
return;
}
this.queryFeeds({
tabId: id,
url: tab.url,
title: tab.title,
windowId: tab.windowId,
status: tab.status,
});
});
browser.tabs.onActivated.addListener((ids) => this.queryFeeds(ids));
let activeTabs = await browser.tabs.query({active: true});
for(let tab of activeTabs) {
this.queryFeeds({
tabId: tab.id,
url: tab.url,
title: tab.title,
windowId: tab.windowId,
status: tab.status,
});
}
},
onContext: function({menuItemId, checked=null}) {
switch(menuItemId) {
case 'brief-button-refresh':
Comm.broadcast('update-all');
break;
case 'brief-button-mark-read':
this.db.query().markRead(true);
break;
case 'brief-button-show-unread':
Prefs.set('showUnreadCounter', checked);
break;
case 'brief-button-options':
browser.runtime.openOptionsPage();
break;
}
},
// Should match `extensions.webextensions.restrictedDomains` pref
RESTRICTED_DOMAINS: new Set([
"accounts-static.cdn.mozilla.net",
"accounts.firefox.com",
"addons.cdn.mozilla.net",
"addons.mozilla.org",
"api.accounts.firefox.com",
"content.cdn.mozilla.net",
"content.cdn.mozilla.net",
"discovery.addons.mozilla.org",
"input.mozilla.org",
"install.mozilla.org",
"oauth.accounts.firefox.com",
"profile.accounts.firefox.com",
"support.mozilla.org",
"sync.services.mozilla.com",
"testpilot.firefox.com",
]),
BRIEF_SUBSCRIBE: new RegExp(
"(chrome://brief/content/brief\\.(xul|xhtml)\\?subscribe=|brief://subscribe/)(.*)"),
async queryFeeds({windowId, tabId, url=undefined, title=undefined, status=undefined}) {
let replies = [[]];
let matchSubscribe = this.BRIEF_SUBSCRIBE.exec(url);
if(matchSubscribe) {
let url = decodeURIComponent(matchSubscribe.pop());
this.db.addFeeds({url});
// @ts-expect-error Types do not know that the tab ID is optional
browser.tabs.update({url: '/ui/brief.xhtml'});
}
try {
replies = /** @type {{kind, url}[][]} */(await browser.tabs.executeScript(tabId, {
file: '/content_scripts/scan-for-feeds.js',
runAt: 'document_end',
}));
} catch(ex) {
console.debug("executeScript error:", ex);
if(ex.message === 'Missing host permission for the tab') {
// There are a few known cases: about:, restricted (AMO) and feed preview pages
if(url === undefined) {
({url, title, status} = await browser.tabs.get(tabId));
}
let {host, protocol} = new URL(url);
if(url === undefined || protocol === 'about:' || protocol === 'view-source:') {
// Ok, looks like there's nothing Brief can do
// (feeds from AMO cannot be fetched)
} else if(Brief.RESTRICTED_DOMAINS.has(host)) {
// FIXME: maybe try fetching them as `restricted.domain.com.`?
} else if(/\.pdf$/.test(title)) {
// Heuristics: looks like the PDF viewer, probably not a feed, ignore
} else if(status === 'loading') {
// Intermediate states during loading cause this message too
}
} else if(ex.message === 'No matching message handler') {
// Happens during tab restore / history navigation (transient states?)
} else if(ex.message === 'Message manager disconnected') {
// Happens during redirect-to-feed (transient states?)
} else {
console.warn("Ignoring unknown error scanning tab for feeds", ex);
}
}
// Default: fallback to "this is not a feed page"
if(replies === undefined) {
replies = [[]];
}
let feeds = replies[0] || []; // Firefox bug 1639529: some built-in pages return undefined
if(feeds.length > 0) {
// Redirecting from the Firefox preview mode looks just ugly, let's keep it the old way
if(feeds[0].kind === 'self') {
let target = encodeURIComponent(feeds[0].url);
let previewUrl = "/ui/brief.xhtml?preview=" + target;
browser.tabs.update(tabId, {url: previewUrl, loadReplace: true});
}
browser.pageAction.show(tabId);
let path = null;
if(feeds[0].kind === 'self') {
path = '/icons/brief.svg#pulsing';
}
browser.pageAction.setIcon({path, tabId});
} else {
browser.pageAction.hide(tabId);
}
this._windowFeeds.set(windowId, feeds);
},
_updateUI: async function() {
let enabled = Prefs.get('showUnreadCounter');
browser.menus.update('brief-button-show-unread', {checked: enabled});
if(enabled) {
let count = await this.db.query({
deleted: 0,
read: 0,
includeFeedsExcludedFromGlobalViews: 0,
}).count();
let text = "";
if(count > 0) {
text = count.toString();
// We crop the badge manually to leave the least-significant digits
if (text.length > 4)
text = '..' + text.substring(text.length - 3);
}
browser.browserAction.setBadgeText({text});
} else {
browser.browserAction.setBadgeText({text: ""});
}
//TODO: return tooltip
/*
_updateStatus: async function Brief__updateStatus() {
let updated = "";
let bundle = Services.strings.createBundle('chrome://brief/locale/brief.properties');
let lastUpdateTime = this.prefs.getIntPref('update.lastUpdateTime') * 1000;
let date = new Date(lastUpdateTime);
let relativeDate = new this.common.RelativeDate(lastUpdateTime);
let time, pluralForms, form;
let lang = Brief.window.navigator.language;
switch (true) {
case relativeDate.deltaMinutes === 0:
updated = bundle.GetStringFromName('lastUpdated.rightNow');
break;
case relativeDate.deltaHours === 0:
pluralForms = bundle.GetStringFromName('minute.pluralForms');
form = this.common.getPluralForm(relativeDate.deltaMinutes, pluralForms);
updated = bundle.formatStringFromName('lastUpdated.ago', [form], 1)
.replace('#number', relativeDate.deltaMinutes);
break;
case relativeDate.deltaHours <= 12:
pluralForms = bundle.GetStringFromName('hour.pluralForms');
form = this.common.getPluralForm(relativeDate.deltaHours, pluralForms);
updated = bundle.formatStringFromName('lastUpdated.ago', [form], 1)
.replace('#number', relativeDate.deltaHours);
break;
case relativeDate.deltaDaySteps === 0:
time = date.toLocaleTimeString(lang, {hour: 'numeric', minute: 'numeric'});
updated = bundle.formatStringFromName('lastUpdated.today', [time], 1);
break;
case relativeDate.deltaDaySteps === 1:
time = date.toLocaleTimeString(lang, {hour: 'numeric', minute: 'numeric'});
updated = bundle.formatStringFromName('lastUpdated.yesterday', [time], 1);
break;
case relativeDate.deltaDaySteps < 7:
pluralForms = bundle.GetStringFromName('day.pluralForms');
form = this.common.getPluralForm(relativeDate.deltaDays, pluralForms);
updated = bundle.formatStringFromName('lastUpdated.ago', [form], 1)
.replace('#number', relativeDate.deltaDays);
break;
case relativeDate.deltaYearSteps === 0:
date = date.toLocaleDateString(lang, {month: 'long', day: 'numeric'});
updated = bundle.formatStringFromName('lastUpdated.fullDate', [date], 1);
break;
default:
date = date.toLocaleDateString(lang, {
year: 'numeric', month: 'long', day: 'numeric'});
updated = bundle.formatStringFromName('lastUpdated.fullDate', [date], 1);
break;
}
let rows = [];
let feeds_query = this.db.query({
deleted: false,
read: false,
sortOrder: 'library',
sortDirection: 'asc'
})
let unreadFeeds = await feeds_query.getProperty('feedID', true);
let noUnreadText = "";
if(unreadFeeds.length == 0)
noUnreadText = bundle.GetStringFromName('noUnreadFeedsTooltip');
for (let feed of unreadFeeds) {
let feedName = Storage.getFeed(feed).title;
if(feedName.length > 24)
feedName = feedName.substring(0, 24) + "...";
let query = this.db.query({
deleted: false,
feeds: [feed],
read: false
})
rows.push(query.getEntryCount().then(count => `${count}\t\t${feedName}`));
}
rows = await Promise.all(rows);
let tooltip = `${updated}\n\n${noUnreadText}${rows.join('\n')}`;
},
*/
//browser.browserAction.setTitle({title: tooltip});
},
};
Brief.init();
// Debugging hook
// @ts-expect-error Adding a custom global variable on Window
window.Brief = Brief;