-
Notifications
You must be signed in to change notification settings - Fork 62
/
background-script.js
396 lines (333 loc) · 10.6 KB
/
background-script.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
async function getCurrentTab() {
// Get active tabs in current window
var tabs = await browser.tabs.query({
currentWindow: true,
active: true,
});
if (tabs.length < 1) {
throw new Error("no tab available");
}
// Make sure URL protocol supported
var supportedProtocols = ["https:", "http:", "ftp:", "file:"],
activeTab = tabs[0],
url = document.createElement('a');
if (activeTab.url !== "") {
url.href = activeTab.url;
if (supportedProtocols.indexOf(url.protocol) === -1) {
throw new Error(`protocol "${url.protocol}" is not supported`);
}
}
return activeTab;
}
async function getPageContent(tab) {
try {
var content = await browser.tabs.sendMessage(tab.id, {type: "page-content"});
return content;
} catch {
return {};
}
}
async function getShioriBookmarkFolder() {
// TODO:
// I'm not sure it's the most efficient way, but it's the simplest.
// We want to put Shiori folder in `Other bookmarks`, which id different depending on browser.
// In Firefox, its id is `unfiled_____` while in Chrome the id is `2`.
var parentId = "",
runtimeUrl = await browser.runtime.getURL("/");
if (runtimeUrl.startsWith("moz")) {
parentId = "unfiled_____";
} else if (runtimeUrl.startsWith("chrome")) {
parentId = "2";
} else {
throw new Error("right now extension only support firefox and chrome")
}
// Check if the parent folder already has Shiori folder
var children = await browser.bookmarks.getChildren(parentId),
shiori = children.find(el => el.url == null && el.title === "Shiori");
if (!shiori) {
shiori = await browser.bookmarks.create({
title: "Shiori",
parentId: parentId
});
}
return shiori;
}
async function findLocalBookmark(url) {
var shioriFolder = await getShioriBookmarkFolder(),
existingBookmarks = await browser.bookmarks.search({
url: url,
});
var idx = existingBookmarks.findIndex(book => {
return book.parentId === shioriFolder.id;
});
if (idx >= 0) {
return existingBookmarks[idx];
} else {
return null;
}
}
async function saveLocalBookmark(url, title) {
var shioriFolder = await getShioriBookmarkFolder(),
existingBookmarks = await browser.bookmarks.search({
url: url,
});
var idx = existingBookmarks.findIndex(book => {
return book.parentId === shioriFolder.id;
});
if (idx === -1) {
await browser.bookmarks.create({
url: url,
title: title,
parentId: shioriFolder.id,
});
}
return Promise.resolve();
}
async function removeLocalBookmark(url) {
var shioriFolder = await getShioriBookmarkFolder(),
existingBookmarks = await browser.bookmarks.search({
url: url,
});
existingBookmarks.forEach(book => {
if (book.parentId !== shioriFolder.id) return;
browser.bookmarks.remove(book.id);
});
return Promise.resolve();
}
async function getExtensionConfig() {
var items = await browser.storage.local.get(),
token = items.token || "",
server = items.server || "";
if (token === "") {
throw new Error("no active session, please login first");
}
if (server === "") {
throw new Error("server url is not specified");
}
return {
token: token,
server: server
};
}
async function openLibraries() {
var config = await getExtensionConfig();
return browser.tabs.create({
active: true,
url: config.server,
});
}
async function removeBookmark() {
var tab = await getCurrentTab(),
config = await getExtensionConfig();
// Create API URL
var apiURL = "";
try {
var api = new URL(config.server);
if (api.pathname.slice(-1) == "/") {
api.pathname = api.pathname + "api/bookmarks/ext";
} else {
api.pathname = api.pathname + "/api/bookmarks/ext";
}
apiURL = api.toString();
} catch(err) {
throw new Error(`${config.server} is not a valid url`);
}
// Send request via background script
var response = await fetch(apiURL, {
method: "delete",
body: JSON.stringify({url: tab.url}),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${config.token}`,
}
});
if (!response.ok) {
var err = await response.text();
throw new Error(err);
}
// Remove local bookmark
await removeLocalBookmark(tab.url);
return Promise.resolve();
}
async function saveBookmark(tags) {
// Get value from async function
var tab = await getCurrentTab(),
config = await getExtensionConfig(),
content = await getPageContent(tab);
// Create API URL
var apiURL = "";
try {
var api = new URL(config.server);
if (api.pathname.slice(-1) == "/") {
api.pathname = api.pathname + "api/bookmarks/ext";
} else {
api.pathname = api.pathname + "/api/bookmarks/ext";
}
apiURL = api.toString();
} catch(err) {
throw new Error(`${config.server} is not a valid url`);
}
// Send request via background script
var data = {
url: tab.url,
tags: tags,
html: content.html || "",
}
var response = await fetch(apiURL, {
method: "post",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${config.token}`,
}
});
if (!response.ok) {
var err = await response.text();
throw new Error(err);
}
// Save to local bookmark
var pageTitle = content.title || tab.title;
await saveLocalBookmark(tab.url, pageTitle);
return Promise.resolve();
}
async function updateIcon() {
// Determine the colour scheme for the icons
var colourScheme = getDarkModeEnabled() ? "light" : "default";
// Set initial icon
var runtimeUrl = await browser.runtime.getURL("/"),
icon = {path: {
16: `icons/action-${colourScheme}-16.png`,
32: `icons/action-${colourScheme}-32.png`,
64: `icons/action-${colourScheme}-64.png`
}};
// Firefox allows using empty object as default icon.
// This way, Firefox will use default_icon that defined in manifest.json
if (runtimeUrl.startsWith("moz")) {
icon = {};
}
// Get current active tab
try {
var tab = await getCurrentTab(),
local = await findLocalBookmark(tab.url);
if (local) icon.path = {
16: "icons/action-bookmarked-16.png",
32: "icons/action-bookmarked-32.png",
64: "icons/action-bookmarked-64.png"
}
} catch {}
return browser.browserAction.setIcon(icon);
}
// Define event handler
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
var task = Promise.resolve();
switch (request.type) {
case "open-libraries":
task = new Promise((resolve, reject) => {
openLibraries()
.then(() => { resolve() })
.catch(err => { reject(err) });
});
break;
case "remove-bookmark":
task = new Promise((resolve, reject) => {
removeBookmark()
.then(() => { resolve() })
.catch(err => { reject(err) });
});
break;
case "save-bookmark":
task = new Promise((resolve, reject) => {
saveBookmark(request.tags)
.then(() => { resolve() })
.catch(err => { reject(err) });
});
break;
}
return task;
});
// Check if dark mode is enabled
function getDarkModeEnabled() {
return window.matchMedia("(prefers-color-scheme: dark)").matches || false;
}
// Add handler for icon change
function updateActiveTab() {
updateIcon().catch(err => console.error(err.message));
}
browser.bookmarks.onCreated.addListener(updateActiveTab);
browser.bookmarks.onRemoved.addListener(updateActiveTab);
browser.tabs.onUpdated.addListener(updateActiveTab);
browser.tabs.onActivated.addListener(updateActiveTab);
browser.windows.onFocusChanged.addListener(updateActiveTab);
updateActiveTab();
if (browser.omnibox) {
browser.omnibox.setDefaultSuggestion({
description: 'Search for stored bookmarks'
});
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
var data = text.split(" ").reduce((prev, curr) => {
if (curr[0] == "#") {
return { ...prev, tags: [...prev.tags, curr.substring(1)] }
}
if (curr[0] == "!") {
return { ...prev, excludedTags: [...prev.excludedTags, curr.substring(1)] }
}
return { ...prev, keyword: [prev.keyword, curr].join(" ") }
}, { tags: [], excludedTags: [], keyword: "" });
return retreiveBookmarks(data.tags, data.excludedTags, data.keyword)
.then(addSuggestions)
});
async function retreiveBookmarks(tags, excludedTags, keyword) {
var tagValue = tags.join(",")
var excludedTagValue = excludedTags.join(",")
var config = await getExtensionConfig();
// Create API URL
var apiURL = "";
try {
var api = new URL(config.server);
if (api.pathname.slice(-1) == "/") {
api.pathname = api.pathname + "api/bookmarks";
} else {
api.pathname = api.pathname + "/api/bookmarks";
}
api.searchParams.set("keyword", keyword)
api.searchParams.set("tags", tagValue)
api.searchParams.set("exclude", excludedTagValue)
apiURL = api.toString();
} catch (err) {
throw new Error(`${config.server} is not a valid url`);
}
var response = await fetch(apiURL, {
method: "GET",
headers: {
"Content-Type": "application/json",
"X-Session-Id": config.session,
}
});
if (!response.ok) {
var err = await response.text();
throw new Error(err);
}
return response.json()
.then(v => {
return v.bookmarks.map(b => ({
content: b.url,
description: b.title
}))
}
);
}
browser.omnibox.onInputEntered.addListener((text, disposition) => {
let url = text;
switch (disposition) {
case "currentTab":
browser.tabs.update({ url });
break;
case "newForegroundTab":
browser.tabs.create({ url });
break;
case "newBackgroundTab":
browser.tabs.create({ url, active: false });
break;
}
});
}