Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
268 lines (222 loc) · 7.93 KB
/
Copy pathbackground.js
File metadata and controls
268 lines (222 loc) · 7.93 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
/* background.js
*
* Handle user interaction and other relevant web extension events. Expects
* that bloom-wrap.js and bloom.js will be included in the background.html page
* before this runs.
*
* Created by Jacob Strieb
* July 2020 & January 2021
*/
/*******************************************************************************
* Global variables
******************************************************************************/
var tabs = {};
/*******************************************************************************
* Helper functions
******************************************************************************/
/***
* Activate the badge for a particular tab
*/
function activateBadge(story, tabId) {
browser.browserAction.enable(tabId);
browser.browserAction.setBadgeText({
text: "" + story.points,
tabId: tabId
});
}
/***
* Deactivate the badge for a particular tab
*/
function deactivateBadge(tabId) {
browser.browserAction.disable(tabId);
browser.browserAction.setBadgeText({
text: "",
tabId: tabId
});
}
/***
* Load settings
*/
async function loadSettings() {
// Load settings
window.settings = (await browser.storage.local.get("settings")).settings;
// Set default settings values if necessary
if (!window.settings) {
window.settings = {
debug_mode: false,
multiple_filters: true,
};
}
}
/*******************************************************************************
* Event handlers and Message Listeners
******************************************************************************/
/***
* Called when a tab gets "updated." Most importantly, this includes when a
* user clicks a link.
*/
function handleTabUpdated(tabId, changeInfo, tab) {
// Only submit URLs of pages that have completed loading
if (!("status" in changeInfo && changeInfo.status === "complete")) {
return;
}
// Ignore built-in Firefox "about:" pages and local files
var tab_url = new URL(tab.url);
if (tab_url.protocol === "about:" || tab_url.protocol === "file:") {
deactivateBadge(tabId);
return;
}
let scoreLabels = window.filters
.filter(f => inBloom(f, tab_url.toString()))
.map(f => f.threshold);
if (scoreLabels.length == 0) {
deactivateBadge(tab.id);
return;
}
let score = scoreLabels.reduce((a, b) => Math.max(a, b));
// TODO: Add bloom filter results to the tablist
activateBadge({points: (score ? `${score}+` : "")}, tabId);
return;
}
/***
* Open the Hacker News Discussion when the action is clicked. Do it in a new
* Window if the Shift key is pressed when the click happens. If any other
* modifier keys or the middle mouse button are clicked, open in a new tab.
* Otherwise, open in the current tab.
*/
function handleActionClicked(tab, onClickData) {
// Algolia doesn't work well with URLs like:
// https://www.youtube.com/watch?v=-pdSjBPH3zM
// I suspect the "=-" leads to treating "-" as an exclusion operator somehow
// https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax
let tab_url = encodeURIComponent(canonicalizeUrl(tab.url).replace("=-", "="));
// Only get the discussion URL if the button is clicked by the user
fetch(`https://hn.algolia.com/api/v1/search?tags=story&query=${tab_url}`)
.then(data => data.json())
.then(json => {
// Filter only those search results that match on the domain of the
// current page - approximate, but mostly works
let stories = Array.from(json.hits).filter(hit => {
if (!hit || !hit.url) return false;
try {
var hit_url = new URL(hit.url);
} catch (err) {
console.error("Opening Hacker News discussion failed on " + hit.url);
return false;
}
let url = new URL(tab.url);
// Return true if the hosts match and neither path is /, or if the hosts
// match and both paths are /.
//
// Fixes problems where Algolia doesn't return a result for the exact
// page if a top-level URL is used to search. For example, without
// this, using the extension on https://github.com/ returns a result
// for a GitHub blog post, not the post using the GitHub homepage as
// the story URL
//
// TODO: Match exact path?
return ((url.host === hit_url.host || url.host === "web.archive.org")
&& ((url.pathname === "/" && hit_url.pathname === "/")
|| (url.pathname !== "/" && hit_url.pathname !== "/")));
});
// If a story matched, go to the discussion for the one Algolia picked as
// the "top" result
if (stories.length > 0) {
let hn_id = stories[0].objectID;
let hn_url = `https://news.ycombinator.com/item?id=${hn_id}`;
if (onClickData.button == 0 && onClickData.modifiers.length == 0) {
browser.tabs.update(tab.id, {url: hn_url});
} else if (onClickData.modifiers.includes("Shift")) {
browser.windows.create({url: hn_url});
} else {
browser.tabs.create({url: hn_url});
}
return;
}
deactivateBadge(tab.id);
})
.catch(console.error);
}
/***
* Add Hacker News story URLs from browsed pages to the Bloom filter. Re-adding
* URLs that are already there doesn't cost much, nor does it cause harm, so we
* don't even bother detecting it.
*
* This function is called when a content script runs on news.ycombinator.com
* and posts a message with the URLs to add.
*/
function addLatest(message) {
if (message.type != "add_stories") {
return;
}
for (let i = 0; i < window.filters.length; i++) {
f = window.filters[i];
message.stories
.filter(u => u.score >= f.threshold)
.forEach(u => addBloom(f, u.url));
}
// Save the updated Bloom filter
// TODO: Maybe re-enable this someday? Still it takes a couple seconds of
// fully blocking the process to store ~80MB of data.
/*
storeBloom(window.filters)
.catch(e => console.error(e));
*/
}
/***
* Reload the settings from storage.
*
* Triggered by a message sent from options.html.
*/
async function reloadSettings(message) {
if (message.type != "reload_settings") {
return;
}
await loadSettings();
}
/***
* Delete the stored Bloom filter and delete the in-memory Bloom filter. Then
* reload them all.
*/
async function resetBloom(message) {
if (message.type != "reset_bloom") {
return;
}
await deleteStoredBloom();
window.filters.forEach(f => freeBloom(f));
await loadBloom();
}
/*******************************************************************************
* Main function called on browser startup or extension load
******************************************************************************/
/***
* Main procedure function, called on extension initialization
*/
(async () => {
// TODO: Remove, or uncomment if the tablist is used again
// browser.tabs.onRemoved.addListener(tabId => delete tabs[tabId]);
await loadSettings();
// Set up event listeners
browser.tabs.onUpdated.addListener(handleTabUpdated);
browser.browserAction.onClicked.addListener(handleActionClicked);
browser.commands.onCommand.addListener(command => {
if (command === "open_in_new_tab") {
browser.tabs.query({active: true, currentWindow: true})
.then(tabs => handleActionClicked(tabs[0], {button: 1, modifiers: []}));
}
});
// Set up message listeners
browser.runtime.onMessage.addListener(addLatest);
browser.runtime.onMessage.addListener(reloadSettings);
browser.runtime.onMessage.addListener(resetBloom);
// Every 10 minutes, check if the Bloom filter is outdated, and update if so
setInterval(updateBloom, 10 * 60 * 1000);
// Style the browser action button
browser.browserAction.disable();
browser.browserAction.setBadgeText({text: ""});
browser.browserAction.setBadgeBackgroundColor({color: "#f0652f"});
// Will not run in Chrome
if (browser.browserAction.setBadgeTextColor) {
browser.browserAction.setBadgeTextColor({color: "white"});
}
})();