-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbackground.js
More file actions
452 lines (370 loc) · 14.6 KB
/
Copy pathbackground.js
File metadata and controls
452 lines (370 loc) · 14.6 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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
async function init() {
await loadUserSettings();
logToDebugConsole("init");
loadContextMenus();
// Delay preloading of bookmarks a bit more
setTimeout(loadBrowserActionGroups, 1500);
// Watch for when the user clicks on the browser action
browser.browserAction.onClicked.addListener(handleBrowserClickAction);
// Watch for when the storage/settings are changed
browser.storage.onChanged.addListener(handleStorageChangeAction);
// Watch for when the user clicks on the context menu
browser.menus.onClicked.addListener(handleMenuClickAction);
// Watch when user changes their bookmarks.
browser.bookmarks.onCreated.addListener(handleBookmarksCreatedAction);
// Don't need to refresh on edit anymore as i'm using the ID instead
// browser.bookmarks.onChanged.addListener(handleBookmarksChangedAction);
browser.bookmarks.onMoved.addListener(handleBookmarksMovedAction);
browser.bookmarks.onRemoved.addListener(handleBookmarksRemovedAction);
// Watch for when a new tab is created
browser.tabs.onCreated.addListener(handleNewTabAction);
if (localStorage.getItem("randomized-history") !== null) {
localStorage.removeItem("randomized-history");
}
}
function showNotification(title, msg) {
logToDebugConsole("showNotification");
browser.notifications.create("random-bookmark-notification", {
type: "basic",
iconUrl: browser.runtime.getURL("icons/icon-96.png"),
title: title,
message: msg,
});
}
async function handleBrowserClickAction(tabInfo) {
logToDebugConsole("handleBrowserClickAction");
if (pluginSettings.initialLoading || pluginSettings.loadingBookmarks || pluginSettings.loadingGroups) {
showNotification("Loading Your Bookmarks", "Sorry, please wait a moment while your bookmarks are preloaded. If this pop up keeps showing up after a minute, please go to the options page and scroll to the bottom and clear out all add-on data, and then reinstall the plugin. Sorry.");
if (sessionInfo.loadingDateTimeStarted !== null) {
const currentDate = new Date();
const seconds = (currentDate.getTime() - sessionInfo.loadingDateTimeStarted) / 1000;
if (seconds >= 30) {
// Try reloading bookmarks again
preloadBookmarksIntoLocalStorage("handleBrowserClickAction");
}
}
} else {
logToDebugConsole("pluginSettings.selectedGroup", pluginSettings.selectedGroup);
const resBookmarks = await browser.storage.local.get(pluginSettings.selectedGroup);
// resBookmarks is the array of bookmarks for the groups
if (resBookmarks[pluginSettings.selectedGroup].length === 0) {
showNotification("No bookmarks found", "Start adding bookmarks first or check the add-on settings");
} else {
const bookmarkInfo = await getRandomBookmark(resBookmarks);
console.log("bookmarkInfo", bookmarkInfo);
openBookmarks(bookmarkInfo, false, tabInfo);
}
}
}
async function getRandomBookmark(resBookmarks) {
logToDebugConsole("getRandomBookmark");
if (pluginSettings.randomOption === "bybookmark" || pluginSettings.randomOption === "alphabetical") {
const groupIndexName = pluginSettings.selectedGroup + "_index";
// Get the current group index
const resIndex = await browser.storage.local.get(groupIndexName);
let groupIndex = 0;
if (Number.isInteger(resIndex[groupIndexName])) {
groupIndex = resIndex[groupIndexName];
}
// Get the bookmark
const bookmarkId = resBookmarks[pluginSettings.selectedGroup][groupIndex];
try {
const bookmarkInfo = await browser.bookmarks.get(bookmarkId);
// Set the index for when the user presses the button again
groupIndex = groupIndex + 1;
if (groupIndex >= resBookmarks[pluginSettings.selectedGroup].length) {
// Hit the limit, recache the group
groupIndex = 0;
handleTheBookmarks("reachedTheEnd");
}
browser.storage.local.set({
[groupIndexName]: groupIndex,
});
return bookmarkInfo;
} catch (bookmarkError) {
showNotification("Bookmark Not Found", "You must have deleted a bookmark, could not find this one.");
throw new Error("Bookmark not found: " + bookmarkError.message);
}
} else {
// Get a random index
let randomIndex = 0;
if (resBookmarks[pluginSettings.selectedGroup].length > 1) {
randomIndex = Math.floor(Math.random() * resBookmarks[pluginSettings.selectedGroup].length);
}
const bookmarkId = resBookmarks[pluginSettings.selectedGroup][randomIndex];
try {
return await browser.bookmarks.get(bookmarkId);
} catch (bookmarkError) {
showNotification("Bookmark Not Found", "You must have deleted a bookmark, could not find this one.");
throw new Error("Bookmark not found: " + bookmarkError.message);
}
}
}
async function handleNewTabAction(tabInfo) {
logToDebugConsole("handleNewTabAction", tabInfo);
if (pluginSettings.randomizeNewTab === false) {
return;
}
// Skip if opened from a link
if (tabInfo.openerTabId !== undefined) {
return;
}
// Use (|| tabInfo.url === "about:blank")
// if we want to also do it on new window
if (tabInfo.title === "New Tab" && tabInfo.url === "about:newtab") {
const resBookmarks = await browser.storage.local.get(pluginSettings.selectedGroup);
// Set the URL for the newly created tab
const bookmarkInfo = await getRandomBookmark(resBookmarks);
openBookmarks(bookmarkInfo, false, tabInfo, true);
}
}
function handleMenuClickAction(info, tab) {
logToDebugConsole("handleMenuClickAction", info, tab);
if (info.menuItemId.toString() === "options-page") {
// Load up the options
logToDebugConsole("Open the options page");
browser.runtime.openOptionsPage();
} else if (info.menuItemId.toString() === "plugin-page") {
// Go to the mozilla browser plugin page
logToDebugConsole("Open plugin page");
browser.tabs.create({
url: "https://addons.mozilla.org/en-US/firefox/addon/random-bookmark-addon/",
active: true,
});
} else if (info.menuItemId.toString() === "refresh-cache") {
// Force refresh of the cache
logToDebugConsole("Force refresh of cache");
handleTheBookmarks("manuallyRefreshCache");
} else if (info.menuItemId.toString() === "last-bookmark-path") {
// user clicked on last bookmark path, dont do anything currently. Maybe open the url again?
} else if (tab === undefined) {
// Context click, the user wants to load up a random bookmark from a folder
let bookmarksToOpen = 1;
if (info.menuItemId.startsWith("open-random")) {
bookmarksToOpen = parseInt(info.menuItemId.replace("open-random-", ""), 10);
}
const getBookmarkInfo = browser.bookmarks.get(info.bookmarkId);
getBookmarkInfo.then(function (bookmarkInfo) {
let folderID = "";
if (bookmarkInfo[0].type === "folder") {
folderID = bookmarkInfo[0].id;
} else if (bookmarkInfo[0].type === "bookmark") {
folderID = bookmarkInfo[0].parentId;
}
const gettingChildren = browser.bookmarks.getChildren(folderID);
gettingChildren.then(function (children) {
const folderBookmarks = [];
for (const child of children) {
if (child.type === "bookmark") {
folderBookmarks.push(child.id);
}
}
if (folderBookmarks.length > 0) {
Shuffle(folderBookmarks);
const toOpen = folderBookmarks.slice(0, bookmarksToOpen);
logToDebugConsole("toOpen", toOpen);
browser.bookmarks.get(toOpen).then((result) => {
openBookmarks(result, true);
});
} else {
showNotification("Random Bookmark Alert", "No bookmarks found in this folder, this does not look in child folders, only the current folder.");
}
});
});
} else if (pluginSettings.loadingBookmarks) {
// Reload the context menus because I don't know how else to reselect the previous selected menu
loadBrowserActionGroups();
showNotification("Loading Your Bookmarks", "Sorry, please wait a moment while your bookmarks are preloaded.");
} else {
if (pluginSettings.selectedGroup !== info.menuItemId.toString()) {
preloadBookmarksIntoLocalStorage("handleMenuClickAction");
}
// User changed the selected category
pluginSettings.selectedGroup = info.menuItemId.toString();
browser.storage.local.set({
activeGroup: info.menuItemId,
});
}
}
async function handleStorageChangeAction(changes, area) {
logToDebugConsole("handleStorageChangeAction", { changes: changes, area: area });
if (area === "sync") {
await loadUserSettings();
loadContextMenus();
if (changes.groups) {
loadBrowserActionGroups();
}
}
}
function handleBookmarksCreatedAction() {
if (pluginSettings.disableAutomaticRefresh === false) {
logToDebugConsole("handleBookmarksCreatedAction");
handleTheBookmarks("handleBookmarksCreatedAction");
}
}
function handleBookmarksMovedAction() {
if (pluginSettings.disableAutomaticRefresh === false) {
logToDebugConsole("handleBookmarksMovedAction");
handleTheBookmarks("handleBookmarksMovedAction");
}
}
function handleBookmarksRemovedAction() {
if (pluginSettings.disableAutomaticRefresh === false) {
logToDebugConsole("handleBookmarksRemovedAction");
handleTheBookmarks("handleBookmarksRemovedAction");
}
}
function handleBookmarksChangedAction(id, changeInfo) {
if (pluginSettings.disableAutomaticRefresh === false) {
logToDebugConsole("handleBookmarksChangedAction", { id: id, changeInfo: changeInfo });
handleTheBookmarks("handleBookmarksChangedAction");
}
}
function handleTheBookmarks(source) {
logToDebugConsole("handleTheBookmarks", { source: source });
// Bookmarks was changed (added/deleted)
// Set all bookmark groups to reload
const userSyncOptions = browser.storage.sync.get();
userSyncOptions.then((syncRes) => {
logToDebugConsole("handleTheBookmarks", { syncRes: syncRes });
if (syncRes.groups) {
const bookmarkGroups = syncRes.groups;
for (let i = 0; i < bookmarkGroups.length; i++) {
// Force reload of bookmarks in storage
bookmarkGroups[i].reload = true;
// Reset the selected group index back to zero
const groupIndexName = bookmarkGroups[i].id + "_index";
browser.storage.local.set({
[groupIndexName]: 0,
});
}
browser.storage.sync.set({
groups: bookmarkGroups,
});
preloadBookmarksIntoLocalStorage("handleTheBookmarks");
}
});
}
/**
* The main function to handle the opening of a bookmark.
* Used by when the user clicks on the context menu or the browser action button
*
* @param array bookmarks
* @param boolean forceNewTab
* @param object tabInfo
*/
async function openBookmarks(bookmarks, forceNewTab = false, tabInfo = null, useTabInfoIfExists = false) {
logToDebugConsole("openBookmarks");
for (const [index, bookmark] of bookmarks.entries()) {
logToDebugConsole("bookmark", bookmark);
await processHistory(bookmark);
await openBookmark(bookmark, index, forceNewTab, tabInfo, useTabInfoIfExists);
}
}
async function openBookmark(bookmark, index, forceNewTab, tabInfo, useTabInfoIfExists) {
if (bookmark.url.startsWith("file:///")) {
showNotification("Cannot open local file", "Sorry, local files being opened are blocked by FireFox currently.");
return;
}
if (useTabInfoIfExists && tabInfo) {
await updateTabUrl(tabInfo.id, bookmark.url, true);
} else if (forceNewTab) {
await createNewTab(bookmark.url, index === 0);
} else {
await handleTabStrategy(bookmark, tabInfo);
}
}
async function handleTabStrategy(bookmark, tabInfo) {
if (pluginSettings.tabOption === "newTab") {
await createNewTab(bookmark.url, pluginSettings.tabSetActive);
} else if (pluginSettings.tabOption === "currentTab" && tabInfo) {
await updateTabUrl(tabInfo.id, bookmark.url, pluginSettings.tabSetActive);
} else {
await handleSessionTab(bookmark);
}
}
async function handleSessionTab(bookmark) {
if (sessionInfo.currentTabId === 0) {
const newTab = await browser.tabs.create({
active: pluginSettings.tabSetActive,
url: bookmark.url,
});
sessionInfo.currentTabId = newTab.id;
return;
}
try {
const tab = await browser.tabs.get(sessionInfo.currentTabId);
logToDebugConsole("tab", tab);
await updateTabUrl(tab.id, bookmark.url, pluginSettings.tabSetActive);
if (pluginSettings.tabSetActive) {
await browser.windows.update(tab.windowId, { focused: true });
}
sessionInfo.currentTabId = tab.id;
} catch (error) {
logToDebugConsole("failed", error);
const newTab = await browser.tabs.create({
active: pluginSettings.tabSetActive,
url: bookmark.url,
});
sessionInfo.currentTabId = newTab.id;
}
}
async function createNewTab(url, active) {
return browser.tabs.create({ active, url });
}
async function updateTabUrl(tabId, url, active) {
return browser.tabs.update(tabId, {
active,
highlighted: active,
url,
});
}
async function processHistory(bookmark) {
const path = await getBookmarkPath(bookmark.id);
// Update the menu with the path of the last randomized bookmark
browser.menus.update("last-bookmark-path", {
title: path,
visible: true,
});
// If enabled, save to local storage
if (pluginSettings.randomizeHistory) {
logToDebugConsole("Save history");
const storageCollection = await browser.storage.local.get("randomized-history");
const historyCollection = storageCollection.hasOwnProperty("randomized-history") ? JSON.parse(storageCollection["randomized-history"]) : [];
historyCollection.unshift({
bookmark,
dateRandomized: new Date().toISOString(),
});
if (historyCollection.length > pluginSettings.maxHistory) {
historyCollection.pop();
}
logToDebugConsole("historyCollection", historyCollection);
browser.storage.local.set({
"randomized-history": JSON.stringify(historyCollection),
});
}
}
/**
* Lets get this party started
*/
document.addEventListener("DOMContentLoaded", init);
/**
* Runs when the user installs the add-on
*/
browser.runtime.onInstalled.addListener(async ({ reason, temporary }) => {
if (temporary) {
console.log("-------------------------------------------------------------------------------------------");
console.log("DEBUGGING RANDOM BOOKMARK");
console.log("-------------------------------------------------------------------------------------------");
pluginSettings.isDebugging = true;
}
switch (reason) {
case "install":
browser.runtime.openOptionsPage();
break;
case "update":
// We've updated how we're updating the bookmarks, just force restore of localstorage.
handleTheBookmarks("pluginupdated");
break;
}
});